@vouchfor/embeds 0.0.0-experiment.bb1a5cf → 0.0.0-experiment.e828084

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,7 +1,7 @@
1
- var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,Yt)=>Et in nt?Am(nt,Et,{enumerable:!0,configurable:!0,writable:!0,value:Yt}):nt[Et]=Yt;var kc=(nt,Et,Yt)=>(bm(nt,typeof Et!="symbol"?Et+"":Et,Yt),Yt);function Et(r,e){for(var t=0;t<e.length;t++){const i=e[t];if(typeof i!="string"&&!Array.isArray(i)){for(const s in i)if(s!=="default"&&!(s in r)){const n=Object.getOwnPropertyDescriptor(i,s);n&&Object.defineProperty(r,s,n.get?n:{enumerable:!0,get:()=>i[s]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}function Yt({canvas:r,scenes:e,currentTime:t,transitionDuration:i}){if(e&&r){const s=e.filter(({start:o,duration:a})=>t>=o&&t<=o+a);if(s.length<=0)return;const n=r.getContext("2d");if(n){const o=Math.max(...e.map(({start:a,duration:l})=>a+l));n.globalCompositeOperation="lighter",n.clearRect(0,0,r.width,r.height),s.forEach(({start:a,duration:l,draw:c,transitionCanvas:d})=>{n.globalAlpha=1,d.width=d.height=0,d.width=r.width,d.height=r.height;const h=d.getContext("2d");if(h){const u=a+l,f=a===0,g=u===o;c.forEach(p=>{p({currentTime:t,canvas:d,context:h})}),!f&&t>=a&&t<=a+i/2?n.globalAlpha=Math.max(0,Math.min(1,(t-a)/(i/2))):!g&&t>=u-i/2&&t<=u&&(n.globalAlpha=Math.max(0,Math.min(1,(u-t)/(i/2)))),n.drawImage(d,0,0,r.width,r.height)}})}}}async function St(){if(typeof window>"u"){const r=await Promise.resolve().then(()=>Rc);return new r.Canvas}return document.createElement("canvas")}function Pc(r){if(typeof r=="string"){const[e,t]=r.split(":");return Math.min(parseFloat(e),parseFloat(t))}return r}function Oc(r){if(typeof r=="string"){const[e,t]=r.split(":"),i=parseFloat(e),s=parseFloat(t);return i/s}return r}function Mi({resolution:r,aspectRatio:e}){const t=Pc(r),i=Oc(e),s=i>=1,n=Math.min(s?t*i:t/i,t),o=Math.max(s?t*i:t/i,t);return{resolution:t,aspectRatio:i,height:s?n:o,width:s?o:n}}function Mc({format:r,resolution:e,aspectRatio:t,videoResolution:i,videoAspectRatio:s}){const{height:n,width:o}=Mi({resolution:e,aspectRatio:t}),{height:a,width:l}=Mi({resolution:i,aspectRatio:s}),c=t>s;let d=1;if(r==="letterbox"||r==="letterbox-video")d=c?n/a:o/l;else if(r==="squarebox"){const p=Math.min(n,o);d=l>=a?p/a:p/l}else(r==="crop"||r==="crop-top")&&(d=c?o/l:n/a);const h=o/d,u=n/d,f=(l-h)/2;let g=(a-u)/2;return r==="crop-top"&&(g=Math.min(0,g)),{sx:f,sy:g,sWidth:h,sHeight:u,scale:d}}function us({source:r,sx:e,sy:t,sw:i,sh:s,dx:n,dy:o,dw:a,dh:l}){const c=(r==null?void 0:r.naturalWidth)??(r==null?void 0:r.videoWidth)??(r==null?void 0:r.width),d=(r==null?void 0:r.naturalHeight)??(r==null?void 0:r.videoHeight)??(r==null?void 0:r.height);e=e??0,t=t??0,i=i??c,s=s??d,i<0&&(e+=i,i=Math.abs(i)),s<0&&(t+=s,s=Math.abs(s)),a<0&&(n+=a,a=Math.abs(a)),l<0&&(o+=l,l=Math.abs(l));const h=Math.max(e,0),u=Math.min(e+i,c),f=Math.max(t,0),g=Math.min(t+s,d),p=a/i,m=l/s;return[r,h,f,u-h,g-f,e<0?n-e*p:n,t<0?o-t*m:o,(u-h)*p,(g-f)*m]}function Fc({context:r,source:e,format:t="letterbox",videoResolution:i,videoAspectRatio:s,posX:n,posY:o,width:a,height:l,offscreenCanvas:c}){const{sx:d,sy:h,sWidth:u,sHeight:f,scale:g}=Mc({resolution:Math.min(a,l),aspectRatio:a/l,format:t,videoResolution:i,videoAspectRatio:s}),p=c&&typeof r.filter<"u";if(t==="letterbox"||t==="squarebox"||t==="letterbox-video"&&!p){if(d<0){const y=Math.abs(d)*g;r.fillStyle="black",r.beginPath(),r.rect(n,o,y,l),r.rect(n+a-y,o,y,l),r.fill(),r.closePath()}if(h<0){const y=Math.abs(h)*g;r.fillStyle="black",r.beginPath(),r.rect(n,o,a,y),r.rect(n,o+l-y,a,y),r.fill(),r.closePath()}}if(t==="letterbox-video"&&p){const{width:y,height:x}=Mi({resolution:i,aspectRatio:s});c.width=y,c.height=x;const E=c.getContext("2d",{alpha:!1});if(E==null||E.drawImage(e,0,0,y,x),E){r.save(),r.globalCompositeOperation="destination-out",r.fillRect(n,o,a,l);const S=us({source:c,sx:d,sy:h,sw:u,sh:f,dx:n,dy:o,dw:a,dh:l});r.globalCompositeOperation="source-over",r.drawImage(...S),E.save();const R=1.3,w=-(y*R-y)/2,I=-(x*R-x)/2;if(E.filter="blur(40px) brightness(20%)",E.translate(w,I),E.scale(R,R),E.drawImage(c,0,0,y,x),E.restore(),r.globalCompositeOperation="destination-over",d<0){const O=a/s,P=l/O,B=us({source:c,sy:(1-P)*x/2,sh:P*x,dx:n,dy:o,dw:a,dh:l});r.drawImage(...B)}if(h<0){const O=l*s,P=a/O,B=us({source:c,sx:(1-P)*y/2,sw:P*y,dx:n,dy:o,dw:a,dh:l});r.drawImage(...B)}r.restore()}}else{const y=us({source:e,sx:d,sy:h,sw:u,sh:f,dx:n,dy:o,dw:a,dh:l});r.drawImage(...y)}const m=d*-1*g,A=h*-1*g,T=a-m*2,b=l-A*2;return{dx:m,dy:A,dw:T,dh:b}}const Nc=/\d{0,2}:?\d{2}:\d{2}\.\d{3}\s-->\s\d{0,2}:?\d{2}:\d{2}\.\d{3}\s{1,2}.*/g,Bc=/\d{0,2}:?\d{2}:\d{2}\.\d{3}/g;function to(r){if(!r)return[];const e=r.match(Nc);return e?e==null?void 0:e.map(t=>{const[i,s]=t.replace(`\r
1
+ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,Yt)=>Et in nt?Am(nt,Et,{enumerable:!0,configurable:!0,writable:!0,value:Yt}):nt[Et]=Yt;var kc=(nt,Et,Yt)=>(bm(nt,typeof Et!="symbol"?Et+"":Et,Yt),Yt);function Et(r,e){for(var t=0;t<e.length;t++){const i=e[t];if(typeof i!="string"&&!Array.isArray(i)){for(const s in i)if(s!=="default"&&!(s in r)){const n=Object.getOwnPropertyDescriptor(i,s);n&&Object.defineProperty(r,s,n.get?n:{enumerable:!0,get:()=>i[s]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}function Yt({canvas:r,scenes:e,currentTime:t,transitionDuration:i}){if(e&&r){const s=e.filter(({start:o,duration:a})=>t>=o&&t<=o+a);if(s.length<=0)return;const n=r.getContext("2d");if(n){const o=Math.max(...e.map(({start:a,duration:l})=>a+l));n.globalCompositeOperation="lighter",n.clearRect(0,0,r.width,r.height),s.forEach(({start:a,duration:l,draw:c,transitionCanvas:d})=>{n.globalAlpha=1,d.width=d.height=0,d.width=r.width,d.height=r.height;const h=d.getContext("2d");if(h){const u=a+l,f=a===0,g=u===o;c.forEach(p=>{p({currentTime:t,canvas:d,context:h})}),!f&&t>=a&&t<=a+i/2?n.globalAlpha=Math.max(0,Math.min(1,(t-a)/(i/2))):!g&&t>=u-i/2&&t<=u&&(n.globalAlpha=Math.max(0,Math.min(1,(u-t)/(i/2)))),n.drawImage(d,0,0,r.width,r.height)}})}}}async function St(){if(typeof window>"u"){const r=await Promise.resolve().then(()=>Rc);return new r.Canvas}return document.createElement("canvas")}function Pc(r){if(typeof r=="string"){const[e,t]=r.split(":");return Math.min(parseFloat(e),parseFloat(t))}return r}function Oc(r){if(typeof r=="string"){const[e,t]=r.split(":"),i=parseFloat(e),s=parseFloat(t);return i/s}return r}function Fi({resolution:r,aspectRatio:e}){const t=Pc(r),i=Oc(e),s=i>=1,n=Math.min(s?t*i:t/i,t),o=Math.max(s?t*i:t/i,t);return{resolution:t,aspectRatio:i,height:s?n:o,width:s?o:n}}function Mc({format:r,resolution:e,aspectRatio:t,videoResolution:i,videoAspectRatio:s}){const{height:n,width:o}=Fi({resolution:e,aspectRatio:t}),{height:a,width:l}=Fi({resolution:i,aspectRatio:s}),c=t>s;let d=1;if(r==="letterbox"||r==="letterbox-video")d=c?n/a:o/l;else if(r==="squarebox"){const p=Math.min(n,o);d=l>=a?p/a:p/l}else(r==="crop"||r==="crop-top")&&(d=c?o/l:n/a);const h=o/d,u=n/d,f=(l-h)/2;let g=(a-u)/2;return r==="crop-top"&&(g=Math.min(0,g)),{sx:f,sy:g,sWidth:h,sHeight:u,scale:d}}function us({source:r,sx:e,sy:t,sw:i,sh:s,dx:n,dy:o,dw:a,dh:l}){const c=(r==null?void 0:r.naturalWidth)??(r==null?void 0:r.videoWidth)??(r==null?void 0:r.width),d=(r==null?void 0:r.naturalHeight)??(r==null?void 0:r.videoHeight)??(r==null?void 0:r.height);e=e??0,t=t??0,i=i??c,s=s??d,i<0&&(e+=i,i=Math.abs(i)),s<0&&(t+=s,s=Math.abs(s)),a<0&&(n+=a,a=Math.abs(a)),l<0&&(o+=l,l=Math.abs(l));const h=Math.max(e,0),u=Math.min(e+i,c),f=Math.max(t,0),g=Math.min(t+s,d),p=a/i,m=l/s;return[r,h,f,u-h,g-f,e<0?n-e*p:n,t<0?o-t*m:o,(u-h)*p,(g-f)*m]}function Fc({context:r,source:e,format:t="letterbox",videoResolution:i,videoAspectRatio:s,posX:n,posY:o,width:a,height:l,offscreenCanvas:c}){const{sx:d,sy:h,sWidth:u,sHeight:f,scale:g}=Mc({resolution:Math.min(a,l),aspectRatio:a/l,format:t,videoResolution:i,videoAspectRatio:s}),p=c&&typeof r.filter<"u";if(t==="letterbox"||t==="squarebox"||t==="letterbox-video"&&!p){if(d<0){const y=Math.abs(d)*g;r.fillStyle="black",r.beginPath(),r.rect(n,o,y,l),r.rect(n+a-y,o,y,l),r.fill(),r.closePath()}if(h<0){const y=Math.abs(h)*g;r.fillStyle="black",r.beginPath(),r.rect(n,o,a,y),r.rect(n,o+l-y,a,y),r.fill(),r.closePath()}}if(t==="letterbox-video"&&p){const{width:y,height:T}=Fi({resolution:i,aspectRatio:s});c.width=y,c.height=T;const E=c.getContext("2d",{alpha:!1});if(E==null||E.drawImage(e,0,0,y,T),E){r.save(),r.globalCompositeOperation="destination-out",r.fillRect(n,o,a,l);const S=us({source:c,sx:d,sy:h,sw:u,sh:f,dx:n,dy:o,dw:a,dh:l});r.globalCompositeOperation="source-over",r.drawImage(...S),E.save();const R=1.3,w=-(y*R-y)/2,I=-(T*R-T)/2;if(E.filter="blur(40px) brightness(20%)",E.translate(w,I),E.scale(R,R),E.drawImage(c,0,0,y,T),E.restore(),r.globalCompositeOperation="destination-over",d<0){const O=a/s,P=l/O,B=us({source:c,sy:(1-P)*T/2,sh:P*T,dx:n,dy:o,dw:a,dh:l});r.drawImage(...B)}if(h<0){const O=l*s,P=a/O,B=us({source:c,sx:(1-P)*y/2,sw:P*y,dx:n,dy:o,dw:a,dh:l});r.drawImage(...B)}r.restore()}}else{const y=us({source:e,sx:d,sy:h,sw:u,sh:f,dx:n,dy:o,dw:a,dh:l});r.drawImage(...y)}const m=d*-1*g,A=h*-1*g,x=a-m*2,b=l-A*2;return{dx:m,dy:A,dw:x,dh:b}}const Nc=/\d{0,2}:?\d{2}:\d{2}\.\d{3}\s-->\s\d{0,2}:?\d{2}:\d{2}\.\d{3}\s{1,2}.*/g,Bc=/\d{0,2}:?\d{2}:\d{2}\.\d{3}/g;function to(r){if(!r)return[];const e=r.match(Nc);return e?e==null?void 0:e.map(t=>{const[i,s]=t.replace(`\r
2
2
  `,`
3
3
  `).split(`
4
- `),[n,o]=i.match(Bc)||[];return{start:n,end:o,text:s}}):[]}function fs(r){const[e,t,i]=r.split(":");return i?parseInt(e)*60*60+parseInt(t)*60+parseFloat(i):parseInt(e)*60+parseInt(t)}function gs({canvas:r,context:e,currentTime:t,vttCaptions:i}){if(i){const s=to(i).find(({start:n,end:o})=>n&&o&&t>=fs(n)&&t<fs(o));if(s){const n=Math.min(r.width,r.height);let o=[""];const a=r.width*.9,l=n*.05;e.font=`${l}px Roobert, Dejavu Sans, sans-serif`,e.textBaseline="middle",s.text.split(" ").forEach(c=>{const d=o.length-1,h=e.measureText(o[d]).width,u=e.measureText(` ${c}`).width;h+u<a?o[d]=`${o[d]} ${c}`:o=[...o,c]}),o.forEach((c,d)=>{const h=c.trim(),u=e.measureText(h),f=(r.width-u.width)/2,g=r.height*.85-(l+n*.04)*(o.length-1-d),p=l*.8,m=l/1.5,A=(r.width-u.width-m)/2,T=g-p,b=u.width+m,y=p*2,x=e.globalAlpha;e.save(),e.globalCompositeOperation="source-over",e.globalAlpha=.8*x,e.fillStyle="#000000",e.beginPath(),e.roundRect(A,T,b,y,n*.01),e.fill(),e.closePath(),e.globalAlpha=x,e.fillStyle="#FFFFFF",e.fillText(h,f,g),e.restore()})}}}const It=1.8;function Fi(r){return typeof r=="number"?{top:r,right:r,bottom:r,left:r}:{top:0,right:0,bottom:0,left:0,...r}}function Uc(r,e=1){return typeof r=="number"?{topLeft:r*e,topRight:r*e,bottomRight:r*e,bottomLeft:r*e}:{topLeft:((r==null?void 0:r.topLeft)??0)*e,topRight:((r==null?void 0:r.topRight)??0)*e,bottomRight:((r==null?void 0:r.bottomRight)??0)*e,bottomLeft:((r==null?void 0:r.bottomLeft)??0)*e}}function ps(r,e){return typeof r=="number"?r:typeof r=="function"?r(e):null}function ms(r,e){const{w:t,gap:i=0,padding:s=0,direction:n="column",elements:o}=r,{right:a,left:l}=Fi(s);if(t){const c=ps(t,e);if(c)return c}if(o){const c=o.length;if(n==="row")return a+l+i*(c-1)+o.reduce((d,h)=>d+=ms(h,e),0);if(n==="column"){let d=0;return o.forEach(h=>{const u=a+l+ms(h,e);u>d&&(d=u)}),d}}return 0}function Hc(r,e,t){const{w:i=0,gap:s=0,padding:n=0,direction:o="column"}=r,{right:a,left:l}=Fi(n),c=e.length,d=e.reduce((u,f)=>{const{w:g}=f;if(g){const p=ps(g,t);if(p)return u+=p}return g==="auto"?u+=ms(f,t):u},0),h=e.filter(({w:u})=>u==="fill").length;return e.reduce((u,f)=>{const{w:g}=f,p=i-a-l,m=Math.min(p,ms(f,t));if(g==="fill"){if(o==="row"){const A=(i-d-a-l-s*(c-1))/h;return u=[...u,A]}if(o==="column")return u=[...u,p]}return u=[...u,m]},[])}function vs(r,e){const{h:t,gap:i=0,padding:s=0,direction:n="column",elements:o}=r,{top:a,bottom:l}=Fi(s);if(t){const c=ps(t,e);if(c)return c}if(o){const c=o.length;if(n==="row"){let d=0;return o.forEach(h=>{const u=a+l+vs(h,e);u>d&&(d=u)}),d}if(n==="column")return a+l+i*(c-1)+o.reduce((d,h)=>d+=vs(h,e),0)}return 0}function Gc(r,e,t){const{h:i=0,gap:s=0,padding:n=0,direction:o="column"}=r,{top:a,bottom:l}=Fi(n),c=e.length,d=e.reduce((u,f)=>{const{h:g}=f;if(g){const p=ps(g,t);if(p)return u+=p}return g==="auto"?u+=vs(f,t):u},0),h=e.filter(({h:u})=>u==="fill").length;return e.reduce((u,f)=>{const{h:g}=f,p=i-a-l,m=Math.min(p,vs(f,t));if(g==="fill"){if(o==="row")return u=[...u,p];if(o==="column"){const A=(i-d-a-l-s*(c-1))/h;return u=[...u,A]}}return u=[...u,m]},[])}function io({canvas:r,offscreenCanvas:e,debug:t=!1,origin:{x:i=0,y:s=0,w:n=r.width,h:o=r.height}={},parent:a,elements:l=[]}){const c=Math.min(n,o)/1080,d={x:0,y:0,w:n/c,h:o/c,gap:0,padding:0,direction:"column",align:"start",justify:"start",...a},{x:h,y:u,w:f,h:g,gap:p,padding:m,direction:A,align:T,justify:b}=d,{top:y,right:x,bottom:E,left:S}=Fi(m);l.map((R,w)=>{const I=r.getContext("2d",{alpha:!1});if(I){const O=l.length,{x:P,y:B,radius:J,elements:H=[],draw:V}=R,{topLeft:j,topRight:F,bottomRight:U,bottomLeft:Q}=Uc(J,c),Y=Hc(d,l,{context:I}),z=Gc(d,l,{context:I}),[K,X,ie]=Y.reduce((be,Le,He)=>(He<w&&(be[0]=be[0]+=Le),He>w&&(be[1]=be[1]+=Le),be[2]=be[2]+=Le,be),[0,0,0]),[ee,ne,se]=z.reduce((be,Le,He)=>(He<w&&(be[0]=be[0]+=Le),He>w&&(be[1]=be[1]+=Le),be[2]=be[2]+=Le,be),[0,0,0]),ye=Y[w],he=z[w],_e={"row|start|start":S+K+p*w,"row|center|start":S+K+p*w,"row|end|start":S+K+p*w,"row|start|center":f/2-ie/2-p*(O-1)/2+K+p*w,"row|center|center":f/2-ie/2-p*(O-1)/2+K+p*w,"row|end|center":f/2-ie/2-p*(O-1)/2+K+p*w,"row|start|end":f-x-ye-X-p*(O-w),"row|center|end":f-x-ye-X-p*(O-w),"row|end|end":f-x-ye-X-p*(O-w),"column|start|start":S,"column|center|start":f/2-ye/2,"column|end|start":f-x-ye-X,"column|start|center":S,"column|center|center":f/2-ye/2,"column|end|center":f-x-ye-X,"column|start|end":S,"column|center|end":f/2-ye/2,"column|end|end":f-x-ye-X},Pt={"row|start|start":y,"row|center|start":g/2-he/2,"row|end|start":g-E-he-ne,"row|start|center":y,"row|center|center":g/2-he/2,"row|end|center":g-E-he-ne,"row|start|end":y,"row|center|end":g/2-he/2,"row|end|end":g-E-he-ne,"column|start|start":y+ee+p*w,"column|center|start":y+ee+p*w,"column|end|start":y+ee+p*w,"column|start|center":g/2-se/2-p*(O-1)/2+ee+p*w,"column|center|center":g/2-se/2-p*(O-1)+ee+p*w,"column|end|center":g/2-se/2-p*(O-1)+ee+p*w,"column|start|end":g-E-he-ne-p*(O-w),"column|center|end":g-E-he-ne-p*(O-w),"column|end|end":g-E-he-ne-p*(O-w)},Tt=h+(P??_e[`${A}|${T}|${b}`]),Ot=u+(B??Pt[`${A}|${T}|${b}`]),Te=i+Tt*c,Ae=s+Ot*c,Ue=ye*c,ue=he*c;V&&(I.save(),J&&(I.beginPath(),I.moveTo(Te+Math.min(ue/It,j),Ae),I.lineTo(Te+Ue-Math.min(ue/It,F),Ae),I.quadraticCurveTo(Te+Ue,Ae,Te+Ue,Ae+Math.min(ue/It,F)),I.lineTo(Te+Ue,Ae+ue-Math.min(ue/It,U)),I.quadraticCurveTo(Te+Ue,Ae+ue,Te+Ue-Math.min(ue/It,U),Ae+ue),I.lineTo(Te+Math.min(ue/It,Q),Ae+ue),I.quadraticCurveTo(Te,Ae+ue,Te,Ae+ue-Math.min(ue/It,Q)),I.lineTo(Te,Ae+Math.min(ue/It,j)),I.quadraticCurveTo(Te,Ae,Te+Math.min(ue/It,j),Ae),I.closePath(),t&&(I.strokeStyle="blue",I.stroke()),I.clip()),V({scale:c,canvas:r,offscreenCanvas:e,context:I,dx:Te,dy:Ae,dw:Ue,dh:ue}),t&&(I.strokeStyle="red",I.strokeRect(Te,Ae,Ue,ue)),I.restore()),io({canvas:r,offscreenCanvas:e,debug:t,origin:{x:i,y:s,w:n,h:o},parent:{...R,x:Tt,y:Ot,w:ye,h:he},elements:H})}})}function Vc(r){return io(r)}function cr({context:r,node:e,maxW:t=1/0}){const i=(e.text??"").split(" ");return i.slice(1).reduce((s,n)=>{const o=`${s[s.length-1].text} ${n}`.trim(),a=r.measureText(o);return a.width>t?s=[...s,{text:n,metrics:r.measureText(n)}]:s[s.length-1]={text:o,metrics:a},s},[{text:i[0],metrics:r.measureText(i[0])}])}function so(r){return r.map(({enabled:e=!0,node:t,...i})=>{if(e)return{...i,...(t==null?void 0:t.type)==="text"&&t.text?{w:t.fill?"fill":({context:s})=>t&&t.type==="text"&&t.text?(s.font=t.font,s.textBaseline="top",Math.ceil(s.measureText(t.text).width)):0,h:t.fill?"fill":()=>{var s,n;if(t&&t.type==="text"){const o=/(?<value>\d+\.?\d*)/;return parseFloat(((n=(s=t.font.match(o))==null?void 0:s.groups)==null?void 0:n.value)??"0")}return 0}}:{},elements:i.elements?so(i.elements):void 0,draw:({canvas:s,offscreenCanvas:n,context:o,dx:a,dy:l,dw:c,dh:d,scale:h})=>{var u,f,g,p,m,A,T,b;if(t){const{type:y,enabled:x=!0}=t;if(x){if(y==="box"&&(o.fillStyle=t.background,o.fillRect(a,l,c,d)),y==="text"&&t.text){const E=/(?<value>\d+\.?\d*)/;let S=0;const R=parseFloat(((f=(u=t.font.match(E))==null?void 0:u.groups)==null?void 0:f.value)??"0")*h;if(t.fill){const{minSize:w,maxSize:I}=t.fill;S=w*h,o.font=t.font.replace(E,S.toString());const O=10*h;let P=0,B=cr({context:o,node:t,maxW:c});for(;S+O<I*h&&(B.length+1)*(S+O)<d;)if(S+=O,o.font=t.font.replace(E,S.toString()),B=cr({context:o,node:t,maxW:c}),P=B.reduce((J,H)=>(H.metrics.width>J&&(J=H.metrics.width),J),0),P>c){S-=O;break}o.font=t.font.replace(E,S.toString())}else S=R,o.font=t.font.replace(E,R.toString());o.textBaseline="top",o.fillStyle=t.color,t.wrap?cr({context:o,node:t,maxW:c}).forEach((w,I)=>{o.fillText(w.text,a,l+S*I)}):o.fillText(t.text,a,l)}if(y==="image"&&t.source&&o.drawImage(t.source,a,l,c,d),y==="video"&&t.source){const E=((g=t.source)==null?void 0:g.naturalWidth)??((p=t.source)==null?void 0:p.videoWidth)??((m=t.source)==null?void 0:m.width),S=((A=t.source)==null?void 0:A.naturalHeight)??((T=t.source)==null?void 0:T.videoHeight)??((b=t.source)==null?void 0:b.height);if(E&&S){const{resolution:R,aspectRatio:w}=Mi({resolution:Math.min(E,S),aspectRatio:E/S}),{dx:I,dy:O,dw:P,dh:B}=Fc({offscreenCanvas:n,context:o,source:t.source,format:t.format??"letterbox",videoResolution:R,videoAspectRatio:w,posX:a,posY:l,width:c,height:d});t.elements&&ut({canvas:s,offscreenCanvas:n,origin:{x:Math.max(a,a+I),y:Math.max(l,l+O),w:Math.min(c,P),h:Math.min(d,B)},elements:t.elements})}}if(y==="gradient"){const E=o.createLinearGradient(a+c,l,a+c,l+d);t.stops.forEach(S=>{E.addColorStop(S.percent,S.color)}),o.fillStyle=E,o.fillRect(a,l,c,d)}}}}}}).filter(Boolean)}function ut({elements:r,...e}){return Vc({...e,elements:so(r)})}async function jc({parts:r,transitionDuration:e=.3333333333333333,burnCaptions:t=!1,getVideoSource:i,getPosterSource:s}){return(await Promise.all(r.map(async({header:n,video:o},a)=>{const l=await St(),c=r.reduce((p,{video:m},A)=>(A<a&&(p+=m.duration-e/2),p),0),d=Math.max(0,c),[h]=await Promise.all([o.poster?(s==null?void 0:s())??null:null]),u=({canvas:p,currentTime:m})=>{const{id:A,format:T}=o,{title:b,subTitle:y}=n??{},x=Math.max(0,m-d),E=i({id:A,currentTime:x});E&&ut({canvas:p,offscreenCanvas:l,elements:[{w:"fill",h:"fill",node:{format:T,type:"video",source:E,elements:[{w:"fill",h:"fill",gap:12,padding:{left:135,bottom:216},justify:"end",elements:[{enabled:!!b,h:44,node:{type:"text",color:"#FFFFFF",text:b,font:"44px CiscoSansTT, Roobert, Dejavu Sans, sans-serif"}},{enabled:!!y,h:28,node:{type:"text",color:"#FFFFFF",text:y,font:"28px CiscoSansTT, Roobert, Dejavu Sans, sans-serif"}}]}]}}]})},f=h&&(({canvas:p,context:m,currentTime:A})=>{if(A<=e/2){const{format:T}=o;m.save(),m.globalAlpha=(e/2-A)/(e/2),ut({canvas:p,offscreenCanvas:l,elements:[{w:"fill",h:"fill",node:{format:T,type:"video",source:h}}]}),m.restore()}}),g=o.captions?({canvas:p,context:m,currentTime:A})=>{const{start:T,captions:b}=o,y=Math.max(0,A-d)+T;b&&t&&gs({canvas:p,context:m,currentTime:y,vttCaptions:b})}:null;return[{id:o.id,start:d,duration:o.duration,draw:[u,g,f].filter(Boolean),video:o,audio:[{url:o.src,start:o.start,duration:o.duration}],transitionCanvas:await St()}].filter(Boolean)}))).flatMap(n=>n)}function dr({header:r,logoSource:e,brandLogo:t,showBackground:i=!0}){const s=!!(r!=null&&r.title),n=!!(r!=null&&r.subTitle),o=r==null?void 0:r.showWatermark,a=!o&&!!t&&(r==null?void 0:r.showBrandLogo),l=!!e||!!t||o||a||s||n,c=e?(e==null?void 0:e.naturalWidth)??e.width:0,d=e?(e==null?void 0:e.naturalHeight)??e.height:0,h=c/d,u=t?(t==null?void 0:t.naturalWidth)??t.width:0,f=t?(t==null?void 0:t.naturalHeight)??t.height:0,g=u/f;return[{enabled:l,w:"fill",h:162,padding:36,justify:"center",elements:[{w:"fill",gap:36,direction:"row",align:"center",elements:[{w:"fill",gap:24,direction:"row",align:"center",elements:[{enabled:!!e,w:h>=1?90:90*h,h:h<1?90:90/h,radius:15,node:{type:"image",source:e}},{enabled:s||n,gap:8,elements:[{enabled:s,h:36,node:{type:"text",text:r==null?void 0:r.title,color:(r==null?void 0:r.color)??"#FFFFFF",font:"bold 36px Roobert, Dejavu Sans, sans-serif"}},{enabled:n,h:36,node:{type:"text",text:r==null?void 0:r.subTitle,color:(r==null?void 0:r.color)??"rgba(255, 255, 255, .8)",font:"36px Roobert, Dejavu Sans, sans-serif"}}]}]},{enabled:a,w:g>=1?90:90*g,h:g<1?90:90/g,radius:15,node:{type:"image",source:t}},{enabled:o,gap:10,padding:14,w:"auto",h:"auto",radius:500,direction:"row",elements:[{node:{type:"text",text:"Made using",color:"rgba(255, 255, 255, .4)",font:"bold 28px Roobert, Dejavu Sans, sans-serif"}},{node:{type:"text",text:"vouch",color:"rgba(255, 255, 255, 1)",font:"bold 30px Roobert, Dejavu Sans, sans-serif"}}],node:{type:"box",background:"rgba(0, 0, 0, 0.2)"}}]}],node:{enabled:i,type:"gradient",stops:[{percent:0,color:"rgba(0, 0, 0, 0.5)"},{percent:.8,color:"rgba(0, 0, 0, 0.05)"},{percent:1,color:"rgba(0, 0, 0, 0)"}]}}]}async function zc(){if(typeof window>"u"){const r=await Promise.resolve().then(()=>Rc);return new r.Image}return new Image}async function Ni(r){return new Promise(e=>{zc().then(t=>{t.onload=()=>{e(t)},t.onerror=()=>{e(null)},t.src=r})})}async function Wc({parts:r,transitionDuration:e=.3333333333333333,burnCaptions:t=!1,getVideoSource:i,getPosterSource:s}){return Promise.all(r.map(async({card:n,header:o,video:a},l)=>{const c=await St(),d=r.reduce((A,{video:T},b)=>(b<l&&(A+=T.duration-e/2),A),0),h=Math.max(0,d),[u,f]=await Promise.all([o&&o.logoSrc?Ni(o.logoSrc):null,a.poster?(s==null?void 0:s())??null:null]),g=({canvas:A,currentTime:T})=>{const{id:b,format:y}=a,x=Math.max(0,T-h),E=i({id:b,currentTime:x});if(E){const S=A.width/A.height<1;ut({canvas:A,offscreenCanvas:c,elements:[{w:"fill",h:"fill",direction:S?"column":"row",elements:[{enabled:!!(n!=null&&n.title),w:"fill",h:"fill",padding:{top:96,right:48,bottom:96,left:48},elements:[{node:{type:"text",text:n==null?void 0:n.title,wrap:!0,color:(n==null?void 0:n.color)??"#000000",font:"bold 72px Roobert, Dejavu Sans, sans-serif"}}],node:{type:"box",background:(n==null?void 0:n.background)??"#FFFFFF"}},{w:"fill",h:"fill",node:{format:y,type:"video",source:E,elements:dr({header:o,logoSource:u})}}]}]})}},p=f&&(({canvas:A,context:T,currentTime:b})=>{if(b<=e/2){const{format:y}=a,x=A.width/A.height<1;T.save(),T.globalAlpha=(e/2-b)/(e/2),ut({canvas:A,offscreenCanvas:c,elements:[{w:"fill",h:"fill",direction:x?"column":"row",elements:[{enabled:!!(n!=null&&n.title),w:"fill",h:"fill"},{w:"fill",h:"fill",node:{format:y,type:"video",source:f}}]}]}),T.restore()}}),m=a.captions?({canvas:A,context:T,currentTime:b})=>{const{start:y,captions:x}=a,E=Math.max(0,b-h)+y;x&&t&&gs({canvas:A,context:T,currentTime:E,vttCaptions:x})}:null;return{id:a.id,start:h,duration:a.duration,draw:[g,m,p].filter(Boolean),audio:[{url:a.src,start:a.start,duration:a.duration}],video:a,transitionCanvas:await St()}}))}async function ro({parts:r,transitionDuration:e=.3333333333333333,burnCaptions:t=!1,getVideoSource:i,getPosterSource:s}){return(await Promise.all(r.map(async({card:n,header:o,video:a},l)=>{const c=await St(),d=(n==null?void 0:n.duration)??0,h=r.reduce((x,{card:E,video:S},R)=>(R<l&&(E!=null&&E.duration&&E!=null&&E.title&&(x+=(E==null?void 0:E.duration)-e/2),x+=S.duration-e/2),x),0),u=Math.max(0,h),f=Math.max(0,h+(n!=null&&n.duration?d-e/2:0)),[g,p,m]=await Promise.all([o&&o.logoSrc?Ni(o.logoSrc):null,o&&o.brandLogo?Ni(o.brandLogo):null,a.poster?(s==null?void 0:s())??null:null]),A=n&&n!=null&&n.title?({canvas:x})=>{ut({canvas:x,offscreenCanvas:c,elements:[{enabled:!!(n!=null&&n.title),w:"fill",h:"fill",padding:{top:148,right:48,bottom:148,left:48},elements:[{node:{type:"text",text:n.title,wrap:!0,fill:{minSize:48,maxSize:128},color:(n==null?void 0:n.color)??"#000000",font:"bold 72px Roobert, Dejavu Sans, sans-serif"}}],node:{type:"box",background:(n==null?void 0:n.background)??"#FFFFFF"}},{x:0,y:0,w:"fill",elements:dr({header:{showBrandLogo:n.showBrandLogo,showWatermark:n.showWatermark},showBackground:!1})}]})}:null,T=({canvas:x,currentTime:E})=>{const{id:S,format:R}=a,w=Math.max(0,E-f),I=i({id:S,currentTime:w});I&&ut({canvas:x,offscreenCanvas:c,elements:[{w:"fill",h:"fill",node:{format:R,type:"video",source:I,elements:dr({header:o,logoSource:g,brandLogo:p})}}]})},b=m&&(({canvas:x,context:E,currentTime:S})=>{if(S<=e/2){const{format:R}=a;E.save(),E.globalAlpha=(e/2-S)/(e/2),ut({canvas:x,offscreenCanvas:c,elements:[{w:"fill",h:"fill",node:{format:R,type:"video",source:m}}]}),E.restore()}}),y=a.captions?({canvas:x,context:E,currentTime:S})=>{const{start:R,captions:w}=a,I=Math.max(0,S-f)+R;w&&t&&gs({canvas:x,context:E,currentTime:I,vttCaptions:w})}:null;return[A&&{id:Math.random(),start:u,duration:d,draw:[A].filter(Boolean),video:null,audio:[{url:null,start:u,duration:d}],transitionCanvas:await St()},{id:a.id,start:f,duration:a.duration,draw:[T,!n&&b,y].filter(Boolean),video:a,audio:[{url:a.src,start:a.start,duration:a.duration}],transitionCanvas:await St()}].filter(Boolean)}))).flatMap(n=>n)}async function Yc({parts:r,transitionDuration:e=.3333333333333333,burnCaptions:t=!1,getVideoSource:i,getPosterSource:s}){return(await Promise.all(r.map(async({header:n,video:o},a)=>{const l=await St(),c=r.reduce((A,{video:T},b)=>(b<a&&(A+=T.duration-e/2),A),0),d=Math.max(0,c),[h,u,f]=await Promise.all([n&&n.logoSrc?Ni(n.logoSrc):null,Ni("data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAcgAAABkCAYAAAACCKDLAAAA1XpUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHjabVFbEsMgCPz3FD0CsEbxOObRmd6gxy8G0iaZMuOygi6gaXu/nukxTKApT1VLK4XMcstNuhElt74jU95xt0WD8TWeSo5LYiGYh2+1uOcjHhcOz93YdBLSJRLzNdGigOhNSNxhdDT4GkIthCCe4BDoPhaVpvU8wrzR1dRXGiDLd24vetvnaq+3TlYHIhsYZAhkbwBjIaEbqYYMtYNswcHJ0I/CH+TfO9H4meg27apKPhB+iei6nqdIH5aeY0HBEdYQAAABg2lDQ1BJQ0MgcHJvZmlsZQAAeJx9kT1Iw0AcxV/TSkWqgnYQcchQneyiIo5ahSJUCLVCqw4ml35Bk4YkxcVRcC04+LFYdXBx1tXBVRAEP0BcXZwUXaTE/yWFFjEeHPfj3b3H3TtAaFSYZoVmAU23zXQyIWZzq2L4FWEMQEAIfTKzjDlJSsF3fN0jwNe7OM/yP/fn6FXzFgMCIvEsM0ybeIN4etM2OO8TR1lJVonPicdNuiDxI9cVj984F10WeGbUzKTniaPEYrGDlQ5mJVMjniKOqZpO+ULWY5XzFmetUmOte/IXRvL6yjLXaY4giUUsQYIIBTWUUYGNOK06KRbStJ/w8Q+7folcCrnKYORYQBUaZNcP/ge/u7UKkxNeUiQBdL04zscoEN4FmnXH+T52nOYJEHwGrvS2v9oAZj5Jr7e12BHQvw1cXLc1ZQ+43AGGngzZlF0pSFMoFID3M/qmHDB4C/Sseb219nH6AGSoq9QNcHAIjBUpe93n3d2dvf17ptXfDwvRcn2L19pvAAAQ7mlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4KPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNC40LjAtRXhpdjIiPgogPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iCiAgICB4bWxuczpzdEV2dD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlRXZlbnQjIgogICAgeG1sbnM6R0lNUD0iaHR0cDovL3d3dy5naW1wLm9yZy94bXAvIgogICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICAgeG1sbnM6cGhvdG9zaG9wPSJodHRwOi8vbnMuYWRvYmUuY29tL3Bob3Rvc2hvcC8xLjAvIgogICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iCiAgIHhtcE1NOkRvY3VtZW50SUQ9ImFkb2JlOmRvY2lkOnBob3Rvc2hvcDplMTMwZTA5My1jZGRmLWFiNDktYmFkNC00ZjA4OWYzYzU3NWUiCiAgIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NDhjZjZkOGEtZjdhNi00ODkzLTgyM2QtYzQwNWY1MzM0ZWVhIgogICB4bXBNTTpPcmlnaW5hbERvY3VtZW50SUQ9InhtcC5kaWQ6YTZkNjgyMjktNWJmNC00ODQ2LTgzOTMtYjZiZTQxZWZhMDBmIgogICBHSU1QOkFQST0iMi4wIgogICBHSU1QOlBsYXRmb3JtPSJNYWMgT1MiCiAgIEdJTVA6VGltZVN0YW1wPSIxNjg5NjQ2MjM3NjQ2MjA4IgogICBHSU1QOlZlcnNpb249IjIuMTAuMzQiCiAgIGRjOkZvcm1hdD0iaW1hZ2UvcG5nIgogICBwaG90b3Nob3A6Q29sb3JNb2RlPSIzIgogICBwaG90b3Nob3A6SUNDUHJvZmlsZT0ic1JHQiBJRUM2MTk2Ni0yLjEiCiAgIHRpZmY6T3JpZW50YXRpb249IjEiCiAgIHhtcDpDcmVhdGVEYXRlPSIyMDIzLTA3LTEyVDE4OjA4OjE1KzA1OjMwIgogICB4bXA6Q3JlYXRvclRvb2w9IkdJTVAgMi4xMCIKICAgeG1wOk1ldGFkYXRhRGF0ZT0iMjAyMzowNzoxOFQxMjoxMDozNCsxMDowMCIKICAgeG1wOk1vZGlmeURhdGU9IjIwMjM6MDc6MThUMTI6MTA6MzQrMTA6MDAiPgogICA8eG1wTU06SGlzdG9yeT4KICAgIDxyZGY6U2VxPgogICAgIDxyZGY6bGkKICAgICAgc3RFdnQ6YWN0aW9uPSJjcmVhdGVkIgogICAgICBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOmE2ZDY4MjI5LTViZjQtNDg0Ni04MzkzLWI2YmU0MWVmYTAwZiIKICAgICAgc3RFdnQ6c29mdHdhcmVBZ2VudD0iQWRvYmUgUGhvdG9zaG9wIDI0LjMgKE1hY2ludG9zaCkiCiAgICAgIHN0RXZ0OndoZW49IjIwMjMtMDctMTJUMTg6MDg6MTUrMDU6MzAiLz4KICAgICA8cmRmOmxpCiAgICAgIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiCiAgICAgIHN0RXZ0OmNoYW5nZWQ9Ii8iCiAgICAgIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6MTI0OTRmODgtMWM4Mi00OThmLWI3N2YtNDEwYzc2ZWJmMTRlIgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJBZG9iZSBQaG90b3Nob3AgMjQuMyAoTWFjaW50b3NoKSIKICAgICAgc3RFdnQ6d2hlbj0iMjAyMy0wNy0xMlQxODo0NTo1NyswNTozMCIvPgogICAgIDxyZGY6bGkKICAgICAgc3RFdnQ6YWN0aW9uPSJzYXZlZCIKICAgICAgc3RFdnQ6Y2hhbmdlZD0iLyIKICAgICAgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDo5N2JjNWI1MC1hOWQ1LTQzOTQtODU2Zi1lNDcxMDUyNzJlZTEiCiAgICAgIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyNC4zIChNYWNpbnRvc2gpIgogICAgICBzdEV2dDp3aGVuPSIyMDIzLTA3LTEyVDE5OjQ5OjEwKzA1OjMwIi8+CiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InNhdmVkIgogICAgICBzdEV2dDpjaGFuZ2VkPSIvIgogICAgICBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjI5YzlmOWY5LWUwOWQtNGRlOS04YmVhLWViNmU1NWM1ZWQxMyIKICAgICAgc3RFdnQ6c29mdHdhcmVBZ2VudD0iR2ltcCAyLjEwIChNYWMgT1MpIgogICAgICBzdEV2dDp3aGVuPSIyMDIzLTA3LTE4VDEyOjEwOjM3KzEwOjAwIi8+CiAgICA8L3JkZjpTZXE+CiAgIDwveG1wTU06SGlzdG9yeT4KICA8L3JkZjpEZXNjcmlwdGlvbj4KIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAKPD94cGFja2V0IGVuZD0idyI/Pv0Rie8AAAAGYktHRAD/AP8A/6C9p5MAAAAJcEhZcwAALiMAAC4jAXilP3YAAAAHdElNRQfnBxICCiU9yio9AAAgAElEQVR42u2dd7gURfb3P4d7L+GCBAFFQUBFTIs5oiJh4UVcFQPO6OrquorhXRO6V1zWwJrWi7qmNaCua57B7GJWEJVFxIBiQERAQBQRRHI+vz+qQNDpntA9Mz1z6/s884i3u6urq+rUt07VCeDg4ODg4PALqOohqnq7qk5W1WVq8IOqjlXVIarattzbQIrU8PWB7YEO9lcNNMvg0YSITHZD18HBoYyJaQ+gf46PLxSRmwO+fyvgPuCwNLeuBK4GrhORta7ncm/wBqraV1VvVdV3VXWl5ob+rjUdHBzKfL48VXPHjIDv3k5VZ2X5zsdUtaIc+6Iyzx29N3AOcDzQxA19BwcHh8gSc0PgOaBdlo/GganAZeXWJvXy1ND7q+po4D3gNEeODg4ODpHH+cCuOT47WFU7OYL0J8aWqvow8A7Q3Y03BwcHh5LBuQGerQTOcgTpTY7dgUnA7904c3BwcCgdWMOgoFap/RxBpm7cM4BXgK3cUHNwcHAoOewSQhk7q2qVI8hNyfFsYDhQ5caYg4ODQ0lii5DKae0I8mdyPBm4w40tBwcHh5LG8pDKWeIIkg171sPduHJwcHAoecwMoYzFIrKonBolJz9IVW0AJIGGblw5ODg4lDzeBlYB9QOU8VpYlVHVw4FHcnz8JxHpUDSCBC4BOrsx5eDg4FD6EJHFqvpf4NgAxTwaYpWqyCz8aF6R9RarqrayBOng4ODgUD74Gya+ai4YBzxVbg2SiwY5CBNcPB9YAyz1ub7ajWGHcoCSiG20Wn9IiP/XtYpDkbXIydYr4d9ZPjoXOFFE1tVpgrQ+LmeE9O6fgBEY/8kPgO9FZIkbpg51gByHYLIgrMcAJXGOEL/TtY5DkUnyflVdC9yZoSL0GdBfRGaUY3tku8XaG2gV8J3rgOuAdiIyUESeEJFpjhwd6gg5NgGGpLg0VEmIayGHCJDkg5iYrPcCCz1u+xK4GNhLRL4s17bIdos1aLqp1cAAEXnWDUOHOorfAo1S/L010Jgy8yNzKFmSnAGcYbdc9+LnvL3zgCkiMrUutEO2BNkt4PsudOToUMdxhMffpwlxR44OUSPKNcC79lfnkDFBqurmwI4B3jUJs6/t4FD6SGoDIAZsh8mFN4KYrPKVIbOF6hXQ2RnpODiUsAYZNNfXneVo5eRQJ8mxGfAmsNtGfz2XpPYi5nuWvj/QxhGkg0NpIBsjne0DvutF19wOZYLBvyBHgP2AC9M85+WEvRh4yzWrg0PpEuTmAd6zqFzNgB3qnPZYCfzR4+ohaZ4+xuPvLwvxVa5xHRxKlyCDBAeY55raoUzQB9jS49r3Xg8pib0x55Wp8KRrVgeH0ibIxgHes8A1tUOZ4E8+1/yI7niPv68ARrpmdXDYBPWjUIl6BXrPMtffDiWPpLYBjvS4Oh943kN7rAec6PHcC869w8HhV9gxCpWodP2QPVS1BdAeaGE16yaAYJy8l2CiT8wSkfmutcoKp/nIzIM+bh7dgHYe1x6PyJgWW8f1DuHVmGwKP2HiIy8BpovId3VY7rfBWCE3sW2z2UYyvxSYA8x01vqB27kx3uf8jiAj1lkdge7AQUAXYAcyNFhS1YXAFOBTjFvAG85YqYh9WUtb4O/AgcB3wD+lJkP3iqRWAAN97rjP55qX9ricIm2vqmpboIcd2/tj3LgaZvDcEjumx2Esb0eJyLwylPtOG7XPLpj0fpnYYaxU1S+Bj4DRwOtO5jNu8ypM1J4bgG2jUCdRVS2xdrxQRG7Oc0ftA5yAMcvvEHLxXwNPA4+IyHtOLApGjs2Aj63mvzGOl5oMtLikHo13Op//EZODUr6XRANLxs1TXH5MiJ+YYkE2PcfPHCoiV/qM66aY4AYnYSxuw4j9ug54HUgAI0o5prKq7g6cjDkv3ibEoicDDwAPiMi3GdTjVOD+XOcXEemY4/fn9b2qejNwfimNiXo4rO+8Jqp6kap+AUzApPXqkIdXdQAuACao6hf2nU1cD+QdZ6YgR0gdODwVzvO5drvPtSM8yBHgPwUa281V9UpgJjAcs+UrIc4hva0G/bWq/t3mjC0VuW+oqgNVdSIwEbgoZHIE2AmToGG2qj6lqns6cXQEWSoC0kpVrwFmW9W+cwFf39m+c5aqXlVKE0uJaY+C9/Zo+tV2UnfHbLWlwnf4W696Wb3OAV7L89gWqxV8BVxB/jO0bw5cBkxT1fNUtTLCcl9fVf9stfW7gd0LNN8eDXygqgl7pungCDKyAjLYTh5/LcDk4YfmmGzeU1X1L3Yv3iE89MM7EtRHGTzvFyFnuJdxjpJoh/GbTIWHhPi6PI7vNsDLmC2zzQvc3psBtwDvq+pvIij7vTGxoW/DO/RfvhEDPlPVs5x4OoKMmoAciNlOuQ5oGqGqNQNq7Qpz/3y95M7aS05+5OrzH7un9qK6IpwX+Vz7dxrtsR3eRjargbt8nj7VR8YeyOP43tuO795FbvfdgPFWi42C3G+mqv/BJGnvHIEqNQHutNuumzk6ih7qlBWrqlYAQ4FLI744+A0wVlX/DlwjImvDKPTuOwZWdV78zZzuXN/KuuHGd6ntOezVZodsdeWZQ8vSF09r2QtjjZgKC4BkmiLOB7w0+seJpTa6sL6Pp3k8N0GIf56nMd4TE/i8OiJdUA3cr6pdgItFRIsk+3thXGq2i+AwPRrYQVUPE5HZjpacBlkMAWmNsbYbUiLfvZ7MX7SpxgKj+Y8Vz3SX5zc55+zKqCZ7zp8xpq5qj1LDCh/tsTnGuMcL1/tcOwxvU/X78/St+0SMHDfGIOAO629ZaNmPA2MjSo4bL4rHqWp7R0uOIAstIDtjEn4eWoLV720FJ2g2FdpVTUmZ8LpD1We/Kct+r6U93iHe1gC3piniAsx5Wiq8SEw+9nn2bI+/LwMeydMnHx5RclyPs4B/Flj2LwIeIwMfzwigHTAK2MJRkyPIQgnIPhgn/Y4l/BmdgbftNlXOWFVRkTK+YRNdLGXa/UPxPkZISg2zfLTHppYgvXCd55gjsS3eiZETQnxRHZ5zzlfVcwok+4MxVuKlhO0xwSwcHEHmXUC6YLZVy8F9og0wKghJLqusX5maIMvv+FFr6YRx+vbCsDRFnIO3ZfM4YvJWGk3Ja9Fxh5t2uCXfvoCqeoHfIibiaOCGiCPIfJPj9na7omkZfVYrzJlk9v5TSa2cW9U6ZX83ZnE5DoG/Yc5xU+FZqfFx7zBnjxf7lP0PH+2xGjjd4/IEIf6+m3aoBB5S1YZ5kv3jKPBWroMjyFIix+bAC2WiOf4SbYHnbUDfbNB8Xr3WKS80lsVlZc2steySRnscmqaIC4CWHtc+B9/4rafg7Xd4m5tyNmBXTFCBsGW/C/Cga14HR5CpBUSAhymsn9MiTNaDQqEL/sGxU6HFvIrUBCmsE60tK8OAa33G9rNSw4c+2mOrNNrjlcRSuypY1w6voALzgBFuytkEg1S1XYiy3wTjytGogN+w1Mr+Wted5Ydy9IO8AGPNlw98i9m2HYOJxPHlL1Na2VRYnSyJHQL0IvzYjgAxVX1NRO7NVIP8tmIrv+vtge/LQHvsDhwVQHv8K97JwSfin57qCEy2l1S4W4ivjFhzfWrH8wRgqh3f6/fbm9rdis7AAUDfPIzjhhiDlNNCKu968pdHcPFGsj/Rttfsjf06VbWRba/OmOw/Pe084FCiyNh60QY7viLH94wRke4F0B53soM3zEPutXblfy8mXdW6LOskVlhOx0RkCTOM3FJgVxH5Ou2dSe3ec8Wo0a/P7eV1x3FS4xtTtBTIsQJ4D9jDqxWkhrhPG22L2UL1Gj9HE5NnPN9P4i3g4BSXVgMdhHgmmRw6kns2j0zHzH3AnSIyOctxfDDGr/SoEOuzBugoIt8ElP2DMem3wsYYjGHVf0VkeY5z0qkYw61ChLOMbDaPLOvSH5P1KBf8JCLNw6hH2WyxWgG+J2RyTAKdReREERmVSyJUEVEReVtETrWaZZghxhrjH+psE0yp8t113qkMhsFZPuS4ChNByQ//8Bk/E4BnfcjxAA9yBBN39dsItM+DwPYicn425LjROH5LRPrbnZGwIgFV2n4LIvsVwJ0ht9U7wIEi0l1ERuRCjrbdJovIYKt9Xwk+gSkcIodyOoOM+0xQ2eIboKeIxEVkWmjqushMS5TdgBkhFdtXVTPZUm42u6IdS8Qzs9auJa49bgFc7XPLLVLjo5kltSveQQUALvE6e7S43OfaTUVunsXAABE5RUTmhjCO3wb2g9B2HAYGzPxxKiYSTRhYhome1FVE3glR9heLyFBM8uWxjnocQRZSe6wPXBNSca8De4jI6HzVV0TewmTOfjmkIoeparq+lDRaZKmflfwT77yL8zGGO17kKMCNPmW/SMx7PCiJPTGh5VLhBSH+aRHb5QfgtyLyRMhjeAkmI8VjIRS3hV005iL7lRiXnjDwFbCfiAzPV8xYEZmOSZ3m3FAcQRYMp+Id9zIbjAD6icgP+a6wiPwIHBnSBLNzGu1nAz6r2sXr0i5aS0kmbtZafod3xg2Ay6WGhT7XT8YYoqTmv/Rbs35n87VFbJqVQH8ReTdPY3itlb3/hVBc/xyfO5ZwomR9bLXGTwsg+2tEZBDwF0dBjiDzrT3Wwz8gdaZ4HjhRJHVuvzwJyio7OY8MobiLM7npvQb7+I2FriVIjs3xP3/6AJMQ10t7bIF/OLJ7iclHPtpjF7yNVsYI8WIGgh8kImMLMIZ/jzH+CYIjcnwuDJKZarXsglpxi8gNmHNJB0eQeUMvgvs8TgKODyutVA6r8BjwScCi9lbV/dLd9G5931sOLsH+vwMT5NlL+ztLanx91K4GWntcW0T67Tu/68UMdTaG8A1XvMbwDPy2sDNDR1XdKsvF8d7A3gHfuwg4TETmFaOT7LlkwlGRI8h84aSAz68A4iKyrFgfYN99AmZLLAj8oscsBni//t4sF08/6t6l1PFaywm23bxwq9QwwUd73Ad/C8qriXlrFUpiL7y3tscL8ZeL2DwXFTj34q2Y/JpBkG2S8BNCqPdZIjK1yEP5TPLr2uNQFwnSRs44NmAx14jIZ8X+FhH5BJ8Yn5lOGKrq5We5BGCV1Gdsg4M8JyitZesSIcdO+Lu4zMA4/XuRYyUw3EcGvgBuSVMNv3yQxczI8LqIvF/g8bsEE8EqCPbLQvaFDM/dffC8iDwWAdlfBPx/R0eOIMNGP7yjnmSCmUQrHU4tMCfA8y0x0TtSYcMZ0YuNDvOUVYzhUNTJsRHGxaCpp3IHp0kNfrsClwB+GSXOIeZ9Hq0kegG/9dEeXyhiE91dpPcGJchOWdy7L8Ei+6zBJHGOBETkReAVR0mOIMNEz4DPDxORFRESkmXAzQGL8QqVs2H765lqX4PBASXQ73cBu/lcv0FqGO2jPf4Gf7/FR4jJKB9ylDTa/uAits1K4MUivft9jFtJruiYxb3dAtZ1hIhMidi4vspRkiPIqBDkInIPq5RPDAeW56FNNhghTKvcjg/q7+X1fA+tZbsIa4+XAH/wuWUiflkiklph+72+xx0LSW8VfRzgZQ48Soi/UcQmGme3O4uxwFtHMJePDlnce0jA6t4UtbFtAzB84GjJEWTwiVK1Ld6BoTPBUyKyNIJC8hPwXIAi9lTVX289xmR19cq1G7Tlp6qP8awCcHZEyfG4NJrbEiAmNb7GTpf6kBtADTHvaDNKomGaOvy1yM30bpHf/2GAZ1sWiCC/KPQZbRZ41NGSI8gwEDS01BMR/ranAvZpyrBxm61YvWj9vx9ufBLqHat+oPUvjBI59iR9nr8/Sg1TfLTHrvj7nb2KCUrvh4vAU8N+XIiPL3JTfVHk9wexxqywcVXTLY7bAC3KVPajXDdHkCWEIGlt1pGfyP9h4c2Az6f0C222bPUGzejryg681Kiv1/NNgZoIkeP+mEDhfnn+bpIan8klqc3t6txrAl4MnO4Xb1VJbAMM8bi8iuKePa7HrCK/f07A5zfL4J4dAr7jjagKvs3M8zUOjiDzQQIZ4hNrWh1VIfmOYMHMU7ZN9cq1mwjezZtd4FfGhVpLu2K3hSXHV8A3DN4LGRD6cPzPuC4iJjPTlHGjD0nfJsSnRWD4/FDk9xcicXinIEMKGBfxuS3q9XMEWQLoGODZL0rg+yaH3TaNVq39cuP/f6VRHybW98oORUOK5y6wnhz7YpLUNvW57VPgBN9oOUk9B3/r3OdIs7WqJHr4lLEA/0wihcSqOvD+IO4ds6Joe1CC85MjyIgjSGDtr0rg+6aH3TbVq9b8yoDj0ua+0dD6aS1/KhI5/sESV7XPbTOBvlLDIh9y7Ia/68wc4E9ptlargNt8yhgixBdGZNwspfzRrMxl/yscHEEGRBAjkvkl8H1BtspSTiArqip+dbb5UqO+vNrQN8Lcv7Q28wgnIRBjfa3lVkxi6ao07fNbqWG2DzluAzzuU44CJxNLm71lMN75Mt/HbN86FA7VAZ5dWALft9B1sSPIYmqQy0rg+4LUMaWhw9jLW89pN3/Zr7YiL9r8Rtbgma+2AfCMDe2Wb3LcFmOgdG4Gi4eeUsOXPuTYCHgak2vQC9f7BQSw2uOOeBvmmGDoxNe5qaSgCBI9a1EJfN9i18WOIIMiyKQkZd43nm3TZdZPv1qdTqrqwvXNLvErbyvgTa1ljzwRY6XWchHmPDFdwOr15DjJhxzFaqB+mR5GkSZTh5KohzmbbOBxy3Ah/p6bRkpK9h0c6gRBBokWUl0C39cowLOe51BdZv6U8mxzaLMrmFux5VdpSHKs1nJayOTYF+PcfkMG3zwd6OpLjgbD8DfKmQnEiKVNbzYI7xRgcyl+UIC6iiC7K81L4PuauS52BBkUQbZKtiiB7wtSR88zjF6T5qY0IV8tVfTYcvQXwLdpFhb3aS2vay17BdQY+2st72Dihu6ZwWPjgYN8t1WN9ngx/qHiVgLHpjt3VBI74W+Z+mchvsBNIUVBEEOkFiXwfS1cF0cDlSVc9yAH2duVwPcFqaPnGUafj797a5v5y86d1fLXSvTnVTt3+6aibe+2a78ZlUab6wm8r7W8gcng8ILU+BIrWksTq40djoll2iaL73kIGCg1rEhDjgOt9uiHM4jJe2nIsT4mqIDX1uoTQtxFPCkegvhadiqB79vedbEjyKAIEm1i5xL4vp0CPOvnsD75qAnfcHvflMFImrRrN7uzfi19gf/i738I0N3+0FpmYPy3ZvPz9ncDYH3M3M457FgsB86TmrTh3yCppwN3prnrCmLyUAbvvdZHq10A/NlNHSUr+1urajMb8ziq2MV1sSPIoAiSqmZnVW0pIpF091DV9hAoio3fNuTkAe/MWn173x28XB/Okhq6ai19MOHdtszwnR0JFrzhl3gbk9PxywzI8WzgjjR33U9M0iYxVhJ98N+iPU+Iz3VTR1ERNGLRQZjoS1FFV9fF0UApn0FODvh8jwh/W498tY0QX33w5B8mtZvvaedwIEndXWoYD+xliaqQWIDJJtI9Q3L8Swbk+ApwZgbk2A7/bAojhPgjbtoo6cUxBM8jm8/F8c5kd/zg4AgyJT4O+PxxEf62IHVbDXzu2+mqH/7xDd9APUMApIY5djKpIZjVcCZYClwP7CA13OUbOs4QYwVJvQmoTVPuu8AxxGR1GnKsAkbgnXJpNnCWmzKKDxGZh7EizhXHq6qUoew7OILcREg+DVDEEaoaOZNvVd0C6BOgiHcziDU5fuDr06ha6+lONoCk7m9JcrXUMAxzJjoc0hjKZI/vMCmoOkoNg6WG9JahSW0MPAlcmObO94A+xDKKvXkzcKDHtXXAH4T4j27KiAyC7GxsAxwaQdkX4CTXtY4gw8KoAM9WR1QjOAfvbPeZ4I1MJpd285dx/DjfzEi3kdQNZ9RSwzdSw5l2chlCsMS4P2KsXw8D2ksNQ6Umw9B6Se2Mcfk4Ks2dHwD9iKU3xlASA227e+EqIT7aTReRQtCUcBdH8Jv6ESxLkUPIqCzx+r9G+rBkfrhQVe+ISuorVW1BcAvJ1zO4ZzKw4LInP9080bU9a+ul3G3aF+MIv4lhiyWya4FrbTqsnkAX+2uPsXxtahdfSzEuJ19jzo0+sSv/SVKTQzSUpMYxGUbSWde+azXHTMixG3B7mjF2lZsqIocxAZ8/XFX3FZEJEdIeL3fd6ggyTLyM8YfMdat0C0y4sagkB74C7zOwTDAnk4lDiKuSGLPjnMVHn/rGdO7r6elyeRlJHUtMUpKuDRT+YN5bxSQ7vo3Mtp9eBfoTk7TRVmwwgGfwDmY+G/i9EF/rpopoQUQ+UtWpBPNrvFVVu4p4Z3IpIE6GwiUFKHNUhFVQvRIXkpUYw4ogGKSqB0RgBdk1BO3xERHJVDN7DeDaxCSaLVvtt4B6kqR2KVrDJPU4jNFRJuT4H+B3GZLjlpgoPl5RS1YCxwjx7918E1kkAj5/ABHYalXVtsA/XXeGhiaqGoryV68MGiOoBlMBPKqqLYsoIC0xZ3JBVz4PZXHviwBb/LSCYQ9P9LuvGTCKpO5bYGLcjaS+hklXlYnZ++XAacQkbcJeJdEM4/rR0ee2M4X4BByijMdCKOMauzgtluzXt7K/uevOUBGKq0zJE6SIjAUmBixmW+A5Va0ugoA0wjjkbxuwqDdFZFLG7UZ8Opig36ePmka/D30jxbUCRpPUUwpAjLuQ1ITt014ZPPETcAQxucov6fFG5FiN2Zrfzee2YUL8ATfHRF72PyO4sU6Vlf2diiD7gskW0931Zkq5Dro74AjS4voQyugKjFTVpgUUkMaYkG4HFakNngUQhYduf4cO83y9IRoD/yGpI0hq+5BJsR5JPYykjsQY8sTILCXZRGAfYjIyo/Y25DgS/5RaTwCXuPmpZFAbQhktgdGqunsBZb8C+Dfm7NHh11gd8Pn+jiB/xgjSOMdniB5WULYtgIC0xxjU9AqhuPEikkvorA1bVJsvWcXz/3iLpsvTjssBwBSSeg/JAGe3Sa0iqYdYZ//ZmNBfh2dIjGonxv2JydQMyXEzS45+UYrGYfwdFYdSwQvAZyGU0wZ4U1WPLoDst7L1PtV1nye+Dfh8XDW47YRk0alXYqwsc8EYEeme50HXD3g+pOIWYtxHHsmHhZuqHg/cRXhpbQ4VkZy2mpTERGDDynl8p5b0+duhLGpUlWkRUzBblu9gAjfMJrZRjNuk1gNaY/wnt7Pv2gs4hNwyw08GziSW+fcqiRbAS/hbCX4CdCt2MABV7YjJe5krthWRGUWs/x4E85FtISILs3znAIIb622M4cBgEfkxD+1zOMZVqW2euuBrEemYY91OBe4v9Hs96tKA4EFJvgJ6isjMuq5BYjWokSEV1xxj8PJGmBauqrqnqr4MJEMkx0Su5GixiUDsP3U+r131Bq0Xrcz0+c7rFxOYLc8fSKqS1KUkdQ2wFhMtZ4L97r8CfXMgx5XAZcAeWZLjNhjfy/3SCFIfFymnZPGEXaCFhYHAF6p6Xlh2Caq6t6qOtHNUW9dlaefzlQTL2gImbdiHqnp2rv1YNhqkrWN7qwlsFnLRY4B7gGdFZEmWdWoEHAmcRrAQcqmwANhZRHJ2RVASzTH+k5vkf/y6dWMOu7Tbss/bNq0usqysw1gqX0Esu5Wgktjd7ir4TUjfWM1xWhQmBqdBZq9B2vfuDrxPiD5wFvOBB4DHRPzziKaoUzPgGIyLUqECpJeFBmnr8xQQ1pb3MruI+gCYhzECSqsFlHqggF+uOmaq6rkYf7gwcaj9rVDVsRjLuUnAVNvYyzDnYtUYi89OmJxuh2K2EvNFMmcEIUezQoovVBIP8otsFx3mLeXDS16u7nZlr6ff7bT5kXmYeNJhrdU4ryEmWZ8xKYljLbFWp9Ecuwvx2W7NXvKy/5GqXm93KMJES2AQxl96npX9jzAp5b7j58TtDTA7T53srkpXTE7RCtc7OeN/IRJktV2kZLVQqSxDQXlAVXuRH+uwhhijml4R+NQ7ROSpkMq6ATj9l8LcYPU6xg95dbet7zpyv29bNLoW+H8F+K55dsV+KzGZlQMxVmDC46WbKB05lh+uBHpjwiTmA62BY+3PIf8YCQwrZgXqlWnDnmm3W8oVb5M+k0U2WuRUvPMgbj/nrOf6EJO+dlWcAFaF/D1L7PsPB9oSk7/kSI7tgNEZkOOHwEGOHMtucbwa4yLkzpLLoz8nEyxjU2BUlmnDLrfWYu8Qbpb7KGAK0F9Ewiap64ATSb0lNFRJvCAxGQeMs7FRj8Jk4zgE2DrLd823JDUGk31kfLp8jRmQ4wDgTtLHsn0dOFaI/4RDOcr+dFU9DmO1XOVapORxu5VrR5AhC8pcVe1tJ+BysRr7CuglspEbRXha5OdK4h5SpwCrDzykJA4Q4suJyULMNqiJNpPUrTD5IrfDbEM1sT/FHIYvwSS4/QqYTEwWhFVvJdEG4zJzVAa3/xs4W4ivcvNOWZPkKFU9xWdXxKF08BDGen3rYry8sswFZaqqdsdkeCh1TfIroIeI5HNb8DJMRvNWKa7tBtyrJE76lSN9TL7FOPYWLGeikqjCuJdcjokX64d1wCAhfoubb+oMST5mE6LfUYLV/xRjANTL9aMsVdVLNyzGC4x6daCBpwIHE8z0vNh4F+gqkv25XJZa5A/4n22eCNyoJKRYDaEkREn0x7jz3JgBOc4FejtyrJOT6512zK4uoWrPAX6H2XVx+FmLfMYRZP4E5RvMWdnjJVj9h63mWJC0S0L84TTtdCFwt7UWLSQx1rPE+AHwNJllXn8F2E2Ij3JzTN3VJIF+lIbhzrdA32L6sUa0DxXjR/5Zod9drw418lIROR6Tc3F5CVR5KXCmiJwskj6/YcgYiNnS9cIZwMs2p2K+ibGFkhiE8Tt7Gtgjg8dWYpJg93X5HB1E5DVgH6Jt2T4F6JZNRp461oc/YtzMvnQEmd+G/hcmFuhbEa7mG8CeIjK8KFjBY8gAAAMWSURBVG1EfCHG6GWRz229gE+UxGlKItRxpCQaKYljlcSTmC2nGzEGQJngLWAPIT7MBR132Ejup2HclK7FBKGIEkYCB9rjIAfvPpyNycTzkiPI/Db0ZEyUm1MwocaigtnYsFQi8mVR24j4p5gQeX7adivgPkuUA5VETqnClER9JbG3krhYSbyEcQN5AhOmq2GGxSzEWOAeKsQnu+nEIYXcrxKRIZhAAv+LQJWWYna0jhQJz7K7DmiSh1tZX5jv91XW4YZW4EFVfRyzv30xxbN0nY6JZnO/iERm+1eIj1ESv7Mr3EY+t+6MyVBwi5J4E+Pf+Akw8xeLsaa2nPZAO/vf3YFdA4zF1RhfqWuE+Hw3hThkIPsfqurBmJyB19jxW0goxgVlcJ6t0su1/9YBd9u5+88Ya/ZWjiDz09jLgX+p6t3A8Zjzt25kEcg9gJC8aYnlcRFZE8n2IT5KSfTAJFdOd+bYEBOQvU8BqrY+VuvfhPh0N2045LBAflpVn7EayTmYM6587qqttmP2OhH5zPVC4D5cAPxdVa+zfTcAc/QTmt97NgS5kNzTj3xXAo29xq7qHlXVdkAcE3NxX8ILOLwWk/bpaeDRUlk9CvHxSmIfTILlg4tcnaWYjAM3lSkxriFYmp9iL7RWBaz/uiIQ5UhgpKq2AX6P8QXeLySyVGC8JcbHRGRuhs99n2M7BplTlgTou6LNZTbE4PpUYqjqdhi/7V0xtgtbWQ2zMVmm2RMc/Ee3ySPW1WqVXTDR+juR/mxsFSbbxxTgc6stvp1tuqxItYVx7bgQGEr+MpR4YQrmvPNeIe7OaxzyLffNMK5h3exEuxPmCCYdac4EvsC4JIwDRhfKRcshH8qBQy7CI0AbuxppgnFWF6tlL7W/7+xeefl9vwkK/jfM2W0+413OwvhkPi7E33Ejz6HIcl//F3LfGONStARYDHxfBJcsB0eQDhElyq0wZ7YnADuGUOQCjHXhGOBlIe58whwcHBxBOpQ8We4K9AAOwlgFdsAkkN0YazEuHPMx59IzMBa8k+xvmvNddHBwiAr+Dx8PrLPKUiy3AAAAAElFTkSuQmCC"),o.poster?(s==null?void 0:s())??null:null]),g=({canvas:A,currentTime:T})=>{const{id:b,format:y,type:x="question"}=o,E=Math.max(0,T-d),S=i({id:b,currentTime:E});if(S){const R=u.naturalWidth/u.naturalHeight,w=A.width/A.height<=9/16,I=w?100:60,O=!w&&((n==null?void 0:n.title)||(n==null?void 0:n.subTitle)),P=w?!!h:!!h||O;ut(x==="question"?{canvas:A,offscreenCanvas:l,elements:[{w:"fill",h:"fill",gap:w?I:32,padding:w?I:32,node:{type:"box",background:"#7900c6"},elements:[{w:"fill",h:"fill",elements:[{enabled:!!P,w:"fill",h:w?180:120,radius:{topLeft:40,topRight:40},padding:{top:30,right:50,bottom:30,left:50},direction:"row",align:"center",justify:w?"center":"start",node:{type:"box",background:"#FFFFFF"},elements:[{enabled:!!O,w:"fill",gap:8,justify:"center",elements:[{enabled:!!(n!=null&&n.title),node:{type:"text",text:n==null?void 0:n.title,color:"#000000",font:"bold 28px Roobert, Dejavu Sans, sans-serif"}},{enabled:!!(n!=null&&n.subTitle),node:{type:"text",text:n==null?void 0:n.subTitle,color:"#000000",font:"24px Roobert, Dejavu Sans, sans-serif"}}]},{enabled:!!h,w:w?100:60,h:w?100:60,node:{type:"image",source:h}}]},{w:"fill",h:"fill",radius:P?{bottomRight:40,bottomLeft:40}:40,node:{format:y,type:"video",source:S}}]},{w:"fill",h:"auto",align:w?"center":"start",elements:[{w:I*R,h:I,node:{type:"image",source:u}}]}]}]}:{canvas:A,offscreenCanvas:l,elements:[{w:"fill",h:"fill",node:{format:y,type:"video",source:S}}]})}},p=f&&(({canvas:A,context:T,currentTime:b})=>{if(b<=e/2){const{format:y}=o;T.save(),T.globalAlpha=(e/2-b)/(e/2),ut({canvas:A,offscreenCanvas:l,elements:[{w:"fill",h:"fill",node:{format:y,type:"video",source:f}}]}),T.restore()}}),m=o.captions?({canvas:A,context:T,currentTime:b})=>{const{start:y,captions:x}=o,E=Math.max(0,b-d)+y;x&&t&&gs({canvas:A,context:T,currentTime:E,vttCaptions:x})}:null;return[{id:o.id,start:d,duration:o.duration,draw:[g,m,p].filter(Boolean),video:o,audio:[{url:o.src,start:o.start,duration:o.duration}],transitionCanvas:await St()}].filter(Boolean)}))).flatMap(n=>n)}/**
4
+ `),[n,o]=i.match(Bc)||[];return{start:n,end:o,text:s}}):[]}function fs(r){const[e,t,i]=r.split(":");return i?parseInt(e)*60*60+parseInt(t)*60+parseFloat(i):parseInt(e)*60+parseInt(t)}function gs({canvas:r,context:e,currentTime:t,vttCaptions:i}){if(i){const s=to(i).find(({start:n,end:o})=>n&&o&&t>=fs(n)&&t<fs(o));if(s){const n=Math.min(r.width,r.height);let o=[""];const a=r.width*.9,l=n*.05;e.font=`${l}px Roobert, Dejavu Sans, sans-serif`,e.textBaseline="middle",s.text.split(" ").forEach(c=>{const d=o.length-1,h=e.measureText(o[d]).width,u=e.measureText(` ${c}`).width;h+u<a?o[d]=`${o[d]} ${c}`:o=[...o,c]}),o.forEach((c,d)=>{const h=c.trim(),u=e.measureText(h),f=(r.width-u.width)/2,g=r.height*.85-(l+n*.04)*(o.length-1-d),p=l*.8,m=l/1.5,A=(r.width-u.width-m)/2,x=g-p,b=u.width+m,y=p*2,T=e.globalAlpha;e.save(),e.globalCompositeOperation="source-over",e.globalAlpha=.8*T,e.fillStyle="#000000",e.beginPath(),e.roundRect(A,x,b,y,n*.01),e.fill(),e.closePath(),e.globalAlpha=T,e.fillStyle="#FFFFFF",e.fillText(h,f,g),e.restore()})}}}const It=1.8;function Ni(r){return typeof r=="number"?{top:r,right:r,bottom:r,left:r}:{top:0,right:0,bottom:0,left:0,...r}}function Uc(r,e=1){return typeof r=="number"?{topLeft:r*e,topRight:r*e,bottomRight:r*e,bottomLeft:r*e}:{topLeft:((r==null?void 0:r.topLeft)??0)*e,topRight:((r==null?void 0:r.topRight)??0)*e,bottomRight:((r==null?void 0:r.bottomRight)??0)*e,bottomLeft:((r==null?void 0:r.bottomLeft)??0)*e}}function ps(r,e){return typeof r=="number"?r:typeof r=="function"?r(e):null}function ms(r,e){const{w:t,gap:i=0,padding:s=0,direction:n="column",elements:o}=r,{right:a,left:l}=Ni(s);if(t){const c=ps(t,e);if(c)return c}if(o){const c=o.length;if(n==="row")return a+l+i*(c-1)+o.reduce((d,h)=>d+=ms(h,e),0);if(n==="column"){let d=0;return o.forEach(h=>{const u=a+l+ms(h,e);u>d&&(d=u)}),d}}return 0}function Hc(r,e,t){const{w:i=0,gap:s=0,padding:n=0,direction:o="column"}=r,{right:a,left:l}=Ni(n),c=e.length,d=e.reduce((u,f)=>{const{w:g}=f;if(g){const p=ps(g,t);if(p)return u+=p}return g==="auto"?u+=ms(f,t):u},0),h=e.filter(({w:u})=>u==="fill").length;return e.reduce((u,f)=>{const{w:g}=f,p=i-a-l,m=Math.min(p,ms(f,t));if(g==="fill"){if(o==="row"){const A=(i-d-a-l-s*(c-1))/h;return u=[...u,A]}if(o==="column")return u=[...u,p]}return u=[...u,m]},[])}function vs(r,e){const{h:t,gap:i=0,padding:s=0,direction:n="column",elements:o}=r,{top:a,bottom:l}=Ni(s);if(t){const c=ps(t,e);if(c)return c}if(o){const c=o.length;if(n==="row"){let d=0;return o.forEach(h=>{const u=a+l+vs(h,e);u>d&&(d=u)}),d}if(n==="column")return a+l+i*(c-1)+o.reduce((d,h)=>d+=vs(h,e),0)}return 0}function Gc(r,e,t){const{h:i=0,gap:s=0,padding:n=0,direction:o="column"}=r,{top:a,bottom:l}=Ni(n),c=e.length,d=e.reduce((u,f)=>{const{h:g}=f;if(g){const p=ps(g,t);if(p)return u+=p}return g==="auto"?u+=vs(f,t):u},0),h=e.filter(({h:u})=>u==="fill").length;return e.reduce((u,f)=>{const{h:g}=f,p=i-a-l,m=Math.min(p,vs(f,t));if(g==="fill"){if(o==="row")return u=[...u,p];if(o==="column"){const A=(i-d-a-l-s*(c-1))/h;return u=[...u,A]}}return u=[...u,m]},[])}function io({canvas:r,offscreenCanvas:e,debug:t=!1,origin:{x:i=0,y:s=0,w:n=r.width,h:o=r.height}={},parent:a,elements:l=[]}){const c=Math.min(n,o)/1080,d={x:0,y:0,w:n/c,h:o/c,gap:0,padding:0,direction:"column",align:"start",justify:"start",...a},{x:h,y:u,w:f,h:g,gap:p,padding:m,direction:A,align:x,justify:b}=d,{top:y,right:T,bottom:E,left:S}=Ni(m);l.map((R,w)=>{const I=r.getContext("2d",{alpha:!1});if(I){const O=l.length,{x:P,y:B,radius:J,elements:H=[],draw:V}=R,{topLeft:j,topRight:F,bottomRight:U,bottomLeft:Q}=Uc(J,c),Y=Hc(d,l,{context:I}),z=Gc(d,l,{context:I}),[K,X,ie]=Y.reduce((be,Le,He)=>(He<w&&(be[0]=be[0]+=Le),He>w&&(be[1]=be[1]+=Le),be[2]=be[2]+=Le,be),[0,0,0]),[ee,ne,se]=z.reduce((be,Le,He)=>(He<w&&(be[0]=be[0]+=Le),He>w&&(be[1]=be[1]+=Le),be[2]=be[2]+=Le,be),[0,0,0]),ye=Y[w],he=z[w],_e={"row|start|start":S+K+p*w,"row|center|start":S+K+p*w,"row|end|start":S+K+p*w,"row|start|center":f/2-ie/2-p*(O-1)/2+K+p*w,"row|center|center":f/2-ie/2-p*(O-1)/2+K+p*w,"row|end|center":f/2-ie/2-p*(O-1)/2+K+p*w,"row|start|end":f-T-ye-X-p*(O-w),"row|center|end":f-T-ye-X-p*(O-w),"row|end|end":f-T-ye-X-p*(O-w),"column|start|start":S,"column|center|start":f/2-ye/2,"column|end|start":f-T-ye-X,"column|start|center":S,"column|center|center":f/2-ye/2,"column|end|center":f-T-ye-X,"column|start|end":S,"column|center|end":f/2-ye/2,"column|end|end":f-T-ye-X},Pt={"row|start|start":y,"row|center|start":g/2-he/2,"row|end|start":g-E-he-ne,"row|start|center":y,"row|center|center":g/2-he/2,"row|end|center":g-E-he-ne,"row|start|end":y,"row|center|end":g/2-he/2,"row|end|end":g-E-he-ne,"column|start|start":y+ee+p*w,"column|center|start":y+ee+p*w,"column|end|start":y+ee+p*w,"column|start|center":g/2-se/2-p*(O-1)/2+ee+p*w,"column|center|center":g/2-se/2-p*(O-1)+ee+p*w,"column|end|center":g/2-se/2-p*(O-1)+ee+p*w,"column|start|end":g-E-he-ne-p*(O-w),"column|center|end":g-E-he-ne-p*(O-w),"column|end|end":g-E-he-ne-p*(O-w)},Tt=h+(P??_e[`${A}|${x}|${b}`]),Ot=u+(B??Pt[`${A}|${x}|${b}`]),Te=i+Tt*c,Ae=s+Ot*c,Ue=ye*c,ue=he*c;V&&(I.save(),J&&(I.beginPath(),I.moveTo(Te+Math.min(ue/It,j),Ae),I.lineTo(Te+Ue-Math.min(ue/It,F),Ae),I.quadraticCurveTo(Te+Ue,Ae,Te+Ue,Ae+Math.min(ue/It,F)),I.lineTo(Te+Ue,Ae+ue-Math.min(ue/It,U)),I.quadraticCurveTo(Te+Ue,Ae+ue,Te+Ue-Math.min(ue/It,U),Ae+ue),I.lineTo(Te+Math.min(ue/It,Q),Ae+ue),I.quadraticCurveTo(Te,Ae+ue,Te,Ae+ue-Math.min(ue/It,Q)),I.lineTo(Te,Ae+Math.min(ue/It,j)),I.quadraticCurveTo(Te,Ae,Te+Math.min(ue/It,j),Ae),I.closePath(),t&&(I.strokeStyle="blue",I.stroke()),I.clip()),V({scale:c,canvas:r,offscreenCanvas:e,context:I,dx:Te,dy:Ae,dw:Ue,dh:ue}),t&&(I.strokeStyle="red",I.strokeRect(Te,Ae,Ue,ue)),I.restore()),io({canvas:r,offscreenCanvas:e,debug:t,origin:{x:i,y:s,w:n,h:o},parent:{...R,x:Tt,y:Ot,w:ye,h:he},elements:H})}})}function Vc(r){return io(r)}function cr({context:r,node:e,maxW:t=1/0}){const i=(e.text??"").split(" ");return i.slice(1).reduce((s,n)=>{const o=`${s[s.length-1].text} ${n}`.trim(),a=r.measureText(o);return a.width>t?s=[...s,{text:n,metrics:r.measureText(n)}]:s[s.length-1]={text:o,metrics:a},s},[{text:i[0],metrics:r.measureText(i[0])}])}function so(r){return r.map(({enabled:e=!0,node:t,...i})=>{if(e)return{...i,...(t==null?void 0:t.type)==="text"&&t.text?{w:t.fill?"fill":({context:s})=>t&&t.type==="text"&&t.text?(s.font=t.font,s.textBaseline="top",Math.ceil(s.measureText(t.text).width)):0,h:t.fill?"fill":()=>{var s,n;if(t&&t.type==="text"){const o=/(?<value>\d+\.?\d*)/;return parseFloat(((n=(s=t.font.match(o))==null?void 0:s.groups)==null?void 0:n.value)??"0")}return 0}}:{},elements:i.elements?so(i.elements):void 0,draw:({canvas:s,offscreenCanvas:n,context:o,dx:a,dy:l,dw:c,dh:d,scale:h})=>{var u,f,g,p,m,A,x,b;if(t){const{type:y,enabled:T=!0}=t;if(T){if(y==="box"&&(o.fillStyle=t.background,o.fillRect(a,l,c,d)),y==="text"&&t.text){const E=/(?<value>\d+\.?\d*)/;let S=0;const R=parseFloat(((f=(u=t.font.match(E))==null?void 0:u.groups)==null?void 0:f.value)??"0")*h;if(t.fill){const{minSize:w,maxSize:I}=t.fill;S=w*h,o.font=t.font.replace(E,S.toString());const O=10*h;let P=0,B=cr({context:o,node:t,maxW:c});for(;S+O<I*h&&(B.length+1)*(S+O)<d;)if(S+=O,o.font=t.font.replace(E,S.toString()),B=cr({context:o,node:t,maxW:c}),P=B.reduce((J,H)=>(H.metrics.width>J&&(J=H.metrics.width),J),0),P>c){S-=O;break}o.font=t.font.replace(E,S.toString())}else S=R,o.font=t.font.replace(E,R.toString());o.textBaseline="top",o.fillStyle=t.color,t.wrap?cr({context:o,node:t,maxW:c}).forEach((w,I)=>{o.fillText(w.text,a,l+S*I)}):o.fillText(t.text,a,l)}if(y==="image"&&t.source&&o.drawImage(t.source,a,l,c,d),y==="video"&&t.source){const E=((g=t.source)==null?void 0:g.naturalWidth)??((p=t.source)==null?void 0:p.videoWidth)??((m=t.source)==null?void 0:m.width),S=((A=t.source)==null?void 0:A.naturalHeight)??((x=t.source)==null?void 0:x.videoHeight)??((b=t.source)==null?void 0:b.height);if(E&&S){const{resolution:R,aspectRatio:w}=Fi({resolution:Math.min(E,S),aspectRatio:E/S}),{dx:I,dy:O,dw:P,dh:B}=Fc({offscreenCanvas:n,context:o,source:t.source,format:t.format??"letterbox",videoResolution:R,videoAspectRatio:w,posX:a,posY:l,width:c,height:d});t.elements&&ut({canvas:s,offscreenCanvas:n,origin:{x:Math.max(a,a+I),y:Math.max(l,l+O),w:Math.min(c,P),h:Math.min(d,B)},elements:t.elements})}}if(y==="gradient"){const E=o.createLinearGradient(a+c,l,a+c,l+d);t.stops.forEach(S=>{E.addColorStop(S.percent,S.color)}),o.fillStyle=E,o.fillRect(a,l,c,d)}}}}}}).filter(Boolean)}function ut({elements:r,...e}){return Vc({...e,elements:so(r)})}async function jc({parts:r,transitionDuration:e=.3333333333333333,burnCaptions:t=!1,getVideoSource:i,getPosterSource:s}){return(await Promise.all(r.map(async({header:n,video:o},a)=>{const l=await St(),c=r.reduce((p,{video:m},A)=>(A<a&&(p+=m.duration-e/2),p),0),d=Math.max(0,c),[h]=await Promise.all([o.poster?(s==null?void 0:s())??null:null]),u=({canvas:p,currentTime:m})=>{const{id:A,format:x}=o,{title:b,subTitle:y}=n??{},T=Math.max(0,m-d),E=i({id:A,currentTime:T});E&&ut({canvas:p,offscreenCanvas:l,elements:[{w:"fill",h:"fill",node:{format:x,type:"video",source:E,elements:[{w:"fill",h:"fill",gap:12,padding:{left:135,bottom:216},justify:"end",elements:[{enabled:!!b,h:44,node:{type:"text",color:"#FFFFFF",text:b,font:"44px CiscoSansTT, Roobert, Dejavu Sans, sans-serif"}},{enabled:!!y,h:28,node:{type:"text",color:"#FFFFFF",text:y,font:"28px CiscoSansTT, Roobert, Dejavu Sans, sans-serif"}}]}]}}]})},f=h&&(({canvas:p,context:m,currentTime:A})=>{if(A<=e/2){const{format:x}=o;m.save(),m.globalAlpha=(e/2-A)/(e/2),ut({canvas:p,offscreenCanvas:l,elements:[{w:"fill",h:"fill",node:{format:x,type:"video",source:h}}]}),m.restore()}}),g=o.captions?({canvas:p,context:m,currentTime:A})=>{const{start:x,captions:b}=o,y=Math.max(0,A-d)+x;b&&t&&gs({canvas:p,context:m,currentTime:y,vttCaptions:b})}:null;return[{id:o.id,start:d,duration:o.duration,draw:[u,g,f].filter(Boolean),video:o,audio:[{url:o.src,start:o.start,duration:o.duration}],transitionCanvas:await St()}].filter(Boolean)}))).flatMap(n=>n)}function dr({header:r,logoSource:e,brandLogo:t,showBackground:i=!0}){const s=!!(r!=null&&r.title),n=!!(r!=null&&r.subTitle),o=r==null?void 0:r.showWatermark,a=!o&&!!t&&(r==null?void 0:r.showBrandLogo),l=!!e||!!t||o||a||s||n,c=e?(e==null?void 0:e.naturalWidth)??e.width:0,d=e?(e==null?void 0:e.naturalHeight)??e.height:0,h=c/d,u=t?(t==null?void 0:t.naturalWidth)??t.width:0,f=t?(t==null?void 0:t.naturalHeight)??t.height:0,g=u/f;return[{enabled:l,w:"fill",h:162,padding:36,justify:"center",elements:[{w:"fill",gap:36,direction:"row",align:"center",elements:[{w:"fill",gap:24,direction:"row",align:"center",elements:[{enabled:!!e,w:h>=1?90:90*h,h:h<1?90:90/h,radius:15,node:{type:"image",source:e}},{enabled:s||n,gap:8,elements:[{enabled:s,h:36,node:{type:"text",text:r==null?void 0:r.title,color:(r==null?void 0:r.color)??"#FFFFFF",font:"bold 36px Roobert, Dejavu Sans, sans-serif"}},{enabled:n,h:36,node:{type:"text",text:r==null?void 0:r.subTitle,color:(r==null?void 0:r.color)??"rgba(255, 255, 255, .8)",font:"36px Roobert, Dejavu Sans, sans-serif"}}]}]},{enabled:a,w:g>=1?90:90*g,h:g<1?90:90/g,radius:15,node:{type:"image",source:t}},{enabled:o,gap:10,padding:14,w:"auto",h:"auto",radius:500,direction:"row",elements:[{node:{type:"text",text:"Made using",color:"rgba(255, 255, 255, .4)",font:"bold 28px Roobert, Dejavu Sans, sans-serif"}},{node:{type:"text",text:"vouch",color:"rgba(255, 255, 255, 1)",font:"bold 30px Roobert, Dejavu Sans, sans-serif"}}],node:{type:"box",background:"rgba(0, 0, 0, 0.2)"}}]}],node:{enabled:i,type:"gradient",stops:[{percent:0,color:"rgba(0, 0, 0, 0.5)"},{percent:.8,color:"rgba(0, 0, 0, 0.05)"},{percent:1,color:"rgba(0, 0, 0, 0)"}]}}]}async function zc(){if(typeof window>"u"){const r=await Promise.resolve().then(()=>Rc);return new r.Image}return new Image}async function li(r){return new Promise(e=>{zc().then(t=>{t.onload=()=>{e(t)},t.onerror=()=>{e(null)},t.src=r})})}async function Wc({parts:r,transitionDuration:e=.3333333333333333,burnCaptions:t=!1,getVideoSource:i,getPosterSource:s}){return Promise.all(r.map(async({card:n,header:o,video:a},l)=>{const c=await St(),d=r.reduce((x,{video:b},y)=>(y<l&&(x+=b.duration-e/2),x),0),h=Math.max(0,d),[u,f,g]=await Promise.all([o&&o.logoSrc?li(o.logoSrc):null,o&&o.brandLogo?li(o.brandLogo):null,a.poster?(s==null?void 0:s())??null:null]),p=({canvas:x,currentTime:b})=>{const{id:y,format:T}=a,E=Math.max(0,b-h),S=i({id:y,currentTime:E});if(S){const R=x.width/x.height<1;ut({canvas:x,offscreenCanvas:c,elements:[{w:"fill",h:"fill",direction:R?"column":"row",elements:[{enabled:!!(n!=null&&n.title),w:"fill",h:"fill",padding:{top:96,right:48,bottom:96,left:48},elements:[{node:{type:"text",text:n==null?void 0:n.title,wrap:!0,color:(n==null?void 0:n.color)??"#000000",font:"bold 72px Roobert, Dejavu Sans, sans-serif"}}],node:{type:"box",background:(n==null?void 0:n.background)??"#FFFFFF"}},{w:"fill",h:"fill",node:{format:T,type:"video",source:S,elements:dr({header:o,logoSource:u,brandLogo:f})}}]}]})}},m=g&&(({canvas:x,context:b,currentTime:y})=>{if(y<=e/2){const{format:T}=a,E=x.width/x.height<1;b.save(),b.globalAlpha=(e/2-y)/(e/2),ut({canvas:x,offscreenCanvas:c,elements:[{w:"fill",h:"fill",direction:E?"column":"row",elements:[{enabled:!!(n!=null&&n.title),w:"fill",h:"fill"},{w:"fill",h:"fill",node:{format:T,type:"video",source:g}}]}]}),b.restore()}}),A=a.captions?({canvas:x,context:b,currentTime:y})=>{const{start:T,captions:E}=a,S=Math.max(0,y-h)+T;E&&t&&gs({canvas:x,context:b,currentTime:S,vttCaptions:E})}:null;return{id:a.id,start:h,duration:a.duration,draw:[p,A,m].filter(Boolean),audio:[{url:a.src,start:a.start,duration:a.duration}],video:a,transitionCanvas:await St()}}))}async function ro({parts:r,transitionDuration:e=.3333333333333333,burnCaptions:t=!1,getVideoSource:i,getPosterSource:s}){return(await Promise.all(r.map(async({card:n,header:o,video:a},l)=>{const c=await St(),d=(n==null?void 0:n.duration)??0,h=r.reduce((T,{card:E,video:S},R)=>(R<l&&(E!=null&&E.duration&&E!=null&&E.title&&(T+=(E==null?void 0:E.duration)-e/2),T+=S.duration-e/2),T),0),u=Math.max(0,h),f=Math.max(0,h+(n!=null&&n.duration?d-e/2:0)),[g,p,m]=await Promise.all([o&&o.logoSrc?li(o.logoSrc):null,o&&o.brandLogo?li(o.brandLogo):null,a.poster?(s==null?void 0:s())??null:null]),A=n&&n!=null&&n.title?({canvas:T})=>{ut({canvas:T,offscreenCanvas:c,elements:[{enabled:!!(n!=null&&n.title),w:"fill",h:"fill",padding:{top:148,right:48,bottom:148,left:48},elements:[{node:{type:"text",text:n.title,wrap:!0,fill:{minSize:48,maxSize:128},color:(n==null?void 0:n.color)??"#000000",font:"bold 72px Roobert, Dejavu Sans, sans-serif"}}],node:{type:"box",background:(n==null?void 0:n.background)??"#FFFFFF"}},{x:0,y:0,w:"fill",elements:dr({header:{showBrandLogo:n.showBrandLogo,showWatermark:n.showWatermark},showBackground:!1})}]})}:null,x=({canvas:T,currentTime:E})=>{const{id:S,format:R}=a,w=Math.max(0,E-f),I=i({id:S,currentTime:w});I&&ut({canvas:T,offscreenCanvas:c,elements:[{w:"fill",h:"fill",node:{format:R,type:"video",source:I,elements:dr({header:o,logoSource:g,brandLogo:p})}}]})},b=m&&(({canvas:T,context:E,currentTime:S})=>{if(S<=e/2){const{format:R}=a;E.save(),E.globalAlpha=(e/2-S)/(e/2),ut({canvas:T,offscreenCanvas:c,elements:[{w:"fill",h:"fill",node:{format:R,type:"video",source:m}}]}),E.restore()}}),y=a.captions?({canvas:T,context:E,currentTime:S})=>{const{start:R,captions:w}=a,I=Math.max(0,S-f)+R;w&&t&&gs({canvas:T,context:E,currentTime:I,vttCaptions:w})}:null;return[A&&{id:Math.random(),start:u,duration:d,draw:[A].filter(Boolean),video:null,audio:[{url:null,start:u,duration:d}],transitionCanvas:await St()},{id:a.id,start:f,duration:a.duration,draw:[x,!n&&b,y].filter(Boolean),video:a,audio:[{url:a.src,start:a.start,duration:a.duration}],transitionCanvas:await St()}].filter(Boolean)}))).flatMap(n=>n)}async function Yc({parts:r,transitionDuration:e=.3333333333333333,burnCaptions:t=!1,getVideoSource:i,getPosterSource:s}){return(await Promise.all(r.map(async({header:n,video:o},a)=>{const l=await St(),c=r.reduce((A,{video:x},b)=>(b<a&&(A+=x.duration-e/2),A),0),d=Math.max(0,c),[h,u,f]=await Promise.all([n&&n.logoSrc?li(n.logoSrc):null,li("data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAcgAAABkCAYAAAACCKDLAAAA1XpUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHjabVFbEsMgCPz3FD0CsEbxOObRmd6gxy8G0iaZMuOygi6gaXu/nukxTKApT1VLK4XMcstNuhElt74jU95xt0WD8TWeSo5LYiGYh2+1uOcjHhcOz93YdBLSJRLzNdGigOhNSNxhdDT4GkIthCCe4BDoPhaVpvU8wrzR1dRXGiDLd24vetvnaq+3TlYHIhsYZAhkbwBjIaEbqYYMtYNswcHJ0I/CH+TfO9H4meg27apKPhB+iei6nqdIH5aeY0HBEdYQAAABg2lDQ1BJQ0MgcHJvZmlsZQAAeJx9kT1Iw0AcxV/TSkWqgnYQcchQneyiIo5ahSJUCLVCqw4ml35Bk4YkxcVRcC04+LFYdXBx1tXBVRAEP0BcXZwUXaTE/yWFFjEeHPfj3b3H3TtAaFSYZoVmAU23zXQyIWZzq2L4FWEMQEAIfTKzjDlJSsF3fN0jwNe7OM/yP/fn6FXzFgMCIvEsM0ybeIN4etM2OO8TR1lJVonPicdNuiDxI9cVj984F10WeGbUzKTniaPEYrGDlQ5mJVMjniKOqZpO+ULWY5XzFmetUmOte/IXRvL6yjLXaY4giUUsQYIIBTWUUYGNOK06KRbStJ/w8Q+7folcCrnKYORYQBUaZNcP/ge/u7UKkxNeUiQBdL04zscoEN4FmnXH+T52nOYJEHwGrvS2v9oAZj5Jr7e12BHQvw1cXLc1ZQ+43AGGngzZlF0pSFMoFID3M/qmHDB4C/Sseb219nH6AGSoq9QNcHAIjBUpe93n3d2dvf17ptXfDwvRcn2L19pvAAAQ7mlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4KPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNC40LjAtRXhpdjIiPgogPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iCiAgICB4bWxuczpzdEV2dD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlRXZlbnQjIgogICAgeG1sbnM6R0lNUD0iaHR0cDovL3d3dy5naW1wLm9yZy94bXAvIgogICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICAgeG1sbnM6cGhvdG9zaG9wPSJodHRwOi8vbnMuYWRvYmUuY29tL3Bob3Rvc2hvcC8xLjAvIgogICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iCiAgIHhtcE1NOkRvY3VtZW50SUQ9ImFkb2JlOmRvY2lkOnBob3Rvc2hvcDplMTMwZTA5My1jZGRmLWFiNDktYmFkNC00ZjA4OWYzYzU3NWUiCiAgIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NDhjZjZkOGEtZjdhNi00ODkzLTgyM2QtYzQwNWY1MzM0ZWVhIgogICB4bXBNTTpPcmlnaW5hbERvY3VtZW50SUQ9InhtcC5kaWQ6YTZkNjgyMjktNWJmNC00ODQ2LTgzOTMtYjZiZTQxZWZhMDBmIgogICBHSU1QOkFQST0iMi4wIgogICBHSU1QOlBsYXRmb3JtPSJNYWMgT1MiCiAgIEdJTVA6VGltZVN0YW1wPSIxNjg5NjQ2MjM3NjQ2MjA4IgogICBHSU1QOlZlcnNpb249IjIuMTAuMzQiCiAgIGRjOkZvcm1hdD0iaW1hZ2UvcG5nIgogICBwaG90b3Nob3A6Q29sb3JNb2RlPSIzIgogICBwaG90b3Nob3A6SUNDUHJvZmlsZT0ic1JHQiBJRUM2MTk2Ni0yLjEiCiAgIHRpZmY6T3JpZW50YXRpb249IjEiCiAgIHhtcDpDcmVhdGVEYXRlPSIyMDIzLTA3LTEyVDE4OjA4OjE1KzA1OjMwIgogICB4bXA6Q3JlYXRvclRvb2w9IkdJTVAgMi4xMCIKICAgeG1wOk1ldGFkYXRhRGF0ZT0iMjAyMzowNzoxOFQxMjoxMDozNCsxMDowMCIKICAgeG1wOk1vZGlmeURhdGU9IjIwMjM6MDc6MThUMTI6MTA6MzQrMTA6MDAiPgogICA8eG1wTU06SGlzdG9yeT4KICAgIDxyZGY6U2VxPgogICAgIDxyZGY6bGkKICAgICAgc3RFdnQ6YWN0aW9uPSJjcmVhdGVkIgogICAgICBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOmE2ZDY4MjI5LTViZjQtNDg0Ni04MzkzLWI2YmU0MWVmYTAwZiIKICAgICAgc3RFdnQ6c29mdHdhcmVBZ2VudD0iQWRvYmUgUGhvdG9zaG9wIDI0LjMgKE1hY2ludG9zaCkiCiAgICAgIHN0RXZ0OndoZW49IjIwMjMtMDctMTJUMTg6MDg6MTUrMDU6MzAiLz4KICAgICA8cmRmOmxpCiAgICAgIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiCiAgICAgIHN0RXZ0OmNoYW5nZWQ9Ii8iCiAgICAgIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6MTI0OTRmODgtMWM4Mi00OThmLWI3N2YtNDEwYzc2ZWJmMTRlIgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJBZG9iZSBQaG90b3Nob3AgMjQuMyAoTWFjaW50b3NoKSIKICAgICAgc3RFdnQ6d2hlbj0iMjAyMy0wNy0xMlQxODo0NTo1NyswNTozMCIvPgogICAgIDxyZGY6bGkKICAgICAgc3RFdnQ6YWN0aW9uPSJzYXZlZCIKICAgICAgc3RFdnQ6Y2hhbmdlZD0iLyIKICAgICAgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDo5N2JjNWI1MC1hOWQ1LTQzOTQtODU2Zi1lNDcxMDUyNzJlZTEiCiAgICAgIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyNC4zIChNYWNpbnRvc2gpIgogICAgICBzdEV2dDp3aGVuPSIyMDIzLTA3LTEyVDE5OjQ5OjEwKzA1OjMwIi8+CiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InNhdmVkIgogICAgICBzdEV2dDpjaGFuZ2VkPSIvIgogICAgICBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjI5YzlmOWY5LWUwOWQtNGRlOS04YmVhLWViNmU1NWM1ZWQxMyIKICAgICAgc3RFdnQ6c29mdHdhcmVBZ2VudD0iR2ltcCAyLjEwIChNYWMgT1MpIgogICAgICBzdEV2dDp3aGVuPSIyMDIzLTA3LTE4VDEyOjEwOjM3KzEwOjAwIi8+CiAgICA8L3JkZjpTZXE+CiAgIDwveG1wTU06SGlzdG9yeT4KICA8L3JkZjpEZXNjcmlwdGlvbj4KIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAKPD94cGFja2V0IGVuZD0idyI/Pv0Rie8AAAAGYktHRAD/AP8A/6C9p5MAAAAJcEhZcwAALiMAAC4jAXilP3YAAAAHdElNRQfnBxICCiU9yio9AAAgAElEQVR42u2dd7gURfb3P4d7L+GCBAFFQUBFTIs5oiJh4UVcFQPO6OrquorhXRO6V1zWwJrWi7qmNaCua57B7GJWEJVFxIBiQERAQBQRRHI+vz+qQNDpntA9Mz1z6/s884i3u6urq+rUt07VCeDg4ODg4PALqOohqnq7qk5W1WVq8IOqjlXVIarattzbQIrU8PWB7YEO9lcNNMvg0YSITHZD18HBoYyJaQ+gf46PLxSRmwO+fyvgPuCwNLeuBK4GrhORta7ncm/wBqraV1VvVdV3VXWl5ob+rjUdHBzKfL48VXPHjIDv3k5VZ2X5zsdUtaIc+6Iyzx29N3AOcDzQxA19BwcHh8gSc0PgOaBdlo/GganAZeXWJvXy1ND7q+po4D3gNEeODg4ODpHH+cCuOT47WFU7OYL0J8aWqvow8A7Q3Y03BwcHh5LBuQGerQTOcgTpTY7dgUnA7904c3BwcCgdWMOgoFap/RxBpm7cM4BXgK3cUHNwcHAoOewSQhk7q2qVI8hNyfFsYDhQ5caYg4ODQ0lii5DKae0I8mdyPBm4w40tBwcHh5LG8pDKWeIIkg171sPduHJwcHAoecwMoYzFIrKonBolJz9IVW0AJIGGblw5ODg4lDzeBlYB9QOU8VpYlVHVw4FHcnz8JxHpUDSCBC4BOrsx5eDg4FD6EJHFqvpf4NgAxTwaYpWqyCz8aF6R9RarqrayBOng4ODgUD74Gya+ai4YBzxVbg2SiwY5CBNcPB9YAyz1ub7ajWGHcoCSiG20Wn9IiP/XtYpDkbXIydYr4d9ZPjoXOFFE1tVpgrQ+LmeE9O6fgBEY/8kPgO9FZIkbpg51gByHYLIgrMcAJXGOEL/TtY5DkUnyflVdC9yZoSL0GdBfRGaUY3tku8XaG2gV8J3rgOuAdiIyUESeEJFpjhwd6gg5NgGGpLg0VEmIayGHCJDkg5iYrPcCCz1u+xK4GNhLRL4s17bIdos1aLqp1cAAEXnWDUOHOorfAo1S/L010Jgy8yNzKFmSnAGcYbdc9+LnvL3zgCkiMrUutEO2BNkt4PsudOToUMdxhMffpwlxR44OUSPKNcC79lfnkDFBqurmwI4B3jUJs6/t4FD6SGoDIAZsh8mFN4KYrPKVIbOF6hXQ2RnpODiUsAYZNNfXneVo5eRQJ8mxGfAmsNtGfz2XpPYi5nuWvj/QxhGkg0NpIBsjne0DvutF19wOZYLBvyBHgP2AC9M85+WEvRh4yzWrg0PpEuTmAd6zqFzNgB3qnPZYCfzR4+ohaZ4+xuPvLwvxVa5xHRxKlyCDBAeY55raoUzQB9jS49r3Xg8pib0x55Wp8KRrVgeH0ibIxgHes8A1tUOZ4E8+1/yI7niPv68ARrpmdXDYBPWjUIl6BXrPMtffDiWPpLYBjvS4Oh943kN7rAec6PHcC869w8HhV9gxCpWodP2QPVS1BdAeaGE16yaAYJy8l2CiT8wSkfmutcoKp/nIzIM+bh7dgHYe1x6PyJgWW8f1DuHVmGwKP2HiIy8BpovId3VY7rfBWCE3sW2z2UYyvxSYA8x01vqB27kx3uf8jiAj1lkdge7AQUAXYAcyNFhS1YXAFOBTjFvAG85YqYh9WUtb4O/AgcB3wD+lJkP3iqRWAAN97rjP55qX9ricIm2vqmpboIcd2/tj3LgaZvDcEjumx2Esb0eJyLwylPtOG7XPLpj0fpnYYaxU1S+Bj4DRwOtO5jNu8ypM1J4bgG2jUCdRVS2xdrxQRG7Oc0ftA5yAMcvvEHLxXwNPA4+IyHtOLApGjs2Aj63mvzGOl5oMtLikHo13Op//EZODUr6XRANLxs1TXH5MiJ+YYkE2PcfPHCoiV/qM66aY4AYnYSxuw4j9ug54HUgAI0o5prKq7g6cjDkv3ibEoicDDwAPiMi3GdTjVOD+XOcXEemY4/fn9b2qejNwfimNiXo4rO+8Jqp6kap+AUzApPXqkIdXdQAuACao6hf2nU1cD+QdZ6YgR0gdODwVzvO5drvPtSM8yBHgPwUa281V9UpgJjAcs+UrIc4hva0G/bWq/t3mjC0VuW+oqgNVdSIwEbgoZHIE2AmToGG2qj6lqns6cXQEWSoC0kpVrwFmW9W+cwFf39m+c5aqXlVKE0uJaY+C9/Zo+tV2UnfHbLWlwnf4W696Wb3OAV7L89gWqxV8BVxB/jO0bw5cBkxT1fNUtTLCcl9fVf9stfW7gd0LNN8eDXygqgl7pungCDKyAjLYTh5/LcDk4YfmmGzeU1X1L3Yv3iE89MM7EtRHGTzvFyFnuJdxjpJoh/GbTIWHhPi6PI7vNsDLmC2zzQvc3psBtwDvq+pvIij7vTGxoW/DO/RfvhEDPlPVs5x4OoKMmoAciNlOuQ5oGqGqNQNq7Qpz/3y95M7aS05+5OrzH7un9qK6IpwX+Vz7dxrtsR3eRjargbt8nj7VR8YeyOP43tuO795FbvfdgPFWi42C3G+mqv/BJGnvHIEqNQHutNuumzk6ih7qlBWrqlYAQ4FLI744+A0wVlX/DlwjImvDKPTuOwZWdV78zZzuXN/KuuHGd6ntOezVZodsdeWZQ8vSF09r2QtjjZgKC4BkmiLOB7w0+seJpTa6sL6Pp3k8N0GIf56nMd4TE/i8OiJdUA3cr6pdgItFRIsk+3thXGq2i+AwPRrYQVUPE5HZjpacBlkMAWmNsbYbUiLfvZ7MX7SpxgKj+Y8Vz3SX5zc55+zKqCZ7zp8xpq5qj1LDCh/tsTnGuMcL1/tcOwxvU/X78/St+0SMHDfGIOAO629ZaNmPA2MjSo4bL4rHqWp7R0uOIAstIDtjEn4eWoLV720FJ2g2FdpVTUmZ8LpD1We/Kct+r6U93iHe1gC3piniAsx5Wiq8SEw+9nn2bI+/LwMeydMnHx5RclyPs4B/Flj2LwIeIwMfzwigHTAK2MJRkyPIQgnIPhgn/Y4l/BmdgbftNlXOWFVRkTK+YRNdLGXa/UPxPkZISg2zfLTHppYgvXCd55gjsS3eiZETQnxRHZ5zzlfVcwok+4MxVuKlhO0xwSwcHEHmXUC6YLZVy8F9og0wKghJLqusX5maIMvv+FFr6YRx+vbCsDRFnIO3ZfM4YvJWGk3Ja9Fxh5t2uCXfvoCqeoHfIibiaOCGiCPIfJPj9na7omkZfVYrzJlk9v5TSa2cW9U6ZX83ZnE5DoG/Yc5xU+FZqfFx7zBnjxf7lP0PH+2xGjjd4/IEIf6+m3aoBB5S1YZ5kv3jKPBWroMjyFIix+bAC2WiOf4SbYHnbUDfbNB8Xr3WKS80lsVlZc2steySRnscmqaIC4CWHtc+B9/4rafg7Xd4m5tyNmBXTFCBsGW/C/Cga14HR5CpBUSAhymsn9MiTNaDQqEL/sGxU6HFvIrUBCmsE60tK8OAa33G9rNSw4c+2mOrNNrjlcRSuypY1w6voALzgBFuytkEg1S1XYiy3wTjytGogN+w1Mr+Wted5Ydy9IO8AGPNlw98i9m2HYOJxPHlL1Na2VRYnSyJHQL0IvzYjgAxVX1NRO7NVIP8tmIrv+vtge/LQHvsDhwVQHv8K97JwSfin57qCEy2l1S4W4ivjFhzfWrH8wRgqh3f6/fbm9rdis7AAUDfPIzjhhiDlNNCKu968pdHcPFGsj/Rttfsjf06VbWRba/OmOw/Pe084FCiyNh60QY7viLH94wRke4F0B53soM3zEPutXblfy8mXdW6LOskVlhOx0RkCTOM3FJgVxH5Ou2dSe3ec8Wo0a/P7eV1x3FS4xtTtBTIsQJ4D9jDqxWkhrhPG22L2UL1Gj9HE5NnPN9P4i3g4BSXVgMdhHgmmRw6kns2j0zHzH3AnSIyOctxfDDGr/SoEOuzBugoIt8ElP2DMem3wsYYjGHVf0VkeY5z0qkYw61ChLOMbDaPLOvSH5P1KBf8JCLNw6hH2WyxWgG+J2RyTAKdReREERmVSyJUEVEReVtETrWaZZghxhrjH+psE0yp8t113qkMhsFZPuS4ChNByQ//8Bk/E4BnfcjxAA9yBBN39dsItM+DwPYicn425LjROH5LRPrbnZGwIgFV2n4LIvsVwJ0ht9U7wIEi0l1ERuRCjrbdJovIYKt9Xwk+gSkcIodyOoOM+0xQ2eIboKeIxEVkWmjqushMS5TdgBkhFdtXVTPZUm42u6IdS8Qzs9auJa49bgFc7XPLLVLjo5kltSveQQUALvE6e7S43OfaTUVunsXAABE5RUTmhjCO3wb2g9B2HAYGzPxxKiYSTRhYhome1FVE3glR9heLyFBM8uWxjnocQRZSe6wPXBNSca8De4jI6HzVV0TewmTOfjmkIoeparq+lDRaZKmflfwT77yL8zGGO17kKMCNPmW/SMx7PCiJPTGh5VLhBSH+aRHb5QfgtyLyRMhjeAkmI8VjIRS3hV005iL7lRiXnjDwFbCfiAzPV8xYEZmOSZ3m3FAcQRYMp+Id9zIbjAD6icgP+a6wiPwIHBnSBLNzGu1nAz6r2sXr0i5aS0kmbtZafod3xg2Ay6WGhT7XT8YYoqTmv/Rbs35n87VFbJqVQH8ReTdPY3itlb3/hVBc/xyfO5ZwomR9bLXGTwsg+2tEZBDwF0dBjiDzrT3Wwz8gdaZ4HjhRJHVuvzwJyio7OY8MobiLM7npvQb7+I2FriVIjs3xP3/6AJMQ10t7bIF/OLJ7iclHPtpjF7yNVsYI8WIGgh8kImMLMIZ/jzH+CYIjcnwuDJKZarXsglpxi8gNmHNJB0eQeUMvgvs8TgKODyutVA6r8BjwScCi9lbV/dLd9G5931sOLsH+vwMT5NlL+ztLanx91K4GWntcW0T67Tu/68UMdTaG8A1XvMbwDPy2sDNDR1XdKsvF8d7A3gHfuwg4TETmFaOT7LlkwlGRI8h84aSAz68A4iKyrFgfYN99AmZLLAj8oscsBni//t4sF08/6t6l1PFaywm23bxwq9QwwUd73Ad/C8qriXlrFUpiL7y3tscL8ZeL2DwXFTj34q2Y/JpBkG2S8BNCqPdZIjK1yEP5TPLr2uNQFwnSRs44NmAx14jIZ8X+FhH5BJ8Yn5lOGKrq5We5BGCV1Gdsg4M8JyitZesSIcdO+Lu4zMA4/XuRYyUw3EcGvgBuSVMNv3yQxczI8LqIvF/g8bsEE8EqCPbLQvaFDM/dffC8iDwWAdlfBPx/R0eOIMNGP7yjnmSCmUQrHU4tMCfA8y0x0TtSYcMZ0YuNDvOUVYzhUNTJsRHGxaCpp3IHp0kNfrsClwB+GSXOIeZ9Hq0kegG/9dEeXyhiE91dpPcGJchOWdy7L8Ei+6zBJHGOBETkReAVR0mOIMNEz4DPDxORFRESkmXAzQGL8QqVs2H765lqX4PBASXQ73cBu/lcv0FqGO2jPf4Gf7/FR4jJKB9ylDTa/uAits1K4MUivft9jFtJruiYxb3dAtZ1hIhMidi4vspRkiPIqBDkInIPq5RPDAeW56FNNhghTKvcjg/q7+X1fA+tZbsIa4+XAH/wuWUiflkiklph+72+xx0LSW8VfRzgZQ48Soi/UcQmGme3O4uxwFtHMJePDlnce0jA6t4UtbFtAzB84GjJEWTwiVK1Ld6BoTPBUyKyNIJC8hPwXIAi9lTVX289xmR19cq1G7Tlp6qP8awCcHZEyfG4NJrbEiAmNb7GTpf6kBtADTHvaDNKomGaOvy1yM30bpHf/2GAZ1sWiCC/KPQZbRZ41NGSI8gwEDS01BMR/ranAvZpyrBxm61YvWj9vx9ufBLqHat+oPUvjBI59iR9nr8/Sg1TfLTHrvj7nb2KCUrvh4vAU8N+XIiPL3JTfVHk9wexxqywcVXTLY7bAC3KVPajXDdHkCWEIGlt1pGfyP9h4c2Az6f0C222bPUGzejryg681Kiv1/NNgZoIkeP+mEDhfnn+bpIan8klqc3t6txrAl4MnO4Xb1VJbAMM8bi8iuKePa7HrCK/f07A5zfL4J4dAr7jjagKvs3M8zUOjiDzQQIZ4hNrWh1VIfmOYMHMU7ZN9cq1mwjezZtd4FfGhVpLu2K3hSXHV8A3DN4LGRD6cPzPuC4iJjPTlHGjD0nfJsSnRWD4/FDk9xcicXinIEMKGBfxuS3q9XMEWQLoGODZL0rg+yaH3TaNVq39cuP/f6VRHybW98oORUOK5y6wnhz7YpLUNvW57VPgBN9oOUk9B3/r3OdIs7WqJHr4lLEA/0wihcSqOvD+IO4ds6Joe1CC85MjyIgjSGDtr0rg+6aH3TbVq9b8yoDj0ua+0dD6aS1/KhI5/sESV7XPbTOBvlLDIh9y7Ia/68wc4E9ptlargNt8yhgixBdGZNwspfzRrMxl/yscHEEGRBAjkvkl8H1BtspSTiArqip+dbb5UqO+vNrQN8Lcv7Q28wgnIRBjfa3lVkxi6ao07fNbqWG2DzluAzzuU44CJxNLm71lMN75Mt/HbN86FA7VAZ5dWALft9B1sSPIYmqQy0rg+4LUMaWhw9jLW89pN3/Zr7YiL9r8Rtbgma+2AfCMDe2Wb3LcFmOgdG4Gi4eeUsOXPuTYCHgak2vQC9f7BQSw2uOOeBvmmGDoxNe5qaSgCBI9a1EJfN9i18WOIIMiyKQkZd43nm3TZdZPv1qdTqrqwvXNLvErbyvgTa1ljzwRY6XWchHmPDFdwOr15DjJhxzFaqB+mR5GkSZTh5KohzmbbOBxy3Ah/p6bRkpK9h0c6gRBBokWUl0C39cowLOe51BdZv6U8mxzaLMrmFux5VdpSHKs1nJayOTYF+PcfkMG3zwd6OpLjgbD8DfKmQnEiKVNbzYI7xRgcyl+UIC6iiC7K81L4PuauS52BBkUQbZKtiiB7wtSR88zjF6T5qY0IV8tVfTYcvQXwLdpFhb3aS2vay17BdQY+2st72Dihu6ZwWPjgYN8t1WN9ngx/qHiVgLHpjt3VBI74W+Z+mchvsBNIUVBEEOkFiXwfS1cF0cDlSVc9yAH2duVwPcFqaPnGUafj797a5v5y86d1fLXSvTnVTt3+6aibe+2a78ZlUab6wm8r7W8gcng8ILU+BIrWksTq40djoll2iaL73kIGCg1rEhDjgOt9uiHM4jJe2nIsT4mqIDX1uoTQtxFPCkegvhadiqB79vedbEjyKAIEm1i5xL4vp0CPOvnsD75qAnfcHvflMFImrRrN7uzfi19gf/i738I0N3+0FpmYPy3ZvPz9ncDYH3M3M457FgsB86TmrTh3yCppwN3prnrCmLyUAbvvdZHq10A/NlNHSUr+1urajMb8ziq2MV1sSPIoAiSqmZnVW0pIpF091DV9hAoio3fNuTkAe/MWn173x28XB/Okhq6ai19MOHdtszwnR0JFrzhl3gbk9PxywzI8WzgjjR33U9M0iYxVhJ98N+iPU+Iz3VTR1ERNGLRQZjoS1FFV9fF0UApn0FODvh8jwh/W498tY0QX33w5B8mtZvvaedwIEndXWoYD+xliaqQWIDJJtI9Q3L8Swbk+ApwZgbk2A7/bAojhPgjbtoo6cUxBM8jm8/F8c5kd/zg4AgyJT4O+PxxEf62IHVbDXzu2+mqH/7xDd9APUMApIY5djKpIZjVcCZYClwP7CA13OUbOs4QYwVJvQmoTVPuu8AxxGR1GnKsAkbgnXJpNnCWmzKKDxGZh7EizhXHq6qUoew7OILcREg+DVDEEaoaOZNvVd0C6BOgiHcziDU5fuDr06ha6+lONoCk7m9JcrXUMAxzJjoc0hjKZI/vMCmoOkoNg6WG9JahSW0MPAlcmObO94A+xDKKvXkzcKDHtXXAH4T4j27KiAyC7GxsAxwaQdkX4CTXtY4gw8KoAM9WR1QjOAfvbPeZ4I1MJpd285dx/DjfzEi3kdQNZ9RSwzdSw5l2chlCsMS4P2KsXw8D2ksNQ6Umw9B6Se2Mcfk4Ks2dHwD9iKU3xlASA227e+EqIT7aTReRQtCUcBdH8Jv6ESxLkUPIqCzx+r9G+rBkfrhQVe+ISuorVW1BcAvJ1zO4ZzKw4LInP9080bU9a+ul3G3aF+MIv4lhiyWya4FrbTqsnkAX+2uPsXxtahdfSzEuJ19jzo0+sSv/SVKTQzSUpMYxGUbSWde+azXHTMixG3B7mjF2lZsqIocxAZ8/XFX3FZEJEdIeL3fd6ggyTLyM8YfMdat0C0y4sagkB74C7zOwTDAnk4lDiKuSGLPjnMVHn/rGdO7r6elyeRlJHUtMUpKuDRT+YN5bxSQ7vo3Mtp9eBfoTk7TRVmwwgGfwDmY+G/i9EF/rpopoQUQ+UtWpBPNrvFVVu4p4Z3IpIE6GwiUFKHNUhFVQvRIXkpUYw4ogGKSqB0RgBdk1BO3xERHJVDN7DeDaxCSaLVvtt4B6kqR2KVrDJPU4jNFRJuT4H+B3GZLjlpgoPl5RS1YCxwjx7918E1kkAj5/ABHYalXVtsA/XXeGhiaqGoryV68MGiOoBlMBPKqqLYsoIC0xZ3JBVz4PZXHviwBb/LSCYQ9P9LuvGTCKpO5bYGLcjaS+hklXlYnZ++XAacQkbcJeJdEM4/rR0ee2M4X4BByijMdCKOMauzgtluzXt7K/uevOUBGKq0zJE6SIjAUmBixmW+A5Va0ugoA0wjjkbxuwqDdFZFLG7UZ8Opig36ePmka/D30jxbUCRpPUUwpAjLuQ1ITt014ZPPETcAQxucov6fFG5FiN2Zrfzee2YUL8ATfHRF72PyO4sU6Vlf2diiD7gskW0931Zkq5Dro74AjS4voQyugKjFTVpgUUkMaYkG4HFakNngUQhYduf4cO83y9IRoD/yGpI0hq+5BJsR5JPYykjsQY8sTILCXZRGAfYjIyo/Y25DgS/5RaTwCXuPmpZFAbQhktgdGqunsBZb8C+Dfm7NHh11gd8Pn+jiB/xgjSOMdniB5WULYtgIC0xxjU9AqhuPEikkvorA1bVJsvWcXz/3iLpsvTjssBwBSSeg/JAGe3Sa0iqYdYZ//ZmNBfh2dIjGonxv2JydQMyXEzS45+UYrGYfwdFYdSwQvAZyGU0wZ4U1WPLoDst7L1PtV1nye+Dfh8XDW47YRk0alXYqwsc8EYEeme50HXD3g+pOIWYtxHHsmHhZuqHg/cRXhpbQ4VkZy2mpTERGDDynl8p5b0+duhLGpUlWkRUzBblu9gAjfMJrZRjNuk1gNaY/wnt7Pv2gs4hNwyw08GziSW+fcqiRbAS/hbCX4CdCt2MABV7YjJe5krthWRGUWs/x4E85FtISILs3znAIIb622M4cBgEfkxD+1zOMZVqW2euuBrEemYY91OBe4v9Hs96tKA4EFJvgJ6isjMuq5BYjWokSEV1xxj8PJGmBauqrqnqr4MJEMkx0Su5GixiUDsP3U+r131Bq0Xrcz0+c7rFxOYLc8fSKqS1KUkdQ2wFhMtZ4L97r8CfXMgx5XAZcAeWZLjNhjfy/3SCFIfFymnZPGEXaCFhYHAF6p6Xlh2Caq6t6qOtHNUW9dlaefzlQTL2gImbdiHqnp2rv1YNhqkrWN7qwlsFnLRY4B7gGdFZEmWdWoEHAmcRrAQcqmwANhZRHJ2RVASzTH+k5vkf/y6dWMOu7Tbss/bNq0usqysw1gqX0Esu5Wgktjd7ir4TUjfWM1xWhQmBqdBZq9B2vfuDrxPiD5wFvOBB4DHRPzziKaoUzPgGIyLUqECpJeFBmnr8xQQ1pb3MruI+gCYhzECSqsFlHqggF+uOmaq6rkYf7gwcaj9rVDVsRjLuUnAVNvYyzDnYtUYi89OmJxuh2K2EvNFMmcEIUezQoovVBIP8otsFx3mLeXDS16u7nZlr6ff7bT5kXmYeNJhrdU4ryEmWZ8xKYljLbFWp9Ecuwvx2W7NXvKy/5GqXm93KMJES2AQxl96npX9jzAp5b7j58TtDTA7T53srkpXTE7RCtc7OeN/IRJktV2kZLVQqSxDQXlAVXuRH+uwhhijml4R+NQ7ROSpkMq6ATj9l8LcYPU6xg95dbet7zpyv29bNLoW+H8F+K55dsV+KzGZlQMxVmDC46WbKB05lh+uBHpjwiTmA62BY+3PIf8YCQwrZgXqlWnDnmm3W8oVb5M+k0U2WuRUvPMgbj/nrOf6EJO+dlWcAFaF/D1L7PsPB9oSk7/kSI7tgNEZkOOHwEGOHMtucbwa4yLkzpLLoz8nEyxjU2BUlmnDLrfWYu8Qbpb7KGAK0F9Ewiap64ATSb0lNFRJvCAxGQeMs7FRj8Jk4zgE2DrLd823JDUGk31kfLp8jRmQ4wDgTtLHsn0dOFaI/4RDOcr+dFU9DmO1XOVapORxu5VrR5AhC8pcVe1tJ+BysRr7CuglspEbRXha5OdK4h5SpwCrDzykJA4Q4suJyULMNqiJNpPUrTD5IrfDbEM1sT/FHIYvwSS4/QqYTEwWhFVvJdEG4zJzVAa3/xs4W4ivcvNOWZPkKFU9xWdXxKF08BDGen3rYry8sswFZaqqdsdkeCh1TfIroIeI5HNb8DJMRvNWKa7tBtyrJE76lSN9TL7FOPYWLGeikqjCuJdcjokX64d1wCAhfoubb+oMST5mE6LfUYLV/xRjANTL9aMsVdVLNyzGC4x6daCBpwIHE8z0vNh4F+gqkv25XJZa5A/4n22eCNyoJKRYDaEkREn0x7jz3JgBOc4FejtyrJOT6512zK4uoWrPAX6H2XVx+FmLfMYRZP4E5RvMWdnjJVj9h63mWJC0S0L84TTtdCFwt7UWLSQx1rPE+AHwNJllXn8F2E2Ij3JzTN3VJIF+lIbhzrdA32L6sUa0DxXjR/5Zod9drw418lIROR6Tc3F5CVR5KXCmiJwskj6/YcgYiNnS9cIZwMs2p2K+ibGFkhiE8Tt7Gtgjg8dWYpJg93X5HB1E5DVgH6Jt2T4F6JZNRp461oc/YtzMvnQEmd+G/hcmFuhbEa7mG8CeIjK8KFjBY8gAAAMWSURBVG1EfCHG6GWRz229gE+UxGlKItRxpCQaKYljlcSTmC2nGzEGQJngLWAPIT7MBR132Ejup2HclK7FBKGIEkYCB9rjIAfvPpyNycTzkiPI/Db0ZEyUm1MwocaigtnYsFQi8mVR24j4p5gQeX7adivgPkuUA5VETqnClER9JbG3krhYSbyEcQN5AhOmq2GGxSzEWOAeKsQnu+nEIYXcrxKRIZhAAv+LQJWWYna0jhQJz7K7DmiSh1tZX5jv91XW4YZW4EFVfRyzv30xxbN0nY6JZnO/iERm+1eIj1ESv7Mr3EY+t+6MyVBwi5J4E+Pf+Akw8xeLsaa2nPZAO/vf3YFdA4zF1RhfqWuE+Hw3hThkIPsfqurBmJyB19jxW0goxgVlcJ6t0su1/9YBd9u5+88Ya/ZWjiDz09jLgX+p6t3A8Zjzt25kEcg9gJC8aYnlcRFZE8n2IT5KSfTAJFdOd+bYEBOQvU8BqrY+VuvfhPh0N2045LBAflpVn7EayTmYM6587qqttmP2OhH5zPVC4D5cAPxdVa+zfTcAc/QTmt97NgS5kNzTj3xXAo29xq7qHlXVdkAcE3NxX8ILOLwWk/bpaeDRUlk9CvHxSmIfTILlg4tcnaWYjAM3lSkxriFYmp9iL7RWBaz/uiIQ5UhgpKq2AX6P8QXeLySyVGC8JcbHRGRuhs99n2M7BplTlgTou6LNZTbE4PpUYqjqdhi/7V0xtgtbWQ2zMVmm2RMc/Ee3ySPW1WqVXTDR+juR/mxsFSbbxxTgc6stvp1tuqxItYVx7bgQGEr+MpR4YQrmvPNeIe7OaxzyLffNMK5h3exEuxPmCCYdac4EvsC4JIwDRhfKRcshH8qBQy7CI0AbuxppgnFWF6tlL7W/7+xeefl9vwkK/jfM2W0+413OwvhkPi7E33Ejz6HIcl//F3LfGONStARYDHxfBJcsB0eQDhElyq0wZ7YnADuGUOQCjHXhGOBlIe58whwcHBxBOpQ8We4K9AAOwlgFdsAkkN0YazEuHPMx59IzMBa8k+xvmvNddHBwiAr+Dx8PrLPKUiy3AAAAAElFTkSuQmCC"),o.poster?(s==null?void 0:s())??null:null]),g=({canvas:A,currentTime:x})=>{const{id:b,format:y,type:T="question"}=o,E=Math.max(0,x-d),S=i({id:b,currentTime:E});if(S){const R=u.naturalWidth/u.naturalHeight,w=A.width/A.height<=9/16,I=w?100:60,O=!w&&((n==null?void 0:n.title)||(n==null?void 0:n.subTitle)),P=w?!!h:!!h||O;ut(T==="question"?{canvas:A,offscreenCanvas:l,elements:[{w:"fill",h:"fill",gap:w?I:32,padding:w?I:32,node:{type:"box",background:"#7900c6"},elements:[{w:"fill",h:"fill",elements:[{enabled:!!P,w:"fill",h:w?180:120,radius:{topLeft:40,topRight:40},padding:{top:30,right:50,bottom:30,left:50},direction:"row",align:"center",justify:w?"center":"start",node:{type:"box",background:"#FFFFFF"},elements:[{enabled:!!O,w:"fill",gap:8,justify:"center",elements:[{enabled:!!(n!=null&&n.title),node:{type:"text",text:n==null?void 0:n.title,color:"#000000",font:"bold 28px Roobert, Dejavu Sans, sans-serif"}},{enabled:!!(n!=null&&n.subTitle),node:{type:"text",text:n==null?void 0:n.subTitle,color:"#000000",font:"24px Roobert, Dejavu Sans, sans-serif"}}]},{enabled:!!h,w:w?100:60,h:w?100:60,node:{type:"image",source:h}}]},{w:"fill",h:"fill",radius:P?{bottomRight:40,bottomLeft:40}:40,node:{format:y,type:"video",source:S}}]},{w:"fill",h:"auto",align:w?"center":"start",elements:[{w:I*R,h:I,node:{type:"image",source:u}}]}]}]}:{canvas:A,offscreenCanvas:l,elements:[{w:"fill",h:"fill",node:{format:y,type:"video",source:S}}]})}},p=f&&(({canvas:A,context:x,currentTime:b})=>{if(b<=e/2){const{format:y}=o;x.save(),x.globalAlpha=(e/2-b)/(e/2),ut({canvas:A,offscreenCanvas:l,elements:[{w:"fill",h:"fill",node:{format:y,type:"video",source:f}}]}),x.restore()}}),m=o.captions?({canvas:A,context:x,currentTime:b})=>{const{start:y,captions:T}=o,E=Math.max(0,b-d)+y;T&&t&&gs({canvas:A,context:x,currentTime:E,vttCaptions:T})}:null;return[{id:o.id,start:d,duration:o.duration,draw:[g,m,p].filter(Boolean),video:o,audio:[{url:o.src,start:o.start,duration:o.duration}],transitionCanvas:await St()}].filter(Boolean)}))).flatMap(n=>n)}/**
5
5
  * @license
6
6
  * Copyright 2019 Google LLC
7
7
  * SPDX-License-Identifier: BSD-3-Clause
@@ -9,17 +9,17 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
9
9
  * @license
10
10
  * Copyright 2017 Google LLC
11
11
  * SPDX-License-Identifier: BSD-3-Clause
12
- */var fr;const As=window,lo=As.trustedTypes,Xc=lo?lo.emptyScript:"",co=As.reactiveElementPolyfillSupport,gr={toAttribute(r,e){switch(e){case Boolean:r=r?Xc:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,e){let t=r;switch(e){case Boolean:t=r!==null;break;case Number:t=r===null?null:Number(r);break;case Object:case Array:try{t=JSON.parse(r)}catch{t=null}}return t}},pr=(r,e)=>e!==r&&(e==e||r==r),mr={attribute:!0,type:String,converter:gr,reflect:!1,hasChanged:pr},vr="finalized";let li=class extends HTMLElement{constructor(){super(),this._$Ei=new Map,this.isUpdatePending=!1,this.hasUpdated=!1,this._$El=null,this.u()}static addInitializer(e){var t;this.finalize(),((t=this.h)!==null&&t!==void 0?t:this.h=[]).push(e)}static get observedAttributes(){this.finalize();const e=[];return this.elementProperties.forEach((t,i)=>{const s=this._$Ep(i,t);s!==void 0&&(this._$Ev.set(s,i),e.push(s))}),e}static createProperty(e,t=mr){if(t.state&&(t.attribute=!1),this.finalize(),this.elementProperties.set(e,t),!t.noAccessor&&!this.prototype.hasOwnProperty(e)){const i=typeof e=="symbol"?Symbol():"__"+e,s=this.getPropertyDescriptor(e,i,t);s!==void 0&&Object.defineProperty(this.prototype,e,s)}}static getPropertyDescriptor(e,t,i){return{get(){return this[t]},set(s){const n=this[e];this[t]=s,this.requestUpdate(e,n,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)||mr}static finalize(){if(this.hasOwnProperty(vr))return!1;this[vr]=!0;const e=Object.getPrototypeOf(this);if(e.finalize(),e.h!==void 0&&(this.h=[...e.h]),this.elementProperties=new Map(e.elementProperties),this._$Ev=new Map,this.hasOwnProperty("properties")){const t=this.properties,i=[...Object.getOwnPropertyNames(t),...Object.getOwnPropertySymbols(t)];for(const s of i)this.createProperty(s,t[s])}return this.elementStyles=this.finalizeStyles(this.styles),!0}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const s of i)t.unshift(ao(s))}else e!==void 0&&t.push(ao(e));return t}static _$Ep(e,t){const i=t.attribute;return i===!1?void 0:typeof i=="string"?i:typeof e=="string"?e.toLowerCase():void 0}u(){var e;this._$E_=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$Eg(),this.requestUpdate(),(e=this.constructor.h)===null||e===void 0||e.forEach(t=>t(this))}addController(e){var t,i;((t=this._$ES)!==null&&t!==void 0?t:this._$ES=[]).push(e),this.renderRoot!==void 0&&this.isConnected&&((i=e.hostConnected)===null||i===void 0||i.call(e))}removeController(e){var t;(t=this._$ES)===null||t===void 0||t.splice(this._$ES.indexOf(e)>>>0,1)}_$Eg(){this.constructor.elementProperties.forEach((e,t)=>{this.hasOwnProperty(t)&&(this._$Ei.set(t,this[t]),delete this[t])})}createRenderRoot(){var e;const t=(e=this.shadowRoot)!==null&&e!==void 0?e:this.attachShadow(this.constructor.shadowRootOptions);return Kc(t,this.constructor.elementStyles),t}connectedCallback(){var e;this.renderRoot===void 0&&(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$ES)===null||e===void 0||e.forEach(t=>{var i;return(i=t.hostConnected)===null||i===void 0?void 0:i.call(t)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$ES)===null||e===void 0||e.forEach(t=>{var i;return(i=t.hostDisconnected)===null||i===void 0?void 0:i.call(t)})}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$EO(e,t,i=mr){var s;const n=this.constructor._$Ep(e,i);if(n!==void 0&&i.reflect===!0){const o=(((s=i.converter)===null||s===void 0?void 0:s.toAttribute)!==void 0?i.converter:gr).toAttribute(t,i.type);this._$El=e,o==null?this.removeAttribute(n):this.setAttribute(n,o),this._$El=null}}_$AK(e,t){var i;const s=this.constructor,n=s._$Ev.get(e);if(n!==void 0&&this._$El!==n){const o=s.getPropertyOptions(n),a=typeof o.converter=="function"?{fromAttribute:o.converter}:((i=o.converter)===null||i===void 0?void 0:i.fromAttribute)!==void 0?o.converter:gr;this._$El=n,this[n]=a.fromAttribute(t,o.type),this._$El=null}}requestUpdate(e,t,i){let s=!0;e!==void 0&&(((i=i||this.constructor.getPropertyOptions(e)).hasChanged||pr)(this[e],t)?(this._$AL.has(e)||this._$AL.set(e,t),i.reflect===!0&&this._$El!==e&&(this._$EC===void 0&&(this._$EC=new Map),this._$EC.set(e,i))):s=!1),!this.isUpdatePending&&s&&(this._$E_=this._$Ej())}async _$Ej(){this.isUpdatePending=!0;try{await this._$E_}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var e;if(!this.isUpdatePending)return;this.hasUpdated,this._$Ei&&(this._$Ei.forEach((s,n)=>this[n]=s),this._$Ei=void 0);let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),(e=this._$ES)===null||e===void 0||e.forEach(s=>{var n;return(n=s.hostUpdate)===null||n===void 0?void 0:n.call(s)}),this.update(i)):this._$Ek()}catch(s){throw t=!1,this._$Ek(),s}t&&this._$AE(i)}willUpdate(e){}_$AE(e){var t;(t=this._$ES)===null||t===void 0||t.forEach(i=>{var s;return(s=i.hostUpdated)===null||s===void 0?void 0:s.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$Ek(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$E_}shouldUpdate(e){return!0}update(e){this._$EC!==void 0&&(this._$EC.forEach((t,i)=>this._$EO(i,this[i],t)),this._$EC=void 0),this._$Ek()}updated(e){}firstUpdated(e){}};li[vr]=!0,li.elementProperties=new Map,li.elementStyles=[],li.shadowRootOptions={mode:"open"},co==null||co({ReactiveElement:li}),((fr=As.reactiveElementVersions)!==null&&fr!==void 0?fr:As.reactiveElementVersions=[]).push("1.6.2");/**
12
+ */var fr;const As=window,lo=As.trustedTypes,Xc=lo?lo.emptyScript:"",co=As.reactiveElementPolyfillSupport,gr={toAttribute(r,e){switch(e){case Boolean:r=r?Xc:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,e){let t=r;switch(e){case Boolean:t=r!==null;break;case Number:t=r===null?null:Number(r);break;case Object:case Array:try{t=JSON.parse(r)}catch{t=null}}return t}},pr=(r,e)=>e!==r&&(e==e||r==r),mr={attribute:!0,type:String,converter:gr,reflect:!1,hasChanged:pr},vr="finalized";let ci=class extends HTMLElement{constructor(){super(),this._$Ei=new Map,this.isUpdatePending=!1,this.hasUpdated=!1,this._$El=null,this.u()}static addInitializer(e){var t;this.finalize(),((t=this.h)!==null&&t!==void 0?t:this.h=[]).push(e)}static get observedAttributes(){this.finalize();const e=[];return this.elementProperties.forEach((t,i)=>{const s=this._$Ep(i,t);s!==void 0&&(this._$Ev.set(s,i),e.push(s))}),e}static createProperty(e,t=mr){if(t.state&&(t.attribute=!1),this.finalize(),this.elementProperties.set(e,t),!t.noAccessor&&!this.prototype.hasOwnProperty(e)){const i=typeof e=="symbol"?Symbol():"__"+e,s=this.getPropertyDescriptor(e,i,t);s!==void 0&&Object.defineProperty(this.prototype,e,s)}}static getPropertyDescriptor(e,t,i){return{get(){return this[t]},set(s){const n=this[e];this[t]=s,this.requestUpdate(e,n,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)||mr}static finalize(){if(this.hasOwnProperty(vr))return!1;this[vr]=!0;const e=Object.getPrototypeOf(this);if(e.finalize(),e.h!==void 0&&(this.h=[...e.h]),this.elementProperties=new Map(e.elementProperties),this._$Ev=new Map,this.hasOwnProperty("properties")){const t=this.properties,i=[...Object.getOwnPropertyNames(t),...Object.getOwnPropertySymbols(t)];for(const s of i)this.createProperty(s,t[s])}return this.elementStyles=this.finalizeStyles(this.styles),!0}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const s of i)t.unshift(ao(s))}else e!==void 0&&t.push(ao(e));return t}static _$Ep(e,t){const i=t.attribute;return i===!1?void 0:typeof i=="string"?i:typeof e=="string"?e.toLowerCase():void 0}u(){var e;this._$E_=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$Eg(),this.requestUpdate(),(e=this.constructor.h)===null||e===void 0||e.forEach(t=>t(this))}addController(e){var t,i;((t=this._$ES)!==null&&t!==void 0?t:this._$ES=[]).push(e),this.renderRoot!==void 0&&this.isConnected&&((i=e.hostConnected)===null||i===void 0||i.call(e))}removeController(e){var t;(t=this._$ES)===null||t===void 0||t.splice(this._$ES.indexOf(e)>>>0,1)}_$Eg(){this.constructor.elementProperties.forEach((e,t)=>{this.hasOwnProperty(t)&&(this._$Ei.set(t,this[t]),delete this[t])})}createRenderRoot(){var e;const t=(e=this.shadowRoot)!==null&&e!==void 0?e:this.attachShadow(this.constructor.shadowRootOptions);return Kc(t,this.constructor.elementStyles),t}connectedCallback(){var e;this.renderRoot===void 0&&(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$ES)===null||e===void 0||e.forEach(t=>{var i;return(i=t.hostConnected)===null||i===void 0?void 0:i.call(t)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$ES)===null||e===void 0||e.forEach(t=>{var i;return(i=t.hostDisconnected)===null||i===void 0?void 0:i.call(t)})}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$EO(e,t,i=mr){var s;const n=this.constructor._$Ep(e,i);if(n!==void 0&&i.reflect===!0){const o=(((s=i.converter)===null||s===void 0?void 0:s.toAttribute)!==void 0?i.converter:gr).toAttribute(t,i.type);this._$El=e,o==null?this.removeAttribute(n):this.setAttribute(n,o),this._$El=null}}_$AK(e,t){var i;const s=this.constructor,n=s._$Ev.get(e);if(n!==void 0&&this._$El!==n){const o=s.getPropertyOptions(n),a=typeof o.converter=="function"?{fromAttribute:o.converter}:((i=o.converter)===null||i===void 0?void 0:i.fromAttribute)!==void 0?o.converter:gr;this._$El=n,this[n]=a.fromAttribute(t,o.type),this._$El=null}}requestUpdate(e,t,i){let s=!0;e!==void 0&&(((i=i||this.constructor.getPropertyOptions(e)).hasChanged||pr)(this[e],t)?(this._$AL.has(e)||this._$AL.set(e,t),i.reflect===!0&&this._$El!==e&&(this._$EC===void 0&&(this._$EC=new Map),this._$EC.set(e,i))):s=!1),!this.isUpdatePending&&s&&(this._$E_=this._$Ej())}async _$Ej(){this.isUpdatePending=!0;try{await this._$E_}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var e;if(!this.isUpdatePending)return;this.hasUpdated,this._$Ei&&(this._$Ei.forEach((s,n)=>this[n]=s),this._$Ei=void 0);let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),(e=this._$ES)===null||e===void 0||e.forEach(s=>{var n;return(n=s.hostUpdate)===null||n===void 0?void 0:n.call(s)}),this.update(i)):this._$Ek()}catch(s){throw t=!1,this._$Ek(),s}t&&this._$AE(i)}willUpdate(e){}_$AE(e){var t;(t=this._$ES)===null||t===void 0||t.forEach(i=>{var s;return(s=i.hostUpdated)===null||s===void 0?void 0:s.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$Ek(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$E_}shouldUpdate(e){return!0}update(e){this._$EC!==void 0&&(this._$EC.forEach((t,i)=>this._$EO(i,this[i],t)),this._$EC=void 0),this._$Ek()}updated(e){}firstUpdated(e){}};ci[vr]=!0,ci.elementProperties=new Map,ci.elementStyles=[],ci.shadowRootOptions={mode:"open"},co==null||co({ReactiveElement:ci}),((fr=As.reactiveElementVersions)!==null&&fr!==void 0?fr:As.reactiveElementVersions=[]).push("1.6.2");/**
13
13
  * @license
14
14
  * Copyright 2017 Google LLC
15
15
  * SPDX-License-Identifier: BSD-3-Clause
16
- */var yr;const bs=window,ci=bs.trustedTypes,ho=ci?ci.createPolicy("lit-html",{createHTML:r=>r}):void 0,xs="$lit$",Ct=`lit$${(Math.random()+"").slice(9)}$`,Ar="?"+Ct,qc=`<${Ar}>`,Kt=document,Ui=()=>Kt.createComment(""),Hi=r=>r===null||typeof r!="object"&&typeof r!="function",uo=Array.isArray,fo=r=>uo(r)||typeof(r==null?void 0:r[Symbol.iterator])=="function",br=`[
16
+ */var yr;const bs=window,di=bs.trustedTypes,ho=di?di.createPolicy("lit-html",{createHTML:r=>r}):void 0,xs="$lit$",Ct=`lit$${(Math.random()+"").slice(9)}$`,Ar="?"+Ct,qc=`<${Ar}>`,Kt=document,Ui=()=>Kt.createComment(""),Hi=r=>r===null||typeof r!="object"&&typeof r!="function",uo=Array.isArray,fo=r=>uo(r)||typeof(r==null?void 0:r[Symbol.iterator])=="function",br=`[
17
17
  \f\r]`,Gi=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,go=/-->/g,po=/>/g,Xt=RegExp(`>|${br}(?:([^\\s"'>=/]+)(${br}*=${br}*(?:[^
18
- \f\r"'\`<>=]|("|')|))|$)`,"g"),mo=/'/g,vo=/"/g,yo=/^(?:script|style|textarea|title)$/i,Zc=r=>(e,...t)=>({_$litType$:r,strings:e,values:t}),te=Zc(1),ot=Symbol.for("lit-noChange"),Ee=Symbol.for("lit-nothing"),Ao=new WeakMap,qt=Kt.createTreeWalker(Kt,129,null,!1),bo=(r,e)=>{const t=r.length-1,i=[];let s,n=e===2?"<svg>":"",o=Gi;for(let l=0;l<t;l++){const c=r[l];let d,h,u=-1,f=0;for(;f<c.length&&(o.lastIndex=f,h=o.exec(c),h!==null);)f=o.lastIndex,o===Gi?h[1]==="!--"?o=go:h[1]!==void 0?o=po:h[2]!==void 0?(yo.test(h[2])&&(s=RegExp("</"+h[2],"g")),o=Xt):h[3]!==void 0&&(o=Xt):o===Xt?h[0]===">"?(o=s??Gi,u=-1):h[1]===void 0?u=-2:(u=o.lastIndex-h[2].length,d=h[1],o=h[3]===void 0?Xt:h[3]==='"'?vo:mo):o===vo||o===mo?o=Xt:o===go||o===po?o=Gi:(o=Xt,s=void 0);const g=o===Xt&&r[l+1].startsWith("/>")?" ":"";n+=o===Gi?c+qc:u>=0?(i.push(d),c.slice(0,u)+xs+c.slice(u)+Ct+g):c+Ct+(u===-2?(i.push(void 0),l):g)}const a=n+(r[t]||"<?>")+(e===2?"</svg>":"");if(!Array.isArray(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return[ho!==void 0?ho.createHTML(a):a,i]};class Vi{constructor({strings:e,_$litType$:t},i){let s;this.parts=[];let n=0,o=0;const a=e.length-1,l=this.parts,[c,d]=bo(e,t);if(this.el=Vi.createElement(c,i),qt.currentNode=this.el.content,t===2){const h=this.el.content,u=h.firstChild;u.remove(),h.append(...u.childNodes)}for(;(s=qt.nextNode())!==null&&l.length<a;){if(s.nodeType===1){if(s.hasAttributes()){const h=[];for(const u of s.getAttributeNames())if(u.endsWith(xs)||u.startsWith(Ct)){const f=d[o++];if(h.push(u),f!==void 0){const g=s.getAttribute(f.toLowerCase()+xs).split(Ct),p=/([.?@])?(.*)/.exec(f);l.push({type:1,index:n,name:p[2],strings:g,ctor:p[1]==="."?To:p[1]==="?"?Eo:p[1]==="@"?So:ji})}else l.push({type:6,index:n})}for(const u of h)s.removeAttribute(u)}if(yo.test(s.tagName)){const h=s.textContent.split(Ct),u=h.length-1;if(u>0){s.textContent=ci?ci.emptyScript:"";for(let f=0;f<u;f++)s.append(h[f],Ui()),qt.nextNode(),l.push({type:2,index:++n});s.append(h[u],Ui())}}}else if(s.nodeType===8)if(s.data===Ar)l.push({type:2,index:n});else{let h=-1;for(;(h=s.data.indexOf(Ct,h+1))!==-1;)l.push({type:7,index:n}),h+=Ct.length-1}n++}}static createElement(e,t){const i=Kt.createElement("template");return i.innerHTML=e,i}}function Zt(r,e,t=r,i){var s,n,o,a;if(e===ot)return e;let l=i!==void 0?(s=t._$Co)===null||s===void 0?void 0:s[i]:t._$Cl;const c=Hi(e)?void 0:e._$litDirective$;return(l==null?void 0:l.constructor)!==c&&((n=l==null?void 0:l._$AO)===null||n===void 0||n.call(l,!1),c===void 0?l=void 0:(l=new c(r),l._$AT(r,t,i)),i!==void 0?((o=(a=t)._$Co)!==null&&o!==void 0?o:a._$Co=[])[i]=l:t._$Cl=l),l!==void 0&&(e=Zt(r,l._$AS(r,e.values),l,i)),e}let xo=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){var t;const{el:{content:i},parts:s}=this._$AD,n=((t=e==null?void 0:e.creationScope)!==null&&t!==void 0?t:Kt).importNode(i,!0);qt.currentNode=n;let o=qt.nextNode(),a=0,l=0,c=s[0];for(;c!==void 0;){if(a===c.index){let d;c.type===2?d=new di(o,o.nextSibling,this,e):c.type===1?d=new c.ctor(o,c.name,c.strings,this,e):c.type===6&&(d=new Io(o,this,e)),this._$AV.push(d),c=s[++l]}a!==(c==null?void 0:c.index)&&(o=qt.nextNode(),a++)}return qt.currentNode=Kt,n}v(e){let t=0;for(const 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++}};class di{constructor(e,t,i,s){var n;this.type=2,this._$AH=Ee,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=i,this.options=s,this._$Cp=(n=s==null?void 0:s.isConnected)===null||n===void 0||n}get _$AU(){var e,t;return(t=(e=this._$AM)===null||e===void 0?void 0:e._$AU)!==null&&t!==void 0?t:this._$Cp}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return t!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=Zt(this,e,t),Hi(e)?e===Ee||e==null||e===""?(this._$AH!==Ee&&this._$AR(),this._$AH=Ee):e!==this._$AH&&e!==ot&&this._(e):e._$litType$!==void 0?this.g(e):e.nodeType!==void 0?this.$(e):fo(e)?this.T(e):this._(e)}k(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}$(e){this._$AH!==e&&(this._$AR(),this._$AH=this.k(e))}_(e){this._$AH!==Ee&&Hi(this._$AH)?this._$AA.nextSibling.data=e:this.$(Kt.createTextNode(e)),this._$AH=e}g(e){var t;const{values:i,_$litType$:s}=e,n=typeof s=="number"?this._$AC(e):(s.el===void 0&&(s.el=Vi.createElement(s.h,this.options)),s);if(((t=this._$AH)===null||t===void 0?void 0:t._$AD)===n)this._$AH.v(i);else{const o=new xo(n,this),a=o.u(this.options);o.v(i),this.$(a),this._$AH=o}}_$AC(e){let t=Ao.get(e.strings);return t===void 0&&Ao.set(e.strings,t=new Vi(e)),t}T(e){uo(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let i,s=0;for(const n of e)s===t.length?t.push(i=new di(this.k(Ui()),this.k(Ui()),this,this.options)):i=t[s],i._$AI(n),s++;s<t.length&&(this._$AR(i&&i._$AB.nextSibling,s),t.length=s)}_$AR(e=this._$AA.nextSibling,t){var i;for((i=this._$AP)===null||i===void 0||i.call(this,!1,!0,t);e&&e!==this._$AB;){const s=e.nextSibling;e.remove(),e=s}}setConnected(e){var t;this._$AM===void 0&&(this._$Cp=e,(t=this._$AP)===null||t===void 0||t.call(this,e))}}class ji{constructor(e,t,i,s,n){this.type=1,this._$AH=Ee,this._$AN=void 0,this.element=e,this.name=t,this._$AM=s,this.options=n,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=Ee}get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}_$AI(e,t=this,i,s){const n=this.strings;let o=!1;if(n===void 0)e=Zt(this,e,t,0),o=!Hi(e)||e!==this._$AH&&e!==ot,o&&(this._$AH=e);else{const a=e;let l,c;for(e=n[0],l=0;l<n.length-1;l++)c=Zt(this,a[i+l],t,l),c===ot&&(c=this._$AH[l]),o||(o=!Hi(c)||c!==this._$AH[l]),c===Ee?e=Ee:e!==Ee&&(e+=(c??"")+n[l+1]),this._$AH[l]=c}o&&!s&&this.j(e)}j(e){e===Ee?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class To extends ji{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===Ee?void 0:e}}const Jc=ci?ci.emptyScript:"";class Eo extends ji{constructor(){super(...arguments),this.type=4}j(e){e&&e!==Ee?this.element.setAttribute(this.name,Jc):this.element.removeAttribute(this.name)}}let So=class extends ji{constructor(e,t,i,s,n){super(e,t,i,s,n),this.type=5}_$AI(e,t=this){var i;if((e=(i=Zt(this,e,t,0))!==null&&i!==void 0?i:Ee)===ot)return;const s=this._$AH,n=e===Ee&&s!==Ee||e.capture!==s.capture||e.once!==s.once||e.passive!==s.passive,o=e!==Ee&&(s===Ee||n);n&&this.element.removeEventListener(this.name,this,s),o&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var t,i;typeof this._$AH=="function"?this._$AH.call((i=(t=this.options)===null||t===void 0?void 0:t.host)!==null&&i!==void 0?i:this.element,e):this._$AH.handleEvent(e)}};class Io{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){Zt(this,e)}}const Qc={O:xs,P:Ct,A:Ar,C:1,M:bo,L:xo,D:fo,R:Zt,I:di,V:ji,H:Eo,N:So,U:To,F:Io},Co=bs.litHtmlPolyfillSupport;Co==null||Co(Vi,di),((yr=bs.litHtmlVersions)!==null&&yr!==void 0?yr:bs.litHtmlVersions=[]).push("2.7.4");const _c=(r,e,t)=>{var i,s;const n=(i=t==null?void 0:t.renderBefore)!==null&&i!==void 0?i:e;let o=n._$litPart$;if(o===void 0){const a=(s=t==null?void 0:t.renderBefore)!==null&&s!==void 0?s:null;n._$litPart$=o=new di(e.insertBefore(Ui(),a),a,void 0,t??{})}return o._$AI(r),o};/**
18
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),mo=/'/g,vo=/"/g,yo=/^(?:script|style|textarea|title)$/i,Zc=r=>(e,...t)=>({_$litType$:r,strings:e,values:t}),te=Zc(1),ot=Symbol.for("lit-noChange"),Ee=Symbol.for("lit-nothing"),Ao=new WeakMap,qt=Kt.createTreeWalker(Kt,129,null,!1),bo=(r,e)=>{const t=r.length-1,i=[];let s,n=e===2?"<svg>":"",o=Gi;for(let l=0;l<t;l++){const c=r[l];let d,h,u=-1,f=0;for(;f<c.length&&(o.lastIndex=f,h=o.exec(c),h!==null);)f=o.lastIndex,o===Gi?h[1]==="!--"?o=go:h[1]!==void 0?o=po:h[2]!==void 0?(yo.test(h[2])&&(s=RegExp("</"+h[2],"g")),o=Xt):h[3]!==void 0&&(o=Xt):o===Xt?h[0]===">"?(o=s??Gi,u=-1):h[1]===void 0?u=-2:(u=o.lastIndex-h[2].length,d=h[1],o=h[3]===void 0?Xt:h[3]==='"'?vo:mo):o===vo||o===mo?o=Xt:o===go||o===po?o=Gi:(o=Xt,s=void 0);const g=o===Xt&&r[l+1].startsWith("/>")?" ":"";n+=o===Gi?c+qc:u>=0?(i.push(d),c.slice(0,u)+xs+c.slice(u)+Ct+g):c+Ct+(u===-2?(i.push(void 0),l):g)}const a=n+(r[t]||"<?>")+(e===2?"</svg>":"");if(!Array.isArray(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return[ho!==void 0?ho.createHTML(a):a,i]};class Vi{constructor({strings:e,_$litType$:t},i){let s;this.parts=[];let n=0,o=0;const a=e.length-1,l=this.parts,[c,d]=bo(e,t);if(this.el=Vi.createElement(c,i),qt.currentNode=this.el.content,t===2){const h=this.el.content,u=h.firstChild;u.remove(),h.append(...u.childNodes)}for(;(s=qt.nextNode())!==null&&l.length<a;){if(s.nodeType===1){if(s.hasAttributes()){const h=[];for(const u of s.getAttributeNames())if(u.endsWith(xs)||u.startsWith(Ct)){const f=d[o++];if(h.push(u),f!==void 0){const g=s.getAttribute(f.toLowerCase()+xs).split(Ct),p=/([.?@])?(.*)/.exec(f);l.push({type:1,index:n,name:p[2],strings:g,ctor:p[1]==="."?To:p[1]==="?"?Eo:p[1]==="@"?So:ji})}else l.push({type:6,index:n})}for(const u of h)s.removeAttribute(u)}if(yo.test(s.tagName)){const h=s.textContent.split(Ct),u=h.length-1;if(u>0){s.textContent=di?di.emptyScript:"";for(let f=0;f<u;f++)s.append(h[f],Ui()),qt.nextNode(),l.push({type:2,index:++n});s.append(h[u],Ui())}}}else if(s.nodeType===8)if(s.data===Ar)l.push({type:2,index:n});else{let h=-1;for(;(h=s.data.indexOf(Ct,h+1))!==-1;)l.push({type:7,index:n}),h+=Ct.length-1}n++}}static createElement(e,t){const i=Kt.createElement("template");return i.innerHTML=e,i}}function Zt(r,e,t=r,i){var s,n,o,a;if(e===ot)return e;let l=i!==void 0?(s=t._$Co)===null||s===void 0?void 0:s[i]:t._$Cl;const c=Hi(e)?void 0:e._$litDirective$;return(l==null?void 0:l.constructor)!==c&&((n=l==null?void 0:l._$AO)===null||n===void 0||n.call(l,!1),c===void 0?l=void 0:(l=new c(r),l._$AT(r,t,i)),i!==void 0?((o=(a=t)._$Co)!==null&&o!==void 0?o:a._$Co=[])[i]=l:t._$Cl=l),l!==void 0&&(e=Zt(r,l._$AS(r,e.values),l,i)),e}let xo=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){var t;const{el:{content:i},parts:s}=this._$AD,n=((t=e==null?void 0:e.creationScope)!==null&&t!==void 0?t:Kt).importNode(i,!0);qt.currentNode=n;let o=qt.nextNode(),a=0,l=0,c=s[0];for(;c!==void 0;){if(a===c.index){let d;c.type===2?d=new hi(o,o.nextSibling,this,e):c.type===1?d=new c.ctor(o,c.name,c.strings,this,e):c.type===6&&(d=new Io(o,this,e)),this._$AV.push(d),c=s[++l]}a!==(c==null?void 0:c.index)&&(o=qt.nextNode(),a++)}return qt.currentNode=Kt,n}v(e){let t=0;for(const 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++}};class hi{constructor(e,t,i,s){var n;this.type=2,this._$AH=Ee,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=i,this.options=s,this._$Cp=(n=s==null?void 0:s.isConnected)===null||n===void 0||n}get _$AU(){var e,t;return(t=(e=this._$AM)===null||e===void 0?void 0:e._$AU)!==null&&t!==void 0?t:this._$Cp}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return t!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=Zt(this,e,t),Hi(e)?e===Ee||e==null||e===""?(this._$AH!==Ee&&this._$AR(),this._$AH=Ee):e!==this._$AH&&e!==ot&&this._(e):e._$litType$!==void 0?this.g(e):e.nodeType!==void 0?this.$(e):fo(e)?this.T(e):this._(e)}k(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}$(e){this._$AH!==e&&(this._$AR(),this._$AH=this.k(e))}_(e){this._$AH!==Ee&&Hi(this._$AH)?this._$AA.nextSibling.data=e:this.$(Kt.createTextNode(e)),this._$AH=e}g(e){var t;const{values:i,_$litType$:s}=e,n=typeof s=="number"?this._$AC(e):(s.el===void 0&&(s.el=Vi.createElement(s.h,this.options)),s);if(((t=this._$AH)===null||t===void 0?void 0:t._$AD)===n)this._$AH.v(i);else{const o=new xo(n,this),a=o.u(this.options);o.v(i),this.$(a),this._$AH=o}}_$AC(e){let t=Ao.get(e.strings);return t===void 0&&Ao.set(e.strings,t=new Vi(e)),t}T(e){uo(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let i,s=0;for(const n of e)s===t.length?t.push(i=new hi(this.k(Ui()),this.k(Ui()),this,this.options)):i=t[s],i._$AI(n),s++;s<t.length&&(this._$AR(i&&i._$AB.nextSibling,s),t.length=s)}_$AR(e=this._$AA.nextSibling,t){var i;for((i=this._$AP)===null||i===void 0||i.call(this,!1,!0,t);e&&e!==this._$AB;){const s=e.nextSibling;e.remove(),e=s}}setConnected(e){var t;this._$AM===void 0&&(this._$Cp=e,(t=this._$AP)===null||t===void 0||t.call(this,e))}}class ji{constructor(e,t,i,s,n){this.type=1,this._$AH=Ee,this._$AN=void 0,this.element=e,this.name=t,this._$AM=s,this.options=n,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=Ee}get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}_$AI(e,t=this,i,s){const n=this.strings;let o=!1;if(n===void 0)e=Zt(this,e,t,0),o=!Hi(e)||e!==this._$AH&&e!==ot,o&&(this._$AH=e);else{const a=e;let l,c;for(e=n[0],l=0;l<n.length-1;l++)c=Zt(this,a[i+l],t,l),c===ot&&(c=this._$AH[l]),o||(o=!Hi(c)||c!==this._$AH[l]),c===Ee?e=Ee:e!==Ee&&(e+=(c??"")+n[l+1]),this._$AH[l]=c}o&&!s&&this.j(e)}j(e){e===Ee?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class To extends ji{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===Ee?void 0:e}}const Jc=di?di.emptyScript:"";class Eo extends ji{constructor(){super(...arguments),this.type=4}j(e){e&&e!==Ee?this.element.setAttribute(this.name,Jc):this.element.removeAttribute(this.name)}}let So=class extends ji{constructor(e,t,i,s,n){super(e,t,i,s,n),this.type=5}_$AI(e,t=this){var i;if((e=(i=Zt(this,e,t,0))!==null&&i!==void 0?i:Ee)===ot)return;const s=this._$AH,n=e===Ee&&s!==Ee||e.capture!==s.capture||e.once!==s.once||e.passive!==s.passive,o=e!==Ee&&(s===Ee||n);n&&this.element.removeEventListener(this.name,this,s),o&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var t,i;typeof this._$AH=="function"?this._$AH.call((i=(t=this.options)===null||t===void 0?void 0:t.host)!==null&&i!==void 0?i:this.element,e):this._$AH.handleEvent(e)}};class Io{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){Zt(this,e)}}const Qc={O:xs,P:Ct,A:Ar,C:1,M:bo,L:xo,D:fo,R:Zt,I:hi,V:ji,H:Eo,N:So,U:To,F:Io},Co=bs.litHtmlPolyfillSupport;Co==null||Co(Vi,hi),((yr=bs.litHtmlVersions)!==null&&yr!==void 0?yr:bs.litHtmlVersions=[]).push("2.7.4");const _c=(r,e,t)=>{var i,s;const n=(i=t==null?void 0:t.renderBefore)!==null&&i!==void 0?i:e;let o=n._$litPart$;if(o===void 0){const a=(s=t==null?void 0:t.renderBefore)!==null&&s!==void 0?s:null;n._$litPart$=o=new hi(e.insertBefore(Ui(),a),a,void 0,t??{})}return o._$AI(r),o};/**
19
19
  * @license
20
20
  * Copyright 2017 Google LLC
21
21
  * SPDX-License-Identifier: BSD-3-Clause
22
- */var xr,Tr;let zi=class extends li{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e,t;const i=super.createRenderRoot();return(e=(t=this.renderOptions).renderBefore)!==null&&e!==void 0||(t.renderBefore=i.firstChild),i}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=_c(t,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),(e=this._$Do)===null||e===void 0||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._$Do)===null||e===void 0||e.setConnected(!1)}render(){return ot}};zi.finalized=!0,zi._$litElement$=!0,(xr=globalThis.litElementHydrateSupport)===null||xr===void 0||xr.call(globalThis,{LitElement:zi});const wo=globalThis.litElementPolyfillSupport;wo==null||wo({LitElement:zi}),((Tr=globalThis.litElementVersions)!==null&&Tr!==void 0?Tr:globalThis.litElementVersions=[]).push("3.3.2");/**
22
+ */var xr,Tr;let zi=class extends ci{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e,t;const i=super.createRenderRoot();return(e=(t=this.renderOptions).renderBefore)!==null&&e!==void 0||(t.renderBefore=i.firstChild),i}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=_c(t,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),(e=this._$Do)===null||e===void 0||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._$Do)===null||e===void 0||e.setConnected(!1)}render(){return ot}};zi.finalized=!0,zi._$litElement$=!0,(xr=globalThis.litElementHydrateSupport)===null||xr===void 0||xr.call(globalThis,{LitElement:zi});const wo=globalThis.litElementPolyfillSupport;wo==null||wo({LitElement:zi}),((Tr=globalThis.litElementVersions)!==null&&Tr!==void 0?Tr:globalThis.litElementVersions=[]).push("3.3.2");/**
23
23
  * @license
24
24
  * Copyright 2017 Google LLC
25
25
  * SPDX-License-Identifier: BSD-3-Clause
@@ -39,11 +39,11 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
39
39
  * @license
40
40
  * Copyright 2017 Google LLC
41
41
  * SPDX-License-Identifier: BSD-3-Clause
42
- */const hi={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},ui=r=>(...e)=>({_$litDirective$:r,values:e});let Wi=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)}};/**
42
+ */const ui={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},fi=r=>(...e)=>({_$litDirective$:r,values:e});let Wi=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)}};/**
43
43
  * @license
44
44
  * Copyright 2018 Google LLC
45
45
  * SPDX-License-Identifier: BSD-3-Clause
46
- */const ge=ui(class extends Wi{constructor(r){var e;if(super(r),r.type!==hi.ATTRIBUTE||r.name!=="class"||((e=r.strings)===null||e===void 0?void 0:e.length)>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(r){return" "+Object.keys(r).filter(e=>r[e]).join(" ")+" "}update(r,[e]){var t,i;if(this.it===void 0){this.it=new Set,r.strings!==void 0&&(this.nt=new Set(r.strings.join(" ").split(/\s/).filter(n=>n!=="")));for(const n in e)e[n]&&!(!((t=this.nt)===null||t===void 0)&&t.has(n))&&this.it.add(n);return this.render(e)}const s=r.element.classList;this.it.forEach(n=>{n in e||(s.remove(n),this.it.delete(n))});for(const n in e){const o=!!e[n];o===this.it.has(n)||!((i=this.nt)===null||i===void 0)&&i.has(n)||(o?(s.add(n),this.it.add(n)):(s.remove(n),this.it.delete(n)))}return ot}});/**
46
+ */const ge=fi(class extends Wi{constructor(r){var e;if(super(r),r.type!==ui.ATTRIBUTE||r.name!=="class"||((e=r.strings)===null||e===void 0?void 0:e.length)>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(r){return" "+Object.keys(r).filter(e=>r[e]).join(" ")+" "}update(r,[e]){var t,i;if(this.it===void 0){this.it=new Set,r.strings!==void 0&&(this.nt=new Set(r.strings.join(" ").split(/\s/).filter(n=>n!=="")));for(const n in e)e[n]&&!(!((t=this.nt)===null||t===void 0)&&t.has(n))&&this.it.add(n);return this.render(e)}const s=r.element.classList;this.it.forEach(n=>{n in e||(s.remove(n),this.it.delete(n))});for(const n in e){const o=!!e[n];o===this.it.has(n)||!((i=this.nt)===null||i===void 0)&&i.has(n)||(o?(s.add(n),this.it.add(n)):(s.remove(n),this.it.delete(n)))}return ot}});/**
47
47
  * @license
48
48
  * Copyright 2018 Google LLC
49
49
  * SPDX-License-Identifier: BSD-3-Clause
@@ -55,29 +55,29 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
55
55
  * @license
56
56
  * Copyright 2017 Google LLC
57
57
  * SPDX-License-Identifier: BSD-3-Clause
58
- */const Ki=(r,e)=>{var t,i;const s=r._$AN;if(s===void 0)return!1;for(const n of s)(i=(t=n)._$AO)===null||i===void 0||i.call(t,e,!1),Ki(n,e);return!0},Ts=r=>{let e,t;do{if((e=r._$AM)===void 0)break;t=e._$AN,t.delete(r),r=e}while((t==null?void 0:t.size)===0)},Ro=r=>{for(let e;e=r._$AM;r=e){let t=e._$AN;if(t===void 0)e._$AN=t=new Set;else if(t.has(r))break;t.add(r),cd(e)}};function ad(r){this._$AN!==void 0?(Ts(this),this._$AM=r,Ro(this)):this._$AM=r}function ld(r,e=!1,t=0){const i=this._$AH,s=this._$AN;if(s!==void 0&&s.size!==0)if(e)if(Array.isArray(i))for(let n=t;n<i.length;n++)Ki(i[n],!1),Ts(i[n]);else i!=null&&(Ki(i,!1),Ts(i));else Ki(this,r)}const cd=r=>{var e,t,i,s;r.type==hi.CHILD&&((e=(i=r)._$AP)!==null&&e!==void 0||(i._$AP=ld),(t=(s=r)._$AQ)!==null&&t!==void 0||(s._$AQ=ad))};let Do=class extends Wi{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,i){super._$AT(e,t,i),Ro(this),this.isConnected=e._$AU}_$AO(e,t=!0){var i,s;e!==this.isConnected&&(this.isConnected=e,e?(i=this.reconnected)===null||i===void 0||i.call(this):(s=this.disconnected)===null||s===void 0||s.call(this)),t&&(Ki(this,e),Ts(this))}setValue(e){if(sd(this._$Ct))this._$Ct._$AI(e,this);else{const t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}};/**
58
+ */const Ki=(r,e)=>{var t,i;const s=r._$AN;if(s===void 0)return!1;for(const n of s)(i=(t=n)._$AO)===null||i===void 0||i.call(t,e,!1),Ki(n,e);return!0},Ts=r=>{let e,t;do{if((e=r._$AM)===void 0)break;t=e._$AN,t.delete(r),r=e}while((t==null?void 0:t.size)===0)},Ro=r=>{for(let e;e=r._$AM;r=e){let t=e._$AN;if(t===void 0)e._$AN=t=new Set;else if(t.has(r))break;t.add(r),cd(e)}};function ad(r){this._$AN!==void 0?(Ts(this),this._$AM=r,Ro(this)):this._$AM=r}function ld(r,e=!1,t=0){const i=this._$AH,s=this._$AN;if(s!==void 0&&s.size!==0)if(e)if(Array.isArray(i))for(let n=t;n<i.length;n++)Ki(i[n],!1),Ts(i[n]);else i!=null&&(Ki(i,!1),Ts(i));else Ki(this,r)}const cd=r=>{var e,t,i,s;r.type==ui.CHILD&&((e=(i=r)._$AP)!==null&&e!==void 0||(i._$AP=ld),(t=(s=r)._$AQ)!==null&&t!==void 0||(s._$AQ=ad))};let Do=class extends Wi{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,i){super._$AT(e,t,i),Ro(this),this.isConnected=e._$AU}_$AO(e,t=!0){var i,s;e!==this.isConnected&&(this.isConnected=e,e?(i=this.reconnected)===null||i===void 0||i.call(this):(s=this.disconnected)===null||s===void 0||s.call(this)),t&&(Ki(this,e),Ts(this))}setValue(e){if(sd(this._$Ct))this._$Ct._$AI(e,this);else{const t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}};/**
59
59
  * @license
60
60
  * Copyright 2020 Google LLC
61
61
  * SPDX-License-Identifier: BSD-3-Clause
62
- */const Ze=()=>new dd;let dd=class{};const Ir=new WeakMap,Je=ui(class extends Do{render(r){return Ee}update(r,[e]){var t;const i=e!==this.G;return i&&this.G!==void 0&&this.ot(void 0),(i||this.rt!==this.lt)&&(this.G=e,this.ct=(t=r.options)===null||t===void 0?void 0:t.host,this.ot(this.lt=r.element)),Ee}ot(r){var e;if(typeof this.G=="function"){const t=(e=this.ct)!==null&&e!==void 0?e:globalThis;let i=Ir.get(t);i===void 0&&(i=new WeakMap,Ir.set(t,i)),i.get(this.G)!==void 0&&this.G.call(this.ct,void 0),i.set(this.G,r),r!==void 0&&this.G.call(this.ct,r)}else this.G.value=r}get rt(){var r,e,t;return typeof this.G=="function"?(e=Ir.get((r=this.ct)!==null&&r!==void 0?r:globalThis))===null||e===void 0?void 0:e.get(this.G):(t=this.G)===null||t===void 0?void 0:t.value}disconnected(){this.rt===this.lt&&this.ot(void 0)}reconnected(){this.ot(this.lt)}});/**
62
+ */const Ze=()=>new dd;let dd=class{};const Ir=new WeakMap,Je=fi(class extends Do{render(r){return Ee}update(r,[e]){var t;const i=e!==this.G;return i&&this.G!==void 0&&this.ot(void 0),(i||this.rt!==this.lt)&&(this.G=e,this.ct=(t=r.options)===null||t===void 0?void 0:t.host,this.ot(this.lt=r.element)),Ee}ot(r){var e;if(typeof this.G=="function"){const t=(e=this.ct)!==null&&e!==void 0?e:globalThis;let i=Ir.get(t);i===void 0&&(i=new WeakMap,Ir.set(t,i)),i.get(this.G)!==void 0&&this.G.call(this.ct,void 0),i.set(this.G,r),r!==void 0&&this.G.call(this.ct,r)}else this.G.value=r}get rt(){var r,e,t;return typeof this.G=="function"?(e=Ir.get((r=this.ct)!==null&&r!==void 0?r:globalThis))===null||e===void 0?void 0:e.get(this.G):(t=this.G)===null||t===void 0?void 0:t.value}disconnected(){this.rt===this.lt&&this.ot(void 0)}reconnected(){this.ot(this.lt)}});/**
63
63
  * @license
64
64
  * Copyright 2017 Google LLC
65
65
  * SPDX-License-Identifier: BSD-3-Clause
66
- */const hd=Symbol();class Cr{constructor(e,t,i){this.i=0,this.status=0,this.autoRun=!0,this.o=e,this.o.addController(this);const s=typeof t=="object"?t:{task:t,args:i};this.t=s.task,this.h=s.args,this.l=s.onComplete,this.u=s.onError,s.autoRun!==void 0&&(this.autoRun=s.autoRun),this.taskComplete=new Promise((n,o)=>{this.v=n,this._=o})}hostUpdated(){this.performTask()}async performTask(){var e;const t=(e=this.h)===null||e===void 0?void 0:e.call(this);this.shouldRun(t)&&await this.run(t)}shouldRun(e){return this.autoRun&&this.k(e)}async run(e){var t,i,s;let n,o;e!=null||(e=(t=this.h)===null||t===void 0?void 0:t.call(this)),this.status!==2&&this.status!==3||(this.taskComplete=new Promise((l,c)=>{this.v=l,this._=c})),this.status=1,queueMicrotask(()=>this.o.requestUpdate());const a=++this.i;try{n=await this.t(e)}catch(l){o=l}if(this.i===a){if(n===hd)this.status=0;else{if(o===void 0){try{(i=this.l)===null||i===void 0||i.call(this,n)}catch{}this.status=2,this.v(n)}else{try{(s=this.u)===null||s===void 0||s.call(this,o)}catch{}this.status=3,this._(o)}this.m=n,this.T=o}this.o.requestUpdate()}}get value(){return this.m}get error(){return this.T}render(e){var t,i,s,n;switch(this.status){case 0:return(t=e.initial)===null||t===void 0?void 0:t.call(e);case 1:return(i=e.pending)===null||i===void 0?void 0:i.call(e);case 2:return(s=e.complete)===null||s===void 0?void 0:s.call(e,this.value);case 3:return(n=e.error)===null||n===void 0?void 0:n.call(e,this.error);default:this.status}}k(e){const t=this.p;return this.p=e,Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.some((i,s)=>pr(i,t[s])):e!==t}}function ud(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var ko={exports:{}};(function(r,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,o=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(l,c,d){if(d=d||{},l=l.trim(),c=c.trim(),!c){if(!d.alwaysNormalize)return l;var h=a.parseURL(l);if(!h)throw new Error("Error trying to parse base URL.");return h.path=a.normalizePath(h.path),a.buildURLFromParts(h)}var u=a.parseURL(c);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return d.alwaysNormalize?(u.path=a.normalizePath(u.path),a.buildURLFromParts(u)):c;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 g=s.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(p.netLoc=f.netLoc,u.path[0]!=="/"))if(!u.path)p.path=f.path,u.params||(p.params=f.params,u.query||(p.query=f.query));else{var m=f.path,A=m.substring(0,m.lastIndexOf("/")+1)+u.path;p.path=a.normalizePath(A)}return p.path===null&&(p.path=d.alwaysNormalize?a.normalizePath(u.path):u.path),a.buildURLFromParts(p)},parseURL:function(l){var c=i.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[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}};r.exports=a})()})(ko);var wr=ko.exports;function Po(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(r);e&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(r,s).enumerable})),t.push.apply(t,i)}return t}function je(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Po(Object(t),!0).forEach(function(i){fd(r,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Po(Object(t)).forEach(function(i){Object.defineProperty(r,i,Object.getOwnPropertyDescriptor(t,i))})}return r}function fd(r,e,t){return e=pd(e),e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function Ce(){return Ce=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(r[i]=t[i])}return r},Ce.apply(this,arguments)}function gd(r,e){if(typeof r!="object"||r===null)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var i=t.call(r,e||"default");if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function pd(r){var e=gd(r,"string");return typeof e=="symbol"?e:String(e)}const W=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)};let v=function(r){return r.MEDIA_ATTACHING="hlsMediaAttaching",r.MEDIA_ATTACHED="hlsMediaAttached",r.MEDIA_DETACHING="hlsMediaDetaching",r.MEDIA_DETACHED="hlsMediaDetached",r.BUFFER_RESET="hlsBufferReset",r.BUFFER_CODECS="hlsBufferCodecs",r.BUFFER_CREATED="hlsBufferCreated",r.BUFFER_APPENDING="hlsBufferAppending",r.BUFFER_APPENDED="hlsBufferAppended",r.BUFFER_EOS="hlsBufferEos",r.BUFFER_FLUSHING="hlsBufferFlushing",r.BUFFER_FLUSHED="hlsBufferFlushed",r.MANIFEST_LOADING="hlsManifestLoading",r.MANIFEST_LOADED="hlsManifestLoaded",r.MANIFEST_PARSED="hlsManifestParsed",r.LEVEL_SWITCHING="hlsLevelSwitching",r.LEVEL_SWITCHED="hlsLevelSwitched",r.LEVEL_LOADING="hlsLevelLoading",r.LEVEL_LOADED="hlsLevelLoaded",r.LEVEL_UPDATED="hlsLevelUpdated",r.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",r.LEVELS_UPDATED="hlsLevelsUpdated",r.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",r.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",r.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",r.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",r.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",r.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",r.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",r.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",r.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",r.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",r.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",r.CUES_PARSED="hlsCuesParsed",r.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",r.INIT_PTS_FOUND="hlsInitPtsFound",r.FRAG_LOADING="hlsFragLoading",r.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",r.FRAG_LOADED="hlsFragLoaded",r.FRAG_DECRYPTED="hlsFragDecrypted",r.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",r.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",r.FRAG_PARSING_METADATA="hlsFragParsingMetadata",r.FRAG_PARSED="hlsFragParsed",r.FRAG_BUFFERED="hlsFragBuffered",r.FRAG_CHANGED="hlsFragChanged",r.FPS_DROP="hlsFpsDrop",r.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",r.ERROR="hlsError",r.DESTROYING="hlsDestroying",r.KEY_LOADING="hlsKeyLoading",r.KEY_LOADED="hlsKeyLoaded",r.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",r.BACK_BUFFER_REACHED="hlsBackBufferReached",r}({}),q=function(r){return r.NETWORK_ERROR="networkError",r.MEDIA_ERROR="mediaError",r.KEY_SYSTEM_ERROR="keySystemError",r.MUX_ERROR="muxError",r.OTHER_ERROR="otherError",r}({}),D=function(r){return r.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",r.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",r.KEY_SYSTEM_NO_SESSION="keySystemNoSession",r.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",r.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",r.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",r.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",r.MANIFEST_LOAD_ERROR="manifestLoadError",r.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",r.MANIFEST_PARSING_ERROR="manifestParsingError",r.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",r.LEVEL_EMPTY_ERROR="levelEmptyError",r.LEVEL_LOAD_ERROR="levelLoadError",r.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",r.LEVEL_PARSING_ERROR="levelParsingError",r.LEVEL_SWITCH_ERROR="levelSwitchError",r.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",r.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",r.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",r.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",r.FRAG_LOAD_ERROR="fragLoadError",r.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",r.FRAG_DECRYPT_ERROR="fragDecryptError",r.FRAG_PARSING_ERROR="fragParsingError",r.FRAG_GAP="fragGap",r.REMUX_ALLOC_ERROR="remuxAllocError",r.KEY_LOAD_ERROR="keyLoadError",r.KEY_LOAD_TIMEOUT="keyLoadTimeOut",r.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",r.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",r.BUFFER_APPEND_ERROR="bufferAppendError",r.BUFFER_APPENDING_ERROR="bufferAppendingError",r.BUFFER_STALLED_ERROR="bufferStalledError",r.BUFFER_FULL_ERROR="bufferFullError",r.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",r.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",r.INTERNAL_EXCEPTION="internalException",r.INTERNAL_ABORTED="aborted",r.UNKNOWN="unknown",r}({});const Qt=function(){},Lr={trace:Qt,debug:Qt,log:Qt,warn:Qt,info:Qt,error:Qt};let Xi=Lr;function md(r){const e=self.console[r];return e?e.bind(self.console,`[${r}] >`):Qt}function vd(r,...e){e.forEach(function(t){Xi[t]=r[t]?r[t].bind(r):md(t)})}function yd(r,e){if(self.console&&r===!0||typeof r=="object"){vd(r,"debug","log","info","warn","error");try{Xi.log(`Debug logs enabled for "${e}" in hls.js version 1.4.6`)}catch{Xi=Lr}}else Xi=Lr}const C=Xi,Ad=/^(\d+)x(\d+)$/,Oo=/(.+?)=(".*?"|.*?)(?:,|$)/g;class me{constructor(e){typeof e=="string"&&(e=me.parseAttrList(e));for(const t in e)e.hasOwnProperty(t)&&(t.substring(0,2)==="X-"&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(t)),this[t]=e[t])}decimalInteger(e){const 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;const i=new Uint8Array(t.length/2);for(let s=0;s<t.length/2;s++)i[s]=parseInt(t.slice(s*2,s*2+2),16);return i}else return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}bool(e){return this[e]==="YES"}decimalResolution(e){const t=Ad.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const i={},s='"';for(Oo.lastIndex=0;(t=Oo.exec(e))!==null;){let n=t[2];n.indexOf(s)===0&&n.lastIndexOf(s)===n.length-1&&(n=n.slice(1,-1));const o=t[1].trim();i[o]=n}return i}}function bd(r){return r!=="ID"&&r!=="CLASS"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function xd(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"}class Mo{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const i=t.attr;for(const s in i)if(Object.prototype.hasOwnProperty.call(e,s)&&e[s]!==i[s]){C.warn(`DATERANGE tag attribute: "${s}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=s;break}e=Ce(new me({}),i,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const i=new Date(this.attr["END-DATE"]);W(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return e!==null?new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(W(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 isValid(){return!!this.id&&!this._badValueForSameId&&W(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class Es{constructor(){this.aborted=!1,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}}}var de={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Fo{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[de.AUDIO]:null,[de.VIDEO]:null,[de.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,t){const i=e.split("@",2),s=[];i.length===1?s[0]=t?t.byteRangeEndOffset:0:s[0]=parseInt(i[1]),s[1]=parseInt(i[0])+s[0],this._byteRange=s}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=wr.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class Rr extends Fo{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=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.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new Es,this.urlId=0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const i=Object.keys(this.levelkeys);if(i.length===1)return this._decryptdata=this.levelkeys[i[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!W(this.programDateTime))return null;const e=W(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),i=t.length;if(i>1||i===1&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,s,n,o=!1){const{elementaryStreams:a}=this,l=a[e];if(!l){a[e]={startPTS:t,endPTS:i,startDTS:s,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,s),l.endDTS=Math.max(l.endDTS,n)}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[de.AUDIO]=null,e[de.VIDEO]=null,e[de.AUDIOVIDEO]=null}}class Td extends Fo{constructor(e,t,i,s,n){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new Es,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=s;const 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(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}const Ed=10;class Sd{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,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.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,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=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,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=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t,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,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?W(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Ed}get drift(){const 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(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end: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 lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function Dr(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function Id(r){const e=No(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Cd(r){const e=function(i,s,n){const o=i[s];i[s]=i[n],i[n]=o};e(r,0,3),e(r,1,2),e(r,4,5),e(r,6,7)}function wd(r){const e=r.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),s=i[i.length-1].split(",");if(s.length===2){const n=s[0]==="base64",o=s[1];n?(i.splice(-1,1),t=Dr(o)):t=Id(o)}}return t}function No(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}var ve={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ze={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Bo(r){switch(r){case ze.FAIRPLAY:return ve.FAIRPLAY;case ze.PLAYREADY:return ve.PLAYREADY;case ze.WIDEVINE:return ve.WIDEVINE;case ze.CLEARKEY:return ve.CLEARKEY}}var Uo={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Ld(r){if(r===Uo.WIDEVINE)return ve.WIDEVINE}function Ho(r){switch(r){case ve.FAIRPLAY:return ze.FAIRPLAY;case ve.PLAYREADY:return ze.PLAYREADY;case ve.WIDEVINE:return ze.WIDEVINE;case ve.CLEARKEY:return ze.CLEARKEY}}function kr(r){const{drmSystems:e,widevineLicenseUrl:t}=r,i=e?[ve.FAIRPLAY,ve.WIDEVINE,ve.PLAYREADY,ve.CLEARKEY].filter(s=>!!e[s]):[];return!i[ve.WIDEVINE]&&t&&i.push(ve.WIDEVINE),i}const Go=function(){return typeof self<"u"&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Rd(r,e,t,i){let s;switch(r){case ve.FAIRPLAY:s=["cenc","sinf"];break;case ve.WIDEVINE:case ve.PLAYREADY:s=["cenc"];break;case ve.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return Dd(s,e,t,i)}function Dd(r,e,t,i){return[{initDataTypes:r,persistentState:i.persistentState||"not-allowed",distinctiveIdentifier:i.distinctiveIdentifier||"not-allowed",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 _t(r,e,t){return Uint8Array.prototype.slice?r.slice(e,t):new Uint8Array(Array.prototype.slice.call(r,e,t))}const Pr=(r,e)=>e+10<=r.length&&r[e]===73&&r[e+1]===68&&r[e+2]===51&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128,Vo=(r,e)=>e+10<=r.length&&r[e]===51&&r[e+1]===68&&r[e+2]===73&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128,Ss=(r,e)=>{const t=e;let i=0;for(;Pr(r,e);){i+=10;const s=Is(r,e+6);i+=s,Vo(r,e+10)&&(i+=10),e+=i}if(i>0)return r.subarray(t,t+i)},Is=(r,e)=>{let t=0;return t=(r[e]&127)<<21,t|=(r[e+1]&127)<<14,t|=(r[e+2]&127)<<7,t|=r[e+3]&127,t},kd=(r,e)=>Pr(r,e)&&Is(r,e+6)+10<=r.length-e,Pd=r=>{const e=zo(r);for(let t=0;t<e.length;t++){const i=e[t];if(jo(i))return Ud(i)}},jo=r=>r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp",Od=r=>{const e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=Is(r,4),i=10;return{type:e,size:t,data:r.subarray(i,i+t)}},zo=r=>{let e=0;const t=[];for(;Pr(r,e);){const i=Is(r,e+6);e+=10;const s=e+i;for(;e+8<s;){const n=Od(r.subarray(e)),o=Md(n);o&&t.push(o),e+=n.size+10}Vo(r,e)&&(e+=10)}return t},Md=r=>r.type==="PRIV"?Fd(r):r.type[0]==="W"?Bd(r):Nd(r),Fd=r=>{if(r.size<2)return;const e=ft(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}},Nd=r=>{if(r.size<2)return;if(r.type==="TXXX"){let t=1;const i=ft(r.data.subarray(t),!0);t+=i.length+1;const s=ft(r.data.subarray(t));return{key:r.type,info:i,data:s}}const e=ft(r.data.subarray(1));return{key:r.type,data:e}},Bd=r=>{if(r.type==="WXXX"){if(r.size<2)return;let t=1;const i=ft(r.data.subarray(t),!0);t+=i.length+1;const s=ft(r.data.subarray(t));return{key:r.type,info:i,data:s}}const e=ft(r.data);return{key:r.type,data:e}},Ud=r=>{if(r.data.byteLength===8){const e=new Uint8Array(r.data),t=e[3]&1;let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}},ft=(r,e=!1)=>{const t=Hd();if(t){const c=t.decode(r);if(e){const d=c.indexOf("\0");return d!==-1?c.substring(0,d):c}return c.replace(/\0/g,"")}const i=r.length;let s,n,o,a="",l=0;for(;l<i;){if(s=r[l++],s===0&&e)return a;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:n=r[l++],a+=String.fromCharCode((s&31)<<6|n&63);break;case 14:n=r[l++],o=r[l++],a+=String.fromCharCode((s&15)<<12|(n&63)<<6|(o&63)<<0);break}}return a};let Or;function Hd(){return!Or&&typeof self.TextDecoder<"u"&&(Or=new self.TextDecoder("utf-8")),Or}const gt={hexDump:function(r){let e="";for(let t=0;t<r.length;t++){let i=r[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}},Cs=Math.pow(2,32)-1,Gd=[].push,Wo={video:1,audio:2,id3:3,text:4};function De(r){return String.fromCharCode.apply(null,r)}function Yo(r,e){const t=r[e]<<8|r[e+1];return t<0?65536+t:t}function _(r,e){const t=Ko(r,e);return t<0?4294967296+t:t}function Ko(r,e){return r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}function Mr(r,e,t){r[e]=t>>24,r[e+1]=t>>16&255,r[e+2]=t>>8&255,r[e+3]=t&255}function re(r,e){const t=[];if(!e.length)return t;const i=r.byteLength;for(let s=0;s<i;){const n=_(r,s),o=De(r.subarray(s+4,s+8)),a=n>1?s+n:i;if(o===e[0])if(e.length===1)t.push(r.subarray(s+8,a));else{const l=re(r.subarray(s+8,a),e.slice(1));l.length&&Gd.apply(t,l)}s=a}return t}function Vd(r){const e=[],t=r[0];let i=8;const s=_(r,i);i+=4;const n=0,o=0;t===0?i+=8:i+=16,i+=2;let a=r.length+o;const l=Yo(r,i);i+=2;for(let c=0;c<l;c++){let d=i;const h=_(r,d);d+=4;const u=h&2147483647;if((h&2147483648)>>>31===1)return C.warn("SIDX has hierarchical references (not supported)"),null;const g=_(r,d);d+=4,e.push({referenceSize:u,subsegmentDuration:g,info:{duration:g/s,start:a,end:a+u-1}}),a+=u,d+=4,i=d}return{earliestPresentationTime:n,timescale:s,version:t,referencesCount:l,references:e}}function Xo(r){const e=[],t=re(r,["moov","trak"]);for(let s=0;s<t.length;s++){const n=t[s],o=re(n,["tkhd"])[0];if(o){let a=o[0],l=a===0?12:20;const c=_(o,l),d=re(n,["mdia","mdhd"])[0];if(d){a=d[0],l=a===0?12:20;const h=_(d,l),u=re(n,["mdia","hdlr"])[0];if(u){const f=De(u.subarray(8,12)),g={soun:de.AUDIO,vide:de.VIDEO}[f];if(g){const p=re(n,["mdia","minf","stbl","stsd"])[0];let m;p&&(m=De(p.subarray(12,16))),e[c]={timescale:h,type:g},e[g]={timescale:h,id:c,codec:m}}}}}}return re(r,["moov","mvex","trex"]).forEach(s=>{const n=_(s,4),o=e[n];o&&(o.default={duration:_(s,12),flags:_(s,20)})}),e}function jd(r,e){if(!r||!e)return r;const t=e.keyId;return t&&e.isCommonEncryption&&re(r,["moov","trak"]).forEach(s=>{const o=re(s,["mdia","minf","stbl","stsd"])[0].subarray(8);let a=re(o,["enca"]);const l=a.length>0;l||(a=re(o,["encv"])),a.forEach(c=>{const d=l?c.subarray(28):c.subarray(78);re(d,["sinf"]).forEach(u=>{const f=qo(u);if(f){const g=f.subarray(8,24);g.some(p=>p!==0)||(C.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${gt.hexDump(g)} -> ${gt.hexDump(t)}`),f.set(t,8))}})})}),r}function qo(r){const e=re(r,["schm"])[0];if(e){const t=De(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return re(r,["schi","tenc"])[0]}return C.error("[eme] missing 'schm' box"),null}function zd(r,e){return re(e,["moof","traf"]).reduce((t,i)=>{const s=re(i,["tfdt"])[0],n=s[0],o=re(i,["tfhd"]).reduce((a,l)=>{const c=_(l,4),d=r[c];if(d){let h=_(s,4);if(n===1){if(h===Cs)return C.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),a;h*=Cs+1,h+=_(s,8)}const u=d.timescale||9e4,f=h/u;if(isFinite(f)&&(a===null||f<a))return f}return a},null);return o!==null&&isFinite(o)&&(t===null||o<t)?o:t},null)}function Wd(r,e){let t=0,i=0,s=0;const n=re(r,["moof","traf"]);for(let o=0;o<n.length;o++){const a=n[o],l=re(a,["tfhd"])[0],c=_(l,4),d=e[c];if(!d)continue;const h=d.default,u=_(l,0)|(h==null?void 0:h.flags);let f=h==null?void 0:h.duration;u&8&&(u&2?f=_(l,12):f=_(l,8));const g=d.timescale||9e4,p=re(a,["trun"]);for(let m=0;m<p.length;m++){if(t=Yd(p[m]),!t&&f){const A=_(p[m],4);t=f*A}d.type===de.VIDEO?i+=t/g:d.type===de.AUDIO&&(s+=t/g)}}if(i===0&&s===0){let o=0;const a=re(r,["sidx"]);for(let l=0;l<a.length;l++){const c=Vd(a[l]);c!=null&&c.references&&(o+=c.references.reduce((d,h)=>d+h.info.duration||0,0))}return o}return i||s}function Yd(r){const e=_(r,0);let t=8;e&1&&(t+=4),e&4&&(t+=4);let i=0;const s=_(r,4);for(let n=0;n<s;n++){if(e&256){const o=_(r,t);i+=o,t+=4}e&512&&(t+=4),e&1024&&(t+=4),e&2048&&(t+=4)}return i}function Kd(r,e,t){re(e,["moof","traf"]).forEach(i=>{re(i,["tfhd"]).forEach(s=>{const n=_(s,4),o=r[n];if(!o)return;const a=o.timescale||9e4;re(i,["tfdt"]).forEach(l=>{const c=l[0];let d=_(l,4);if(c===0)d-=t*a,d=Math.max(d,0),Mr(l,4,d);else{d*=Math.pow(2,32),d+=_(l,8),d-=t*a,d=Math.max(d,0);const h=Math.floor(d/(Cs+1)),u=Math.floor(d%(Cs+1));Mr(l,4,h),Mr(l,8,u)}})})})}function Xd(r){const e={valid:null,remainder:null},t=re(r,["moof"]);if(t){if(t.length<2)return e.remainder=r,e}else return e;const i=t[t.length-1];return e.valid=_t(r,0,i.byteOffset-8),e.remainder=_t(r,i.byteOffset-8),e}function $t(r,e){const t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function Zo(r,e){const t=[],i=e.samples,s=e.timescale,n=e.id;let o=!1;return re(i,["moof"]).map(l=>{const c=l.byteOffset-8;re(l,["traf"]).map(h=>{const u=re(h,["tfdt"]).map(f=>{const g=f[0];let p=_(f,4);return g===1&&(p*=Math.pow(2,32),p+=_(f,8)),p/s})[0];return u!==void 0&&(r=u),re(h,["tfhd"]).map(f=>{const g=_(f,4),p=_(f,0)&16777215,m=(p&1)!==0,A=(p&2)!==0,T=(p&8)!==0;let b=0;const y=(p&16)!==0;let x=0;const E=(p&32)!==0;let S=8;g===n&&(m&&(S+=8),A&&(S+=4),T&&(b=_(f,S),S+=4),y&&(x=_(f,S),S+=4),E&&(S+=4),e.type==="video"&&(o=qd(e.codec)),re(h,["trun"]).map(R=>{const w=R[0],I=_(R,0)&16777215,O=(I&1)!==0;let P=0;const B=(I&4)!==0,J=(I&256)!==0;let H=0;const V=(I&512)!==0;let j=0;const F=(I&1024)!==0,U=(I&2048)!==0;let Q=0;const Y=_(R,4);let z=8;O&&(P=_(R,z),z+=4),B&&(z+=4);let K=P+c;for(let X=0;X<Y;X++){if(J?(H=_(R,z),z+=4):H=b,V?(j=_(R,z),z+=4):j=x,F&&(z+=4),U&&(w===0?Q=_(R,z):Q=Ko(R,z),z+=4),e.type===de.VIDEO){let ie=0;for(;ie<j;){const ee=_(i,K);if(K+=4,Zd(o,i[K])){const ne=i.subarray(K,K+ee);Jo(ne,o?2:1,r+Q/s,t)}K+=ee,ie+=ee+4}}r+=H/s}}))})})}),t}function qd(r){if(!r)return!1;const e=r.indexOf("."),t=e<0?r:r.substring(0,e);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function Zd(r,e){if(r){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Jo(r,e,t,i){const s=Qo(r);let n=0;n+=e;let o=0,a=0,l=!1,c=0;for(;n<s.length;){o=0;do{if(n>=s.length)break;c=s[n++],o+=c}while(c===255);a=0;do{if(n>=s.length)break;c=s[n++],a+=c}while(c===255);const d=s.length-n;if(!l&&o===4&&n<s.length){if(l=!0,s[n++]===181){const u=Yo(s,n);if(n+=2,u===49){const f=_(s,n);if(n+=4,f===1195456820){const g=s[n++];if(g===3){const p=s[n++],m=31&p,A=64&p,T=A?2+m*3:0,b=new Uint8Array(T);if(A){b[0]=p;for(let y=1;y<T;y++)b[y]=s[n++]}i.push({type:g,payloadType:o,pts:t,bytes:b})}}}}}else if(o===5&&a<d){if(l=!0,a>16){const h=[];for(let g=0;g<16;g++){const p=s[n++].toString(16);h.push(p.length==1?"0"+p:p),(g===3||g===5||g===7||g===9)&&h.push("-")}const u=a-16,f=new Uint8Array(u);for(let g=0;g<u;g++)f[g]=s[n++];i.push({payloadType:o,pts:t,uuid:h.join(""),userData:ft(f),userDataBytes:f})}}else if(a<d)n+=a;else if(a>d)break}}function Qo(r){const e=r.byteLength,t=[];let i=1;for(;i<e-2;)r[i]===0&&r[i+1]===0&&r[i+2]===3?(t.push(i+2),i+=2):i++;if(t.length===0)return r;const s=e-t.length,n=new Uint8Array(s);let o=0;for(i=0;i<s;o++,i++)o===t[0]&&(o++,t.shift()),n[i]=r[o];return n}function Jd(r){const e=r[0];let t="",i="",s=0,n=0,o=0,a=0,l=0,c=0;if(e===0){for(;De(r.subarray(c,c+1))!=="\0";)t+=De(r.subarray(c,c+1)),c+=1;for(t+=De(r.subarray(c,c+1)),c+=1;De(r.subarray(c,c+1))!=="\0";)i+=De(r.subarray(c,c+1)),c+=1;i+=De(r.subarray(c,c+1)),c+=1,s=_(r,12),n=_(r,16),a=_(r,20),l=_(r,24),c=28}else if(e===1){c+=4,s=_(r,c),c+=4;const h=_(r,c);c+=4;const u=_(r,c);for(c+=4,o=4294967296*h+u,Number.isSafeInteger(o)||(o=Number.MAX_SAFE_INTEGER,C.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),a=_(r,c),c+=4,l=_(r,c),c+=4;De(r.subarray(c,c+1))!=="\0";)t+=De(r.subarray(c,c+1)),c+=1;for(t+=De(r.subarray(c,c+1)),c+=1;De(r.subarray(c,c+1))!=="\0";)i+=De(r.subarray(c,c+1)),c+=1;i+=De(r.subarray(c,c+1)),c+=1}const d=r.subarray(c,r.byteLength);return{schemeIdUri:t,value:i,timeScale:s,presentationTime:o,presentationTimeDelta:n,eventDuration:a,id:l,payload:d}}function Qd(r,...e){const t=e.length;let i=8,s=t;for(;s--;)i+=e[s].byteLength;const 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(r,4),s=0,i=8;s<t;s++)n.set(e[s],i),i+=e[s].byteLength;return n}function _d(r,e,t){if(r.byteLength!==16)throw new RangeError("Invalid system id");let i,s;if(e){i=1,s=new Uint8Array(e.length*16);for(let a=0;a<e.length;a++){const l=e[a];if(l.byteLength!==16)throw new RangeError("Invalid key");s.set(l,a*16)}}else i=0,s=new Uint8Array;let n;i>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;const o=new Uint8Array(4);return t&&t.byteLength>0&&new DataView(o.buffer).setUint32(0,t.byteLength,!1),Qd([112,115,115,104],new Uint8Array([i,0,0,0]),r,n,s,o,t||new Uint8Array)}function $d(r){if(!(r instanceof ArrayBuffer)||r.byteLength<32)return null;const e={version:0,systemId:"",kids:null,data:null},t=new DataView(r),i=t.getUint32(0);if(r.byteLength!==i&&i>44||t.getUint32(4)!==1886614376||(e.version=t.getUint32(8)>>>24,e.version>1))return null;e.systemId=gt.hexDump(new Uint8Array(r,12,16));const n=t.getUint32(28);if(e.version===0){if(i-32<n)return null;e.data=new Uint8Array(r,32,n)}else if(e.version===1){e.kids=[];for(let o=0;o<n;o++)e.kids.push(new Uint8Array(r,32+o*16,16))}return e}let ws={};class qi{static clearKeyUriToKeyIdMap(){ws={}}constructor(e,t,i,s=[1],n=null){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=s,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&e!=="AES-128"}isSupported(){if(this.method){if(this.method==="AES-128"||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case ze.FAIRPLAY:case ze.WIDEVINE:case ze.PLAYREADY:case ze.CLEARKEY:return["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(this.method==="AES-128"&&this.uri&&!this.iv){typeof e!="number"&&(this.method==="AES-128"&&!this.iv&&C.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const i=eh(e);return new qi(this.method,this.uri,"identity",this.keyFormatVersions,i)}const t=wd(this.uri);if(t)switch(this.keyFormat){case ze.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case ze.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=_d(i,null,t);const s=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),n=String.fromCharCode.apply(null,Array.from(s)),o=n.substring(n.indexOf("<"),n.length),c=new DOMParser().parseFromString(o,"text/xml").getElementsByTagName("KID")[0];if(c){const d=c.childNodes[0]?c.childNodes[0].nodeValue:c.getAttribute("VALUE");if(d){const h=Dr(d).subarray(0,16);Cd(h),this.keyId=h}}break}default:{let i=t.subarray(0,16);if(i.length!==16){const s=new Uint8Array(16);s.set(i,16-i.length),i=s}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=ws[this.uri];if(!i){const s=Object.keys(ws).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,s),ws[this.uri]=i}this.keyId=i}return this}}function eh(r){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}const _o=/\{\$([a-zA-Z0-9-_]+)\}/g;function $o(r){return _o.test(r)}function We(r,e,t){if(r.variableList!==null||r.hasVariableRefs)for(let i=t.length;i--;){const s=t[i],n=e[s];n&&(e[s]=Fr(r,n))}}function Fr(r,e){if(r.variableList!==null||r.hasVariableRefs){const t=r.variableList;return e.replace(_o,i=>{const s=i.substring(2,i.length-1),n=t==null?void 0:t[s];return n===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),i):n})}return e}function ea(r,e,t){let i=r.variableList;i||(r.variableList=i={});let s,n;if("QUERYPARAM"in e){s=e.QUERYPARAM;try{const o=new self.URL(t).searchParams;if(o.has(s))n=o.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${t}"`)}catch(o){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else s=e.NAME,n=e.VALUE;s in i?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):i[s]=n||""}function th(r,e,t){const i=e.IMPORT;if(t&&i in t){let s=r.variableList;s||(r.variableList=s={}),s[i]=t[i]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function Ls(){if(!(typeof self>"u"))return self.MediaSource||self.WebKitMediaSource}const ih={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}},ta=Ls();function sh(r,e){const t=ih[e];return!!t&&t[r.slice(0,4)]===!0}function Nr(r,e){var t;return(t=ta==null?void 0:ta.isTypeSupported(`${e||"video"}/mp4;codecs="${r}"`))!=null?t:!1}const ia=/#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,sa=/#EXT-X-MEDIA:(.*)/g,rh=/^#EXT(?:INF|-X-TARGETDURATION):/m,ra=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),nh=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(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)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class at{static findGroup(e,t){for(let i=0;i<e.length;i++){const s=e[i];if(s.id===t)return s}}static convertAVC1ToAVCOTI(e){const t=e.split(".");if(t.length>2){let i=t.shift()+".";return i+=parseInt(t.shift()).toString(16),i+=("000"+parseInt(t.shift()).toString(16)).slice(-4),i}return e}static resolve(e,t){return wr.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return rh.test(e)}static parseMasterPlaylist(e,t){const i=$o(e),s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];ia.lastIndex=0;let o;for(;(o=ia.exec(e))!=null;)if(o[1]){var a;const c=new me(o[1]);We(s,c,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const d=Fr(s,o[2]),h={attrs:c,bitrate:c.decimalInteger("AVERAGE-BANDWIDTH")||c.decimalInteger("BANDWIDTH"),name:c.NAME,url:at.resolve(d,t)},u=c.decimalResolution("RESOLUTION");u&&(h.width=u.width,h.height=u.height),oh((c.CODECS||"").split(/[ ,]+/).filter(f=>f),h),h.videoCodec&&h.videoCodec.indexOf("avc1")!==-1&&(h.videoCodec=at.convertAVC1ToAVCOTI(h.videoCodec)),(a=h.unknownCodecs)!=null&&a.length||n.push(h),s.levels.push(h)}else if(o[3]){const c=o[3],d=o[4];switch(c){case"SESSION-DATA":{const h=new me(d);We(s,h,["DATA-ID","LANGUAGE","VALUE","URI"]);const u=h["DATA-ID"];u&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[u]=h);break}case"SESSION-KEY":{const h=na(d,t,s);h.encrypted&&h.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(h)):C.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);break}case"DEFINE":{{const h=new me(d);We(s,h,["NAME","VALUE","QUERYPARAM"]),ea(s,h,t)}break}case"CONTENT-STEERING":{const h=new me(d);We(s,h,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:at.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=oa(d);break}}}const l=n.length>0&&n.length<s.levels.length;return s.levels=l?n:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,i){let s;const n={},o=i.levels,a={AUDIO:o.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:o.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(sa.lastIndex=0;(s=sa.exec(e))!==null;){const c=new me(s[1]),d=c.TYPE;if(d){const h=a[d],u=n[d]||[];n[d]=u,We(i,c,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const f={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",instreamId:c["INSTREAM-ID"],name:c.NAME||c.LANGUAGE||"",type:d,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:c.LANGUAGE,url:c.URI?at.resolve(c.URI,t):""};if(h!=null&&h.length){const g=at.findGroup(h,f.groupId)||h[0];aa(f,g,"audioCodec"),aa(f,g,"textCodec")}u.push(f)}}return n}static parseLevelPlaylist(e,t,i,s,n,o){const a=new Sd(t),l=a.fragments;let c=null,d=0,h=0,u=0,f=0,g=null,p=new Rr(s,t),m,A,T,b=-1,y=!1;for(ra.lastIndex=0,a.m3u8=e,a.hasVariableRefs=$o(e);(m=ra.exec(e))!==null;){y&&(y=!1,p=new Rr(s,t),p.start=u,p.sn=d,p.cc=f,p.level=i,c&&(p.initSegment=c,p.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null));const R=m[1];if(R){p.duration=parseFloat(R);const w=(" "+m[2]).slice(1);p.title=w||null,p.tagList.push(w?["INF",R,w]:["INF",R])}else if(m[3]){if(W(p.duration)){p.start=u,T&&da(p,T,a),p.sn=d,p.level=i,p.cc=f,p.urlId=n,l.push(p);const w=(" "+m[3]).slice(1);p.relurl=Fr(a,w),la(p,g),g=p,u+=p.duration,d++,h=0,y=!0}}else if(m[4]){const w=(" "+m[4]).slice(1);g?p.setByteRange(w,g):p.setByteRange(w)}else if(m[5])p.rawProgramDateTime=(" "+m[5]).slice(1),p.tagList.push(["PROGRAM-DATE-TIME",p.rawProgramDateTime]),b===-1&&(b=l.length);else{if(m=m[0].match(nh),!m){C.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A<m.length&&!(typeof m[A]<"u");A++);const w=(" "+m[A]).slice(1),I=(" "+m[A+1]).slice(1),O=m[A+2]?(" "+m[A+2]).slice(1):"";switch(w){case"PLAYLIST-TYPE":a.type=I.toUpperCase();break;case"MEDIA-SEQUENCE":d=a.startSN=parseInt(I);break;case"SKIP":{const P=new me(I);We(a,P,["RECENTLY-REMOVED-DATERANGES"]);const B=P.decimalInteger("SKIPPED-SEGMENTS");if(W(B)){a.skippedSegments=B;for(let H=B;H--;)l.unshift(null);d+=B}const J=P.enumeratedString("RECENTLY-REMOVED-DATERANGES");J&&(a.recentlyRemovedDateranges=J.split(" "));break}case"TARGETDURATION":a.targetduration=Math.max(parseInt(I),1);break;case"VERSION":a.version=parseInt(I);break;case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"#":(I||O)&&p.tagList.push(O?[I,O]:[I]);break;case"DISCONTINUITY":f++,p.tagList.push(["DIS"]);break;case"GAP":p.gap=!0,p.tagList.push([w]);break;case"BITRATE":p.tagList.push([w,I]);break;case"DATERANGE":{const P=new me(I);We(a,P,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),We(a,P,P.clientAttrs);const B=new Mo(P,a.dateRanges[P.ID]);B.isValid||a.skippedSegments?a.dateRanges[B.id]=B:C.warn(`Ignoring invalid DATERANGE tag: "${I}"`),p.tagList.push(["EXT-X-DATERANGE",I]);break}case"DEFINE":{{const P=new me(I);We(a,P,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in P?th(a,P,o):ea(a,P,t)}break}case"DISCONTINUITY-SEQUENCE":f=parseInt(I);break;case"KEY":{const P=na(I,t,a);if(P.isSupported()){if(P.method==="NONE"){T=void 0;break}T||(T={}),T[P.keyFormat]&&(T=Ce({},T)),T[P.keyFormat]=P}else C.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${I}"`);break}case"START":a.startTimeOffset=oa(I);break;case"MAP":{const P=new me(I);if(We(a,P,["BYTERANGE","URI"]),p.duration){const B=new Rr(s,t);ca(B,P,i,T),c=B,p.initSegment=c,c.rawProgramDateTime&&!p.rawProgramDateTime&&(p.rawProgramDateTime=c.rawProgramDateTime)}else ca(p,P,i,T),c=p,y=!0;break}case"SERVER-CONTROL":{const P=new me(I);a.canBlockReload=P.bool("CAN-BLOCK-RELOAD"),a.canSkipUntil=P.optionalFloat("CAN-SKIP-UNTIL",0),a.canSkipDateRanges=a.canSkipUntil>0&&P.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=P.optionalFloat("PART-HOLD-BACK",0),a.holdBack=P.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const P=new me(I);a.partTarget=P.decimalFloatingPoint("PART-TARGET");break}case"PART":{let P=a.partList;P||(P=a.partList=[]);const B=h>0?P[P.length-1]:void 0,J=h++,H=new me(I);We(a,H,["BYTERANGE","URI"]);const V=new Td(H,p,t,J,B);P.push(V),p.duration+=V.duration;break}case"PRELOAD-HINT":{const P=new me(I);We(a,P,["URI"]),a.preloadHint=P;break}case"RENDITION-REPORT":{const P=new me(I);We(a,P,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(P);break}default:C.warn(`line parsed but not handled: ${m}`);break}}}g&&!g.relurl?(l.pop(),u-=g.duration,a.partList&&(a.fragmentHint=g)):a.partList&&(la(p,g),p.cc=f,a.fragmentHint=p,T&&da(p,T,a));const x=l.length,E=l[0],S=l[x-1];if(u+=a.skippedSegments*a.targetduration,u>0&&x&&S){a.averagetargetduration=u/x;const R=S.sn;a.endSN=R!=="initSegment"?R:0,a.live||(S.endList=!0),E&&(a.startCC=E.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(u+=a.fragmentHint.duration),a.totalduration=u,a.endCC=f,b>0&&ah(l,b),a}}function na(r,e,t){var i,s;const n=new me(r);We(t,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const o=(i=n.METHOD)!=null?i:"",a=n.URI,l=n.hexadecimalInteger("IV"),c=n.KEYFORMATVERSIONS,d=(s=n.KEYFORMAT)!=null?s:"identity";a&&n.IV&&!l&&C.error(`Invalid IV: ${n.IV}`);const h=a?at.resolve(a,e):"",u=(c||"1").split("/").map(Number).filter(Number.isFinite);return new qi(o,h,d,u,l)}function oa(r){const t=new me(r).decimalFloatingPoint("TIME-OFFSET");return W(t)?t:null}function oh(r,e){["video","audio","text"].forEach(t=>{const i=r.filter(s=>sh(s,t));if(i.length){const s=i.filter(n=>n.lastIndexOf("avc1",0)===0||n.lastIndexOf("mp4a",0)===0);e[`${t}Codec`]=s.length>0?s[0]:i[0],r=r.filter(n=>i.indexOf(n)===-1)}}),e.unknownCodecs=r}function aa(r,e,t){const i=e[t];i&&(r[t]=i)}function ah(r,e){let t=r[e];for(let i=e;i--;){const s=r[i];if(!s)return;s.programDateTime=t.programDateTime-s.duration*1e3,t=s}}function la(r,e){r.rawProgramDateTime?r.programDateTime=Date.parse(r.rawProgramDateTime):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime),W(r.programDateTime)||(r.programDateTime=null,r.rawProgramDateTime=null)}function ca(r,e,t,i){r.relurl=e.URI,e.BYTERANGE&&r.setByteRange(e.BYTERANGE),r.level=t,r.sn="initSegment",i&&(r.levelkeys=i),r.initSegment=null}function da(r,e,t){r.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(s=>e[s].isCommonEncryption)&&i.push(r)}var ae={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Z={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function ha(r){const{type:e}=r;switch(e){case ae.AUDIO_TRACK:return Z.AUDIO;case ae.SUBTITLE_TRACK:return Z.SUBTITLE;default:return Z.MAIN}}function Br(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class lh{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{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)}unregisterListeners(){const{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)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,n=i||s,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(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ae.MANIFEST,url:i,deliveryDirectives:null})}onLevelLoading(e,t){const{id:i,level:s,url:n,deliveryDirectives:o}=t;this.load({id:i,level:s,responseType:"text",type:ae.LEVEL,url:n,deliveryDirectives:o})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:ae.AUDIO_TRACK,url:n,deliveryDirectives:o})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:ae.SUBTITLE_TRACK,url:n,deliveryDirectives:o})}load(e){var t;const i=this.hls.config;let s=this.getInternalLoader(e);if(s){const c=s.context;if(c&&c.url===e.url){C.trace("[playlist-loader]: playlist request ongoing");return}C.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let n;if(e.type===ae.MANIFEST?n=i.manifestLoadPolicy.default:n=Ce({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),(t=e.deliveryDirectives)!=null&&t.part){let c;if(e.type===ae.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===ae.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===ae.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const d=c.partTarget,h=c.targetduration;if(d&&h){const u=Math.max(d*3,h*.8)*1e3;n=Ce({},n,{maxTimeToFirstByteMs:Math.min(u,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(u,n.maxTimeToFirstByteMs)})}}}const 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:(c,d,h,u)=>{const f=this.getInternalLoader(h);this.resetInternalLoader(h.type);const g=c.data;if(g.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(c,h,new Error("no EXTM3U delimiter"),u||null,d);return}d.parsing.start=performance.now(),at.isMediaPlaylist(g)?this.handleTrackOrLevelPlaylist(c,d,h,u||null,f):this.handleMasterPlaylist(c,d,h,u)},onError:(c,d,h,u)=>{this.handleNetworkError(d,h,!1,c,u)},onTimeout:(c,d,h)=>{this.handleNetworkError(d,h,!0,void 0,c)}};s.load(e,a,l)}handleMasterPlaylist(e,t,i,s){const n=this.hls,o=e.data,a=Br(e,i),l=at.parseMasterPlaylist(o,a);if(l.playlistParsingError){this.handleManifestParsingError(e,i,l.playlistParsingError,s,t);return}const{contentSteering:c,levels:d,sessionData:h,sessionKeys:u,startTimeOffset:f,variableList:g}=l;this.variableList=g;const{AUDIO:p=[],SUBTITLES:m,"CLOSED-CAPTIONS":A}=at.parseMasterPlaylistMedia(o,a,l);p.length&&!p.some(b=>!b.url)&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(C.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:!1,autoselect:!1,forced:!1,id:-1,attrs:new me({}),bitrate:0,url:""})),n.trigger(v.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:m,captions:A,contentSteering:c,url:a,stats:t,networkDetails:s,sessionData:h,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,i,s,n){const o=this.hls,{id:a,level:l,type:c}=i,d=Br(e,i),h=W(a)?a:0,u=W(l)?l:h,f=ha(i),g=at.parseLevelPlaylist(e.data,d,u,f,h,this.variableList);if(c===ae.MANIFEST){const p={attrs:new me({}),bitrate:0,details:g,name:"",url:d};o.trigger(v.MANIFEST_LOADED,{levels:[p],audioTracks:[],url:d,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=g,this.handlePlaylistLoaded(g,e,t,i,s,n)}handleManifestParsingError(e,t,i,s,n){this.hls.trigger(v.ERROR,{type:q.NETWORK_ERROR,details:D.MANIFEST_PARSING_ERROR,fatal:t.type===ae.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:n})}handleNetworkError(e,t,i=!1,s,n){let o=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===ae.LEVEL?o+=`: ${e.level} id: ${e.id}`:(e.type===ae.AUDIO_TRACK||e.type===ae.SUBTITLE_TRACK)&&(o+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(o);C.warn(`[playlist-loader]: ${o}`);let l=D.UNKNOWN,c=!1;const d=this.getInternalLoader(e);switch(e.type){case ae.MANIFEST:l=i?D.MANIFEST_LOAD_TIMEOUT:D.MANIFEST_LOAD_ERROR,c=!0;break;case ae.LEVEL:l=i?D.LEVEL_LOAD_TIMEOUT:D.LEVEL_LOAD_ERROR,c=!1;break;case ae.AUDIO_TRACK:l=i?D.AUDIO_TRACK_LOAD_TIMEOUT:D.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case ae.SUBTITLE_TRACK:l=i?D.SUBTITLE_TRACK_LOAD_TIMEOUT:D.SUBTITLE_LOAD_ERROR,c=!1;break}d&&this.resetInternalLoader(e.type);const h={type:q.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:d,context:e,error:a,networkDetails:t,stats:n};if(s){const u=(t==null?void 0:t.url)||e.url;h.response=je({url:u,data:void 0},s)}this.hls.trigger(v.ERROR,h)}handlePlaylistLoaded(e,t,i,s,n,o){const a=this.hls,{type:l,level:c,id:d,groupId:h,deliveryDirectives:u}=s,f=Br(t,s),g=ha(s),p=typeof s.level=="number"&&g===Z.MAIN?c:void 0;if(!e.fragments.length){const A=new Error("No Segments found in Playlist");a.trigger(v.ERROR,{type:q.NETWORK_ERROR,details:D.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:A,reason:A.message,response:t,context:s,level:p,parent:g,networkDetails:n,stats:i});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const m=e.playlistParsingError;if(m){a.trigger(v.ERROR,{type:q.NETWORK_ERROR,details:D.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:m,reason:m.message,response:t,context:s,level:p,parent:g,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 ae.MANIFEST:case ae.LEVEL:a.trigger(v.LEVEL_LOADED,{details:e,level:p||0,id:d||0,stats:i,networkDetails:n,deliveryDirectives:u});break;case ae.AUDIO_TRACK:a.trigger(v.AUDIO_TRACK_LOADED,{details:e,id:d||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:u});break;case ae.SUBTITLE_TRACK:a.trigger(v.SUBTITLE_TRACK_LOADED,{details:e,id:d||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:u});break}}}function ua(r,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=r,e.dispatchEvent(t)}function fa(r,e){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues&&!r.cues.getCueById(e.id))try{if(r.addCue(e),!r.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){C.debug(`[texttrack-utils]: ${i}`);const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,r.addCue(s)}t==="disabled"&&(r.mode=t)}function fi(r){const e=r.mode;if(e==="disabled"&&(r.mode="hidden"),r.cues)for(let t=r.cues.length;t--;)r.removeCue(r.cues[t]);e==="disabled"&&(r.mode=e)}function Ur(r,e,t,i){const s=r.mode;if(s==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){const n=dh(r.cues,e,t);for(let o=0;o<n.length;o++)(!i||i(n[o]))&&r.removeCue(n[o])}s==="disabled"&&(r.mode=s)}function ch(r,e){if(e<r[0].startTime)return 0;const t=r.length-1;if(e>r[t].endTime)return-1;let i=0,s=t;for(;i<=s;){const n=Math.floor((s+i)/2);if(e<r[n].startTime)s=n-1;else if(e>r[n].startTime&&i<t)i=n+1;else return n}return r[i].startTime-e<e-r[s].startTime?i:s}function dh(r,e,t){const i=[],s=ch(r,e);if(s>-1)for(let n=s,o=r.length;n<o;n++){const a=r[n];if(a.startTime>=e&&a.endTime<=t)i.push(a);else if(a.startTime>t)return i}return i}var lt={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const hh=.25;function Hr(){if(!(typeof self>"u"))return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const Rs=(()=>{const r=Hr();try{new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Gr(r,e){return r.getTime()/1e3-e}function uh(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class fh{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{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.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(v.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{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.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(v.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(fi(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const i=e[t];if(i.kind==="metadata"&&i.label==="id3")return ua(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:s}}}=this;if(!i&&!s)return;const{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=Hr();for(let a=0;a<n.length;a++){const l=n[a].type;if(l===lt.emsg&&!i||!s)continue;const c=zo(n[a].data);if(c){const d=n[a].pts;let h=d+n[a].duration;h>Rs&&(h=Rs),h-d<=0&&(h=d+hh);for(let f=0;f<c.length;f++){const g=c[f];if(!jo(g)){this.updateId3CueEnds(d,l);const p=new o(d,h,"");p.value=g,l&&(p.type=l),this.id3Track.addCue(p)}}}}}updateId3CueEnds(e,t){var i;const s=(i=this.id3Track)==null?void 0:i.cues;if(s)for(let n=s.length;n--;){const o=s[n];o.type===t&&o.startTime<e&&o.endTime===Rs&&(o.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){const{id3Track:n,hls:o}=this;if(!o)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:l}}=o;if(n&&(a||l)){let c;s==="audio"?c=d=>d.type===lt.audioId3&&l:s==="video"?c=d=>d.type===lt.emsg&&a:c=d=>d.type===lt.audioId3&&l||d.type===lt.emsg&&a,Ur(n,t,i,c)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:s}=this,{dateRanges:n}=t,o=Object.keys(n);if(s){const d=Object.keys(i).filter(h=>!o.includes(h));for(let h=d.length;h--;){const u=d[h];Object.keys(i[u].cues).forEach(f=>{s.removeCue(i[u].cues[f])}),delete i[u]}}const a=t.fragments[t.fragments.length-1];if(o.length===0||!W(a==null?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=a.programDateTime/1e3-a.start,c=Hr();for(let d=0;d<o.length;d++){const h=o[d],u=n[h],f=i[h],g=(f==null?void 0:f.cues)||{};let p=(f==null?void 0:f.durationKnown)||!1;const m=Gr(u.startDate,l);let A=Rs;const T=u.endDate;if(T)A=Gr(T,l),p=!0;else if(u.endOnNext&&!p){const y=o.reduce((x,E)=>{const S=n[E];return S.class===u.class&&S.id!==E&&S.startDate>u.startDate&&x.push(S),x},[]).sort((x,E)=>x.startDate.getTime()-E.startDate.getTime())[0];y&&(A=Gr(y.startDate,l),p=!0)}const b=Object.keys(u.attr);for(let y=0;y<b.length;y++){const x=b[y];if(!bd(x))continue;let E=g[x];if(E)p&&!f.durationKnown&&(E.endTime=A);else{let S=u.attr[x];E=new c(m,A,""),xd(x)&&(S=uh(S)),E.value={key:x,data:S},E.type=lt.dateRange,E.id=h,this.id3Track.addCue(E),g[x]=E}}i[h]={cues:g,dateRange:u,durationKnown:p}}}}class gh{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(e===null)return null;const{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:n,liveSyncDurationCount:o,lowLatencyMode:a}=this.config,l=this.hls.userConfig;let c=a&&i||t;(l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=n!==void 0?n:o*s);const d=s,h=1;return c+Math.min(this.stallCount*h,d)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,i=this.levelDetails;if(e===null||t===null||i===null)return null;const s=i.edge,n=e-t-this.edgeStalled,o=s-i.totalduration,a=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(o,n),a)}get drift(){const{levelDetails:e}=this;return e===null?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(v.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(v.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(v.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(v.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var i;t.details===D.BUFFER_STALLED_ERROR&&(this.stallCount++,(i=this.levelDetails)!=null&&i.live&&C.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:n}=this.config;if(!s||n===1)return;const o=this.targetLatency;if(o===null)return;const a=i-o,l=Math.min(this.maxLatency,o+t.targetduration),c=a<l;if(t.live&&c&&a>.05&&this.forwardBufferLength>1){const d=Math.min(2,Math.max(1,n)),h=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;e.playbackRate=Math.min(d,Math.max(1,h))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const Vr=["NONE","TYPE-0","TYPE-1",null];var Zi={No:"",Yes:"YES",v2:"v2"};function ph(r,e){const{canSkipUntil:t,canSkipDateRanges:i,endSN:s}=r,n=e!==void 0?e-s:0;return t&&n<t?i?Zi.v2:Zi.Yes:Zi.No}class ga{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){const 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}}class Ji{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=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.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.unknownCodecs=e.unknownCodecs,this.codecSet=[e.videoCodec,e.audioCodec].filter(t=>t).join(",").replace(/\.[^.,]+/g,"")}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get attrs(){return this._attrs[this._urlId]}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get uri(){return this.url[this._urlId]||""}get urlId(){return this._urlId}set urlId(e){const t=e%this.url.length;this._urlId!==t&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=t)}get audioGroupId(){var e;return(e=this.audioGroupIds)==null?void 0:e[this.urlId]}get textGroupId(){var e;return(e=this.textGroupIds)==null?void 0:e[this.urlId]}addFallback(e){this.url.push(e.url),this._attrs.push(e.attrs)}}function jr(r,e){const t=e.startPTS;if(W(t)){let i=0,s;e.sn>r.sn?(i=t-r.start,s=r):(i=r.start-t,s=e),s.duration!==i&&(s.duration=i)}else e.sn>r.sn?r.cc===e.cc&&r.minEndPTS?e.start=r.start+(r.minEndPTS-r.start):e.start=r.start+r.duration:e.start=Math.max(r.start-e.duration,0)}function pa(r,e,t,i,s,n){i-t<=0&&(C.warn("Fragment should have a positive duration",e),i=t+e.duration,n=s+e.duration);let a=t,l=i;const c=e.startPTS,d=e.endPTS;if(W(c)){const m=Math.abs(c-t);W(e.deltaPTS)?e.deltaPTS=Math.max(m,e.deltaPTS):e.deltaPTS=m,a=Math.max(t,c),t=Math.min(t,c),s=Math.min(s,e.startDTS),l=Math.min(i,d),i=Math.max(i,d),n=Math.max(n,e.endDTS)}const h=t-e.start;e.start!==0&&(e.start=t),e.duration=i-e.start,e.startPTS=t,e.maxStartPTS=a,e.startDTS=s,e.endPTS=i,e.minEndPTS=l,e.endDTS=n;const u=e.sn;if(!r||u<r.startSN||u>r.endSN)return 0;let f;const g=u-r.startSN,p=r.fragments;for(p[g]=e,f=g;f>0;f--)jr(p[f],p[f-1]);for(f=g;f<p.length-1;f++)jr(p[f],p[f+1]);return r.fragmentHint&&jr(p[p.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,h}function mh(r,e){let t=null;const i=r.fragments;for(let l=i.length-1;l>=0;l--){const c=i[l].initSegment;if(c){t=c;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let s=0,n;if(Ah(r,e,(l,c)=>{l.relurl&&(s=l.cc-c.cc),W(l.startPTS)&&W(l.endPTS)&&(c.start=c.startPTS=l.startPTS,c.startDTS=l.startDTS,c.maxStartPTS=l.maxStartPTS,c.endPTS=l.endPTS,c.endDTS=l.endDTS,c.minEndPTS=l.minEndPTS,c.duration=l.endPTS-l.startPTS,c.duration&&(n=c),e.PTSKnown=e.alignedSliding=!0),c.elementaryStreams=l.elementaryStreams,c.loader=l.loader,c.stats=l.stats,c.urlId=l.urlId,l.initSegment&&(c.initSegment=l.initSegment,t=l.initSegment)}),t&&(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(c=>{var d;(!c.initSegment||c.initSegment.relurl===((d=t)==null?void 0:d.relurl))&&(c.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some(l=>!l),e.deltaUpdateFailed){C.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=vh(r.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const o=e.fragments;if(s){C.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l<o.length;l++)o[l].cc+=s}e.skippedSegments&&(e.startCC=e.fragments[0].cc),yh(r.partList,e.partList,(l,c)=>{c.elementaryStreams=l.elementaryStreams,c.stats=l.stats}),n?pa(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):ma(r,e),o.length&&(e.totalduration=e.edge-o[0].start),e.driftStartTime=r.driftStartTime,e.driftStart=r.driftStart;const a=e.advancedDateTime;if(e.advanced&&a){const l=e.edge;e.driftStart||(e.driftStartTime=a,e.driftStart=l),e.driftEndTime=a,e.driftEnd=l}else e.driftEndTime=r.driftEndTime,e.driftEnd=r.driftEnd,e.advancedDateTime=r.advancedDateTime}function vh(r,e,t){const i=Ce({},r);return t&&t.forEach(s=>{delete i[s]}),Object.keys(e).forEach(s=>{const n=new Mo(e[s].attr,i[s]);n.isValid?i[s]=n:C.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[s].attr)}"`)}),i}function yh(r,e,t){if(r&&e){let i=0;for(let s=0,n=r.length;s<=n;s++){const o=r[s],a=e[s+i];o&&a&&o.index===a.index&&o.fragment.sn===a.fragment.sn?t(o,a):i--}}}function Ah(r,e,t){const i=e.skippedSegments,s=Math.max(r.startSN,e.startSN)-e.startSN,n=(r.fragmentHint?1:0)+(i?e.endSN:Math.min(r.endSN,e.endSN))-e.startSN,o=e.startSN-r.startSN,a=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=r.fragmentHint?r.fragments.concat(r.fragmentHint):r.fragments;for(let c=s;c<=n;c++){const d=l[o+c];let h=a[c];i&&!h&&c<i&&(h=e.fragments[c]=d),d&&h&&t(d,h)}}function ma(r,e){const t=e.startSN+e.skippedSegments-r.startSN,i=r.fragments;t<0||t>=i.length||zr(e,i[t].start)}function zr(r,e){if(e){const t=r.fragments;for(let i=r.skippedSegments;i<t.length;i++)t[i].start+=e;r.fragmentHint&&(r.fragmentHint.start+=e)}}function bh(r,e=1/0){let t=1e3*r.targetduration;if(r.updated){const i=r.fragments,s=4;if(i.length&&t*s>e){const n=i[i.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function xh(r,e,t){if(!(r!=null&&r.details))return null;const i=r.details;let s=i.fragments[e-i.startSN];return s||(s=i.fragmentHint,s&&s.sn===e)?s:e<i.startSN&&t&&t.sn===e?t:null}function va(r,e,t){var i;return r!=null&&r.details?ya((i=r.details)==null?void 0:i.partList,e,t):null}function ya(r,e,t){if(r)for(let i=r.length;i--;){const s=r[i];if(s.index===t&&s.fragment.sn===e)return s}return null}function Ds(r){switch(r.details){case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_TIMEOUT:case D.LEVEL_LOAD_TIMEOUT:case D.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Aa(r,e){const t=Ds(e);return r.default[`${t?"timeout":"error"}Retry`]}function Wr(r,e){const t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function ba(r){return je(je({},r),{errorRetry:null,timeoutRetry:null})}function ks(r,e,t,i){return!!r&&e<r.maxNumRetry&&(Th(i)||!!t)}function Th(r){return r===0&&navigator.onLine===!1||!!r&&(r<400||r>499)}const xa={search:function(r,e){let t=0,i=r.length-1,s=null,n=null;for(;t<=i;){s=(t+i)/2|0,n=r[s];const o=e(n);if(o>0)t=s+1;else if(o<0)i=s-1;else return n}return null}};function Eh(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!W(e))return null;const i=r[0].programDateTime;if(e<(i||0))return null;const s=r[r.length-1].endProgramDateTime;if(e>=(s||0))return null;t=t||0;for(let n=0;n<r.length;++n){const o=r[n];if(Sh(e,t,o))return o}return null}function Qi(r,e,t=0,i=0){let s=null;if(r?s=e[r.sn-e[0].sn+1]||null:t===0&&e[0].start===0&&(s=e[0]),s&&Yr(t,i,s)===0)return s;const n=xa.search(e,Yr.bind(null,t,i));return n&&(n!==r||!s)?n:s}function Yr(r=0,e=0,t){if(t.start<=r&&t.start+t.duration>r)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=r?1:t.start-i>r&&t.start?-1:0}function Sh(r,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>r}function Ih(r,e){return xa.search(r,t=>t.cc<e?1:t.cc>e?-1:0)}const Ch=3e5;var Ye={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},ct={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class wh{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=C.log.bind(C,"[info]:"),this.warn=C.warn.bind(C,"[warning]:"),this.error=C.error.bind(C,"[error]:"),this.registerListeners()}registerListeners(){const 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(){const 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,this.penalizedRenditions={}}startLoad(e){this.playlistError=0}stopLoad(){}getVariantLevelIndex(e){return(e==null?void 0:e.type)===Z.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const s=this.hls,n=t.context;switch(t.details){case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Ye.SendAlternateToPenaltyBox;return}case D.LEVEL_EMPTY_ERROR:case D.LEVEL_PARSING_ERROR:{var o,a;const l=t.parent===Z.MAIN?t.level:s.loadLevel;t.details===D.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(a=o.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l))}return;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:typeof(n==null?void 0:n.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case D.AUDIO_TRACK_LOAD_ERROR:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.SUBTITLE_LOAD_ERROR:case D.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const l=s.levels[s.loadLevel];if(l&&(n.type===ae.AUDIO_TRACK&&n.groupId===l.audioGroupId||n.type===ae.SUBTITLE_TRACK&&n.groupId===l.textGroupId)){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=Ye.SendAlternateToPenaltyBox,t.errorAction.flags=ct.MoveAllAlternatesMatchingHost;return}}return;case D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const l=s.levels[s.loadLevel],c=l==null?void 0:l.attrs["HDCP-LEVEL"];c&&(t.errorAction={action:Ye.SendAlternateToPenaltyBox,flags:ct.MoveAllAlternatesMatchingHDCP,hdcpLevel:c})}return;case D.BUFFER_ADD_CODEC_ERROR:case D.REMUX_ALLOC_ERROR:t.errorAction=this.getLevelSwitchAction(t,(i=t.level)!=null?i:s.loadLevel);return;case D.INTERNAL_EXCEPTION:case D.BUFFER_APPENDING_ERROR:case D.BUFFER_APPEND_ERROR:case D.BUFFER_FULL_ERROR:case D.LEVEL_SWITCH_ERROR:case D.BUFFER_STALLED_ERROR:case D.BUFFER_SEEK_OVER_HOLE:case D.BUFFER_NUDGE_ON_STALL:t.errorAction={action:Ye.DoNothing,flags:ct.None};return}if(t.type===q.KEY_SYSTEM_ERROR){const l=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l);return}}getPlaylistRetryOrSwitchAction(e,t){var i;const s=this.hls,n=Aa(s.config.playlistLoadPolicy,e),o=this.playlistError++,a=(i=e.response)==null?void 0:i.code;if(ks(n,o,Ds(e),a))return{action:Ye.RetryRequest,flags:ct.None,retryConfig:n,retryCount:o};const c=this.getLevelSwitchAction(e,t);return n&&(c.retryConfig=n,c.retryCount=o),c}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:o}=t.config,a=Aa(e.details.startsWith("key")?o:n,e),l=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(s){var c;e.details!==D.FRAG_GAP&&s.fragmentError++;const h=(c=e.response)==null?void 0:c.code;if(ks(a,l,Ds(e),h))return{action:Ye.RetryRequest,flags:ct.None,retryConfig:a,retryCount:l}}const d=this.getLevelSwitchAction(e,i);return a&&(d.retryConfig=a,d.retryCount=l),d}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const s=this.hls.levels[t];if(s&&(s.loadError++,i.autoLevelEnabled)){var n,o;let a=-1;const{levels:l,loadLevel:c,minAutoLevel:d,maxAutoLevel:h}=i,u=(n=e.frag)==null?void 0:n.type,{type:f,groupId:g}=(o=e.context)!=null?o:{};for(let p=l.length;p--;){const m=(p+c)%l.length;if(m!==c&&m>=d&&m<=h&&l[m].loadError===0){const A=l[m];if(e.details===D.FRAG_GAP&&e.frag){const T=l[m].details;if(T){const b=Qi(e.frag,T.fragments,e.frag.start);if(b!=null&&b.gap)continue}}else{if(f===ae.AUDIO_TRACK&&g===A.audioGroupId||f===ae.SUBTITLE_TRACK&&g===A.textGroupId)continue;if(u===Z.AUDIO&&s.audioGroupId===A.audioGroupId||u===Z.SUBTITLE&&s.textGroupId===A.textGroupId)continue}a=m;break}}if(a>-1&&i.loadLevel!==a)return e.levelRetry=!0,this.playlistError=0,{action:Ye.SendAlternateToPenaltyBox,flags:ct.None,nextAutoLevel:a}}return{action:Ye.SendAlternateToPenaltyBox,flags:ct.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case Ye.DoNothing:break;case Ye.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==D.FRAG_GAP&&(t.fatal=!0);break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:s,hdcpLevel:n,nextAutoLevel:o}=i;switch(s){case ct.None:this.switchLevel(e,o);break;case ct.MoveAllAlternatesMatchingHost:i.resolved||(i.resolved=this.redundantFailover(e));break;case ct.MoveAllAlternatesMatchingHDCP:n&&(t.maxHdcpLevel=Vr[Vr.indexOf(n)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(e,o)}switchLevel(e,t){t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}redundantFailover(e){const{hls:t,penalizedRenditions:i}=this,s=e.parent===Z.MAIN?e.level:t.loadLevel,n=t.levels[s],o=n.url.length,a=e.frag?e.frag.urlId:n.urlId;n.urlId===a&&(!e.frag||n.details)&&this.penalizeRendition(n,e);for(let l=1;l<o;l++){const c=(a+l)%o,d=i[c];if(!d||Lh(d,e,i[a]))return this.warn(`Switching to Redundant Stream ${c+1}/${o}: "${n.url[c]}" after ${e.details}`),this.playlistError=0,t.levels.forEach(h=>{h.urlId=c}),t.nextLoadLevel=s,!0}return!1}penalizeRendition(e,t){const{penalizedRenditions:i}=this,s=i[e.urlId]||{lastErrorPerfMs:0,errors:[],details:void 0};s.lastErrorPerfMs=performance.now(),s.errors.push(t),s.details=e.details,i[e.urlId]=s}}function Lh(r,e,t){if(performance.now()-r.lastErrorPerfMs>Ch)return!0;const i=r.details;if(e.details===D.FRAG_GAP&&i&&e.frag){const s=e.frag.start,n=Qi(null,i.fragments,s);if(n&&!n.gap)return!0}if(t&&r.errors.length<t.errors.length){const s=r.errors[r.errors.length-1];if(i&&s.frag&&e.frag&&Math.abs(s.frag.start-e.frag.start)>i.targetduration*3)return!0}return!1}class Kr{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=C.log.bind(C,`${t}:`),this.warn=C.warn.bind(C,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){clearTimeout(this.timer),this.timer=-1}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t){const i=t==null?void 0:t.renditionReports;if(i){let s=-1;for(let n=0;n<i.length;n++){const o=i[n];let a;try{a=new self.URL(o.URI,t.url).href}catch(l){C.warn(`Could not construct new URL for Rendition Report: ${l}`),a=o.URI||""}if(a===e){s=n;break}else a===e.substring(0,a.length)&&(s=n)}if(s!==-1){const n=i[s],o=parseInt(n["LAST-MSN"])||(t==null?void 0:t.lastPartSn);let a=parseInt(n["LAST-PART"])||(t==null?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const l=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&l>t.partTarget&&(a+=1)}return new ga(o,a>=0?a:void 0,Zi.No)}}}loadPlaylist(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,i){const{details:s,stats:n}=t,o=self.performance.now(),a=n.loading.first?Math.max(0,o-n.loading.first):0;if(s.advancedDateTime=Date.now()-a,s.live||i!=null&&i.live){if(s.reloaded(i),i&&this.log(`live playlist ${e} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:"MISSED"}`),i&&s.fragments.length>0&&mh(i,s),!this.canLoad||!s.live)return;let l,c,d;if(s.canBlockReload&&s.endSN&&s.advanced){const m=this.hls.config.lowLatencyMode,A=s.lastPartSn,T=s.endSN,b=s.lastPartIndex,y=b!==-1,x=A===T,E=m?0:b;y?(c=x?T+1:A,d=x?E:b+1):c=T+1;const S=s.age,R=S+s.ageHeader;let w=Math.min(R-s.partTarget,s.targetduration*1.5);if(w>0){if(i&&w>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${w} with playlist age: ${s.age}`),w=0;else{const I=Math.floor(w/s.targetduration);if(c+=I,d!==void 0){const O=Math.round(w%s.targetduration/s.partTarget);d+=O}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${S.toFixed(2)}s goal: ${w} skip sn ${I} to part ${d}`)}s.tuneInGoal=w}if(l=this.getDeliveryDirectives(s,t.deliveryDirectives,c,d),m||!x){this.loadPlaylist(l);return}}else s.canBlockReload&&(l=this.getDeliveryDirectives(s,t.deliveryDirectives,c,d));const h=this.hls.mainForwardBufferInfo,u=h?h.end-h.len:0,f=(s.edge-u)*1e3,g=bh(s,f);s.updated&&o>this.requestScheduled+g&&(this.requestScheduled=n.loading.start),c!==void 0&&s.canBlockReload?this.requestScheduled=n.loading.first+g-(s.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+g<o?this.requestScheduled=o:this.requestScheduled-o<=0&&(this.requestScheduled+=g);let p=this.requestScheduled-o;p=Math.max(0,p),this.log(`reload live playlist ${e} in ${Math.round(p)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(l),p)}else this.clearTimer()}getDeliveryDirectives(e,t,i,s){let n=ph(e,i);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,n=Zi.No),new ga(i,s,n)}checkRetry(e){const t=e.details,i=Ds(e),s=e.errorAction,{action:n,retryCount:o=0,retryConfig:a}=s||{},l=!!s&&!!a&&(n===Ye.RetryRequest||!s.resolved&&n===Ye.SendAlternateToPenaltyBox);if(l){var c;if(this.requestScheduled=-1,o>=a.maxNumRetry)return!1;if(i&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const d=Wr(a,o);this.timer=self.setTimeout(()=>this.loadPlaylist(),d),this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" in ${d}ms`)}e.levelRetry=!0,s.resolved=!0}return l}}let Xr;class Rh extends Kr{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-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(){const{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.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(v.FRAG_LOADED,this.onFragLoaded,this),e.on(v.ERROR,this.onError,this)}_unregisterListeners(){const{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.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(v.FRAG_LOADED,this.onFragLoaded,this),e.off(v.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}startLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.startLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=[],s={};let n;t.levels.forEach(o=>{var a;const l=o.attrs;((a=o.audioCodec)==null?void 0:a.indexOf("mp4a.40.34"))!==-1&&(Xr||(Xr=/chrome|firefox/i.test(navigator.userAgent)),Xr&&(o.audioCodec=void 0));const{AUDIO:c,CODECS:d,"FRAME-RATE":h,"PATHWAY-ID":u,RESOLUTION:f,SUBTITLES:g}=l,m=`${`${u||"."}-`}${o.bitrate}-${f}-${h}-${d}`;n=s[m],n?n.addFallback(o):(n=new Ji(o),s[m]=n,i.push(n)),Ps(n,"audio",c),Ps(n,"text",g)}),this.filterAndSortMediaOptions(i,t)}filterAndSortMediaOptions(e,t){let i=[],s=[],n=!1,o=!1,a=!1,l=e.filter(({audioCodec:f,videoCodec:g,width:p,height:m,unknownCodecs:A})=>(n||(n=!!(p&&m)),o||(o=!!g),a||(a=!!f),!(A!=null&&A.length)&&(!f||Nr(f,"audio"))&&(!g||Nr(g,"video"))));if((n||o)&&a&&(l=l.filter(({videoCodec:f,width:g,height:p})=>!!f||!!(g&&p))),l.length===0){Promise.resolve().then(()=>{if(this.hls){const f=new Error("no level with compatible codecs found in manifest");this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:f,reason:f.message})}});return}t.audioTracks&&(i=t.audioTracks.filter(f=>!f.audioCodec||Nr(f.audioCodec,"audio")),Ta(i)),t.subtitles&&(s=t.subtitles,Ta(s));const c=l.slice(0);l.sort((f,g)=>f.attrs["HDCP-LEVEL"]!==g.attrs["HDCP-LEVEL"]?(f.attrs["HDCP-LEVEL"]||"")>(g.attrs["HDCP-LEVEL"]||"")?1:-1:f.bitrate!==g.bitrate?f.bitrate-g.bitrate:f.attrs["FRAME-RATE"]!==g.attrs["FRAME-RATE"]?f.attrs.decimalFloatingPoint("FRAME-RATE")-g.attrs.decimalFloatingPoint("FRAME-RATE"):f.attrs.SCORE!==g.attrs.SCORE?f.attrs.decimalFloatingPoint("SCORE")-g.attrs.decimalFloatingPoint("SCORE"):n&&f.height!==g.height?f.height-g.height:0);let d=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let f=0;f<c.length;f++)if(c[f].pathwayId===l[0].pathwayId){d=c[f];break}}this._levels=l;for(let f=0;f<l.length;f++)if(l[f]===d){this._firstLevel=f,this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${d.bitrate}`);break}const h=a&&!o,u={levels:l,audioTracks:i,subtitleTracks:s,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:a,video:o,altAudio:!h&&i.some(f=>!!f.url)};this.hls.trigger(v.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const d=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(v.ERROR,{type:q.OTHER_ERROR,details:D.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:d,reason:d.message}),h)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,o=t[e],a=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,i===e&&o.details&&s&&n===a)return;this.log(`Switching to level ${e}${a?" with Pathway "+a:""} from level ${i}${n?" with Pathway "+n:""}`);const l=Ce({},o,{level:e,maxBitrate:o.maxBitrate,attrs:o.attrs,uri:o.uri,urlId:o.urlId});delete l._attrs,delete l._urlId,this.hls.trigger(v.LEVEL_SWITCHING,l);const c=o.details;if(!c||c.live){const d=this.switchParams(o.uri,s==null?void 0:s.details);this.loadPlaylist(d)}}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){const e=this.hls.config.startLevel;return e!==void 0?e:this._firstLevel}else return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===ae.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragLoaded(e,{frag:t}){if(t!==void 0&&t.type===Z.MAIN){const i=this._levels[t.level];i!==void 0&&(i.loadError=0)}}onLevelLoaded(e,t){var i;const{level:s,details:n}=t,o=this._levels[s];if(!o){var a;this.warn(`Invalid level index ${s}`),(a=t.deliveryDirectives)!=null&&a.skip&&(n.deltaUpdateFailed=!0);return}s===this.currentLevelIndex?(o.fragmentError===0&&(o.loadError=0),this.playlistLoaded(s,t,o.details)):(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}onAudioTrackSwitched(e,t){const i=this.currentLevel;if(!i)return;const s=this.hls.audioTracks[t.id].groupId;if(i.audioGroupIds&&i.audioGroupId!==s){let n=-1;for(let o=0;o<i.audioGroupIds.length;o++)if(i.audioGroupIds[o]===s){n=o;break}n!==-1&&n!==i.urlId&&(i.urlId=n,this.canLoad&&this.startLoad())}}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){const s=i.urlId;let n=i.uri;if(e)try{n=e.addDirectives(n)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}const o=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${o?" Pathway "+o:""} URI ${s+1}/${i.url.length} ${n}`),this.clearTimer(),this.hls.trigger(v.LEVEL_LOADING,{url:n,level:t,id:s,deliveryDirectives:e||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,t){const i=(n,o)=>o!==t,s=this._levels.filter((n,o)=>o!==e?!0:n.url.length>1&&t!==void 0?(n.url=n.url.filter(i),n.audioGroupIds&&(n.audioGroupIds=n.audioGroupIds.filter(i)),n.textGroupIds&&(n.textGroupIds=n.textGroupIds.filter(i)),n.urlId=0,!0):(this.steering&&this.steering.removeLevel(n),!1));this.hls.trigger(v.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){t.forEach((i,s)=>{const{details:n}=i;n!=null&&n.fragments&&n.fragments.forEach(o=>{o.level=s})}),this._levels=t}}function Ps(r,e,t){t&&(e==="audio"?(r.audioGroupIds||(r.audioGroupIds=[]),r.audioGroupIds[r.url.length-1]=t):e==="text"&&(r.textGroupIds||(r.textGroupIds=[]),r.textGroupIds[r.url.length-1]=t))}function Ta(r){const e={};r.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}var ke={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Dh{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=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=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(){const{hls:e}=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.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let s=i.length;s--;){const n=i[s];if(!n)break;const o=n.end;if(n.start<=e&&o!==null&&e<=o)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:i}=this,s=Object.keys(i);for(let n=s.length;n--;){const o=i[s[n]];if((o==null?void 0:o.body.type)===t&&o.buffered){const a=o.body;if(a.start<=e&&e<=a.end)return a}}return null}detectEvictedFragments(e,t,i,s){this.timeRanges&&(this.timeRanges[e]=t);const n=(s==null?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const a=this.fragments[o];if(!a||n>=a.body.sn)return;if(!a.buffered&&!a.loaded){a.body.type===i&&this.removeFragment(a.body);return}const l=a.range[e];l&&l.time.some(c=>{const d=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return d&&this.removeFragment(a.body),d})})}detectPartialFragments(e){const t=this.timeRanges,{frag:i,part:s}=e;if(!t||i.sn==="initSegment")return;const n=gi(i),o=this.fragments[n];if(!o)return;const a=!i.relurl;Object.keys(t).forEach(l=>{const c=i.elementaryStreams[l];if(!c)return;const d=t[l],h=a||c.partial===!0;o.range[l]=this.getBufferedTimes(i,s,h,d)}),o.loaded=null,Object.keys(o.range).length?(o.buffered=!0,o.body.endList&&(this.endListFragments[o.body.type]=o),Os(o)||this.removeParts(i.sn-1,i.type)):this.removeFragment(o.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=i.filter(s=>s.fragment.sn>=e))}fragBuffered(e,t){const i=gi(e);let s=this.fragments[i];!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)}getBufferedTimes(e,t,i,s){const n={time:[],partial:i},o=e.start,a=e.end,l=e.minEndPTS||a,c=e.maxStartPTS||o;for(let d=0;d<s.length;d++){const h=s.start(d)-this.bufferPadding,u=s.end(d)+this.bufferPadding;if(c>=h&&l<=u){n.time.push({startPTS:Math.max(o,s.start(d)),endPTS:Math.min(a,s.end(d))});break}else if(o<u&&a>h)n.partial=!0,n.time.push({startPTS:Math.max(o,s.start(d)),endPTS:Math.min(a,s.end(d))});else if(a<=h)break}return n}getPartialFragment(e){let t=null,i,s,n,o=0;const{bufferPadding:a,fragments:l}=this;return Object.keys(l).forEach(c=>{const d=l[c];d&&Os(d)&&(s=d.body.start-a,n=d.body.end+a,e>=s&&e<=n&&(i=Math.min(e-s,n-e),o<=i&&(t=d.body,o=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Os(t))}getState(e){const t=gi(e),i=this.fragments[t];return i?i.buffered?Os(i)?ke.PARTIAL:ke.OK:ke.APPENDING:ke.NOT_LOADED}isTimeBuffered(e,t,i){let s,n;for(let o=0;o<i.length;o++){if(s=i.start(o)-this.bufferPadding,n=i.end(o)+this.bufferPadding,e>=s&&t<=n)return!0;if(t<=s)return!1}return!1}onFragLoaded(e,t){const{frag:i,part:s}=t;if(i.sn==="initSegment"||i.bitrateTest)return;const n=s?null:t,o=gi(i);this.fragments[o]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:s,timeRanges:n}=t;if(i.sn==="initSegment")return;const o=i.type;if(s){let a=this.activePartLists[o];a||(this.activePartLists[o]=a=[]),a.push(s)}this.timeRanges=n,Object.keys(n).forEach(a=>{const l=n[a];this.detectEvictedFragments(a,l,o,s)})}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=gi(e);return!!this.fragments[t]}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,s,n){s&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const a=this.fragments[o];if(!a)return;const l=a.body;l.type!==i||s&&!l.gap||l.start<t&&l.end>e&&(a.buffered||n)&&this.removeFragment(l)})}removeFragment(e){const t=gi(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const s=e.sn;this.activePartLists[e.type]=i.filter(n=>n.fragment.sn!==s)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function Os(r){var e,t,i;return r.buffered&&(r.body.gap||((e=r.range.video)==null?void 0:e.partial)||((t=r.range.audio)==null?void 0:t.partial)||((i=r.range.audiovideo)==null?void 0:i.partial))}function gi(r){return`${r.type}_${r.level}_${r.urlId}_${r.sn}`}const Ea=Math.pow(2,17);class kh{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){const i=e.url;if(!i)return Promise.reject(new wt({type:q.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const s=this.config,n=s.fLoader,o=s.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap){l(Ia(e));return}const c=this.loader=e.loader=n?new n(s):new o(s),d=Sa(e),h=ba(s.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Ea};e.stats=c.stats,c.load(d,u,{onSuccess:(f,g,p,m)=>{this.resetLoader(e,c);let A=f.data;p.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(A.slice(0,16)),A=A.slice(16)),a({frag:e,part:null,payload:A,networkDetails:m})},onError:(f,g,p,m)=>{this.resetLoader(e,c),l(new wt({type:q.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:je({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:m}))},onAbort:(f,g,p)=>{this.resetLoader(e,c),l(new wt({type:q.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,c),l(new wt({type:q.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:p,stats:f}))},onProgress:(f,g,p,m)=>{t&&t({frag:e,part:null,payload:p,networkDetails:m})}})})}loadPart(e,t,i){this.abort();const s=this.config,n=s.fLoader,o=s.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Ia(e,t));return}const c=this.loader=e.loader=n?new n(s):new o(s),d=Sa(e,t),h=ba(s.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ea};t.stats=c.stats,c.load(d,u,{onSuccess:(f,g,p,m)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const A={frag:e,part:t,payload:f.data,networkDetails:m};i(A),a(A)},onError:(f,g,p,m)=>{this.resetLoader(e,c),l(new wt({type:q.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:je({url:d.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:m}))},onAbort:(f,g,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new wt({type:q.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,c),l(new wt({type:q.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(e,t){const i=e.stats,s=t.stats,n=s.total;if(i.loaded+=s.loaded,n){const l=Math.round(e.duration/t.duration),c=Math.min(Math.round(i.loaded/n),l),h=(l-c)*Math.round(i.loaded/c);i.total=i.loaded+h}else i.total=Math.max(i.loaded,i.total);const o=i.loading,a=s.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 Sa(r,e=null){const t=e||r,i={frag:r,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},s=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(W(s)&&W(n)){var o;let a=s,l=n;if(r.sn==="initSegment"&&((o=r.decryptdata)==null?void 0:o.method)==="AES-128"){const c=n-s;c%16&&(l=n+(16-c%16)),s!==0&&(i.resetIV=!0,a=s-16)}i.rangeStart=a,i.rangeEnd=l}return i}function Ia(r,e){const t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),i={type:q.MEDIA_ERROR,details:D.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(i.part=e),(e||r).stats.aborted=!0,new wt(i)}class wt extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Ph{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const t in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[t].loader;if(i){if(e&&e!==i.context.frag.type)return;i.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=D.KEY_LOAD_ERROR,i,s,n){return new wt({type:q.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:s})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:s}=e;for(let n=0;n<t.length;n++){const o=t[n];if(s<=o.cc&&(i==="initSegment"||o.sn==="initSegment"||i<o.sn)){this.emeController.selectKeySystemFormat(o).then(a=>{o.setKeyFormat(a)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,c))}const o=n.uri;if(!o)return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${o}"`)));let a=this.keyUriToKeyInfo[o];if((i=a)!=null&&i.decryptdata.key)return n.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});if((s=a)!=null&&s.keyLoadPromise){var l;switch((l=a.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then(c=>(n.key=c.keyInfo.decryptdata.key,{frag:e,keyInfo:a}))}}switch(a=this.keyUriToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const s=this.emeController.loadKey(i);if(s)return(e.keyLoadPromise=s.then(n=>(e.mediaKeySessionContext=n,i))).catch(n=>{throw e.keyLoadPromise=null,n})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,s=i.loader,n=new s(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((o,a)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=i.keyLoadPolicy.default,d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,f,g,p)=>{const{frag:m,keyInfo:A,url:T}=g;if(!m.decryptdata||A!==this.keyUriToKeyInfo[T])return a(this.createKeyLoadError(m,D.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));A.decryptdata.key=m.decryptdata.key=new Uint8Array(u.data),m.keyLoader=null,A.loader=null,o({frag:m,keyInfo:A})},onError:(u,f,g,p)=>{this.resetLoader(f),a(this.createKeyLoadError(t,D.KEY_LOAD_ERROR,new Error(`HTTP Error ${u.code} loading key ${u.text}`),g,je({url:l.url,data:void 0},u)))},onTimeout:(u,f,g)=>{this.resetLoader(f),a(this.createKeyLoadError(t,D.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(u,f,g)=>{this.resetLoader(f),a(this.createKeyLoadError(t,D.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};n.load(l,d,h)})}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[s],n&&n.destroy()}}class Oh{constructor(){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?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}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(){}}const Mh={length:0,start:()=>0,end:()=>0};class fe{static isBuffered(e,t){try{if(e){const i=fe.getBuffered(e);for(let s=0;s<i.length;s++)if(t>=i.start(s)&&t<=i.end(s))return!0}}catch{}return!1}static bufferInfo(e,t,i){try{if(e){const s=fe.getBuffered(e),n=[];let o;for(o=0;o<s.length;o++)n.push({start:s.start(o),end:s.end(o)});return this.bufferedInfo(n,t,i)}}catch{}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.sort(function(c,d){const h=c.start-d.start;return h||d.end-c.end});let s=[];if(i)for(let c=0;c<e.length;c++){const d=s.length;if(d){const h=s[d-1].end;e[c].start-h<i?e[c].end>h&&(s[d-1].end=e[c].end):s.push(e[c])}else s.push(e[c])}else s=e;let n=0,o,a=t,l=t;for(let c=0;c<s.length;c++){const d=s[c].start,h=s[c].end;if(t+i>=d&&t<h)a=d,l=h,n=l-t;else if(t+i<d){o=d;break}}return{len:n,start:a||0,end:l||0,nextStart:o}}static getBuffered(e){try{return e.buffered}catch(t){return C.log("failed to get media.buffered",t),Mh}}}class qr{constructor(e,t,i,s=0,n=-1,o=!1){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=Ms(),this.buffering={audio:Ms(),video:Ms(),audiovideo:Ms()},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=n,this.partial=o}}function Ms(){return{start:0,executeStart:0,executeEnd:0,end:0}}function Ca(r,e){let t=null;for(let i=0,s=r.length;i<s;i++){const n=r[i];if(n&&n.cc===e){t=n;break}}return t}function Fh(r,e,t){return!!(e.details&&(t.endCC>t.startCC||r&&r.cc<t.startCC))}function Nh(r,e,t=0){const i=r.fragments,s=e.fragments;if(!s.length||!i.length){C.log("No fragments to align");return}const n=Ca(i,s[0].cc);if(!n||n&&!n.startPTS){C.log("No frag in previous level to align on");return}return n}function wa(r,e){if(r){const t=r.start+e;r.start=r.startPTS=t,r.endPTS=t+r.duration}}function Zr(r,e){const t=e.fragments;for(let i=0,s=t.length;i<s;i++)wa(t[i],r);e.fragmentHint&&wa(e.fragmentHint,r),e.alignedSliding=!0}function Bh(r,e,t){e&&(Uh(r,t,e),!t.alignedSliding&&e.details&&Hh(t,e.details),!t.alignedSliding&&e.details&&!t.skippedSegments&&ma(e.details,t))}function Uh(r,e,t){if(Fh(r,t,e)){const i=Nh(t.details,e);i&&W(i.start)&&(C.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),Zr(i.start,e))}}function Hh(r,e){if(!e.fragments.length||!r.hasProgramDateTime||!e.hasProgramDateTime)return;const t=e.fragments[0].programDateTime,i=r.fragments[0].programDateTime,s=(i-t)/1e3+e.fragments[0].start;s&&W(s)&&(C.log(`Adjusting PTS using programDateTime delta ${i-t}ms, sliding:${s.toFixed(3)} ${r.url} `),Zr(s,r))}function La(r,e){if(!r.hasProgramDateTime||!e.hasProgramDateTime)return;const t=r.fragments,i=e.fragments;if(!t.length||!i.length)return;const s=Math.round(i.length/2)-1,n=i[s],o=Ca(t,n.cc)||t[Math.round(t.length/2)-1],a=n.programDateTime,l=o.programDateTime;if(a===null||l===null)return;const c=(l-a)/1e3-(o.start-n.start);Zr(c,r)}class Gh{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class Vh{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function jh(r){const e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?_t(r,0,e-t):r}class zh{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){const t=new DataView(e),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=t.getUint32(s*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],n=i[1],o=i[2],a=i[3],l=this.invSubMix,c=l[0],d=l[1],h=l[2],u=l[3],f=new Uint32Array(256);let g=0,p=0,m=0;for(m=0;m<256;m++)m<128?f[m]=m<<1:f[m]=m<<1^283;for(m=0;m<256;m++){let A=p^p<<1^p<<2^p<<3^p<<4;A=A>>>8^A&255^99,e[g]=A,t[A]=g;const T=f[g],b=f[T],y=f[b];let x=f[A]*257^A*16843008;s[g]=x<<24|x>>>8,n[g]=x<<16|x>>>16,o[g]=x<<8|x>>>24,a[g]=x,x=y*16843009^b*65537^T*257^g*16843008,c[A]=x<<24|x>>>8,d[A]=x<<16|x>>>16,h[A]=x<<8|x>>>24,u[A]=x,g?(g=T^f[f[f[y^T]]],p^=f[f[p]]):g=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,s=0;for(;s<t.length&&i;)i=t[s]===this.key[s],s++;if(i)return;this.key=t;const n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);const o=this.ksRows=(n+6+1)*4;let a,l;const c=this.keySchedule=new Uint32Array(o),d=this.invKeySchedule=new Uint32Array(o),h=this.sBox,u=this.rcon,f=this.invSubMix,g=f[0],p=f[1],m=f[2],A=f[3];let T,b;for(a=0;a<o;a++){if(a<n){T=c[a]=t[a];continue}b=T,a%n===0?(b=b<<8|b>>>24,b=h[b>>>24]<<24|h[b>>>16&255]<<16|h[b>>>8&255]<<8|h[b&255],b^=u[a/n|0]<<24):n>6&&a%n===4&&(b=h[b>>>24]<<24|h[b>>>16&255]<<16|h[b>>>8&255]<<8|h[b&255]),c[a]=T=(c[a-n]^b)>>>0}for(l=0;l<o;l++)a=o-l,l&3?b=c[a]:b=c[a-4],l<4||a<=4?d[l]=b:d[l]=g[h[b>>>24]]^p[h[b>>>16&255]]^m[h[b>>>8&255]]^A[h[b&255]],d[l]=d[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const s=this.keySize+6,n=this.invKeySchedule,o=this.invSBox,a=this.invSubMix,l=a[0],c=a[1],d=a[2],h=a[3],u=this.uint8ArrayToUint32Array_(i);let f=u[0],g=u[1],p=u[2],m=u[3];const A=new Int32Array(e),T=new Int32Array(A.length);let b,y,x,E,S,R,w,I,O,P,B,J,H,V;const j=this.networkToHostOrderSwap;for(;t<A.length;){for(O=j(A[t]),P=j(A[t+1]),B=j(A[t+2]),J=j(A[t+3]),S=O^n[0],R=J^n[1],w=B^n[2],I=P^n[3],H=4,V=1;V<s;V++)b=l[S>>>24]^c[R>>16&255]^d[w>>8&255]^h[I&255]^n[H],y=l[R>>>24]^c[w>>16&255]^d[I>>8&255]^h[S&255]^n[H+1],x=l[w>>>24]^c[I>>16&255]^d[S>>8&255]^h[R&255]^n[H+2],E=l[I>>>24]^c[S>>16&255]^d[R>>8&255]^h[w&255]^n[H+3],S=b,R=y,w=x,I=E,H=H+4;b=o[S>>>24]<<24^o[R>>16&255]<<16^o[w>>8&255]<<8^o[I&255]^n[H],y=o[R>>>24]<<24^o[w>>16&255]<<16^o[I>>8&255]<<8^o[S&255]^n[H+1],x=o[w>>>24]<<24^o[I>>16&255]<<16^o[S>>8&255]<<8^o[R&255]^n[H+2],E=o[I>>>24]<<24^o[S>>16&255]<<16^o[R>>8&255]<<8^o[w&255]^n[H+3],T[t]=j(b^f),T[t+1]=j(E^g),T[t+2]=j(x^p),T[t+3]=j(y^m),f=O,g=P,p=B,m=J,t=t+4}return T.buffer}}const Wh=16;class Jr{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,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.useSoftware=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.subtle===null&&(this.useSoftware=!0)}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(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?jh(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i){return this.useSoftware?new Promise((s,n)=>{this.softwareDecrypt(new Uint8Array(e),t,i);const o=this.flush();o?s(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i)}softwareDecrypt(e,t,i){const{currentIV:s,currentResult:n,remainderData:o}=this;this.logOnce("JS AES decrypt"),o&&(e=$t(o,e),this.remainderData=null);const a=this.getValidChunk(e);if(!a.length)return null;s&&(i=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new zh),l.expandKey(t);const c=n;return this.currentResult=l.decrypt(a.buffer,0,i),this.currentIV=_t(a,-16).buffer,c||null}webCryptoDecrypt(e,t,i){const s=this.subtle;return(this.key!==t||!this.fastAesKey)&&(this.key=t,this.fastAesKey=new Vh(s,t)),this.fastAesKey.expandKey().then(n=>s?(this.logOnce("WebCrypto AES decrypt"),new Gh(s,new Uint8Array(i)).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(C.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i)))}onWebCryptoError(e,t,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i);const s=this.flush();if(s)return s.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%Wh;return i!==e.length&&(t=_t(e,0,i),this.remainderData=_t(e,i)),t}logOnce(e){this.logEnabled&&(C.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Yh={toString:function(r){let e="";const t=r.length;for(let i=0;i<t;i++)e+=`[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;return e}},M={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"};class Qr extends Oh{constructor(e,t,i,s,n){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=M.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=n,this.logPrefix=s,this.log=C.log.bind(C,`${s}:`),this.warn=C.warn.bind(C,`${s}:`),this.hls=e,this.fragmentLoader=new kh(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Jr(e.config),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const 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=M.STOPPED}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;const i=t.partList;if(i!=null&&i.length){const n=i[i.length-1];return fe.isBuffered(this.media,n.start+n.duration/2)}const s=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(s)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levels[this.levelLastLoaded])==null?void 0:e.details}}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),i.addEventListener("seeking",this.onvseeking),i.addEventListener("ended",this.onvended);const s=this.config;this.levels&&s.autoStartLoad&&this.state===M.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(){const e=this.media;e!=null&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:t,media:i,mediaBuffer:s,state:n}=this,o=i?i.currentTime:0,a=fe.bufferInfo(s||i,o,e.maxBufferHole);if(this.log(`media seeking to ${W(o)?o.toFixed(3):o}, state: ${n}`),this.state===M.ENDED)this.resetLoadingState();else if(t){const l=e.maxFragLookUpTolerance,c=t.start-l,d=t.start+t.duration+l;if(!a.len||d<a.start||c>a.end){const h=o>d;(o<c||h)&&(h&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}i&&(this.fragmentTracker.removeFragmentsInRange(o,1/0,this.playlistType,!0),this.lastCurrentTime=o),!this.loadedmetadata&&!a.len&&(this.nextLoadPosition=this.startPosition=o),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.stopLoad(),super.onHandlerDestroying()}onHandlerDestroyed(){this.state=M.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._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const s=n=>{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${n.part?" p: "+n.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,i,s).then(n=>{if(!n)return;const o=this.state;if(this.fragContextChanged(e)){(o===M.FRAG_LOADING||!this.fragCurrent&&o===M.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=M.IDLE);return}"payload"in n&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(v.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===M.STOPPED||this.state===M.ERROR||(this.warn(n),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===ke.APPENDING){const n=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,n),a=Math.max(e.duration,o?o.len:this.config.maxBufferLength);this.reduceMaxBufferLength(a)&&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)===ke.PARTIAL&&i.removeFragment(e))}flushMainBuffer(e,t,i=null){if(!(e-t))return;const s={startOffset:e,endOffset:t,type:i};this.hls.trigger(v.BUFFER_FLUSHING,s)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{if(!i||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:s}=this,{payload:n}=i,o=e.decryptdata;if(n&&n.byteLength>0&&o&&o.key&&o.iv&&o.method==="AES-128"){const a=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),o.key.buffer,o.iv.buffer).catch(l=>{throw s.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:e}),l}).then(l=>{const c=self.performance.now();return s.trigger(v.FRAG_DECRYPTED,{frag:e,payload:l,stats:{tstart:a,tdecrypt:c}}),i.payload=l,i})}return i}).then(i=>{const{fragCurrent:s,hls:n,levels:o}=this;if(!o)throw new Error("init load aborted, missing levels");const a=e.stats;this.state=M.IDLE,t.fragmentError=0,e.data=new Uint8Array(i.payload),a.parsing.start=a.buffering.start=self.performance.now(),a.parsing.end=a.buffering.end=self.performance.now(),i.frag===s&&n.trigger(v.FRAG_BUFFERED,{stats:a,frag:s,part:null,id:e.type}),this.tick()}).catch(i=>{this.state===M.STOPPED||this.state===M.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.level!==t.level||e.sn!==t.sn||e.urlId!==t.urlId}fragBufferedComplete(e,t){var i,s,n,o;const a=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===Z.MAIN?"level":"track"} ${e.level} (frag:[${((i=e.startPTS)!=null?i:NaN).toFixed(3)}-${((s=e.endPTS)!=null?s:NaN).toFixed(3)}] > buffer:${a?Yh.toString(fe.getBuffered(a)):"(detached)"})`),this.state=M.IDLE,a&&(!this.loadedmetadata&&e.type==Z.MAIN&&a.buffered.length&&((n=this.fragCurrent)==null?void 0:n.sn)===((o=this.fragPrevious)==null?void 0:o.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:s,partsLoaded:n}=e,o=!n||n.length===0||n.some(l=>!l),a=new qr(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!o);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,s){var n;const o=t==null?void 0: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)?(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${e.level}`),this.state=M.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(v.KEY_LOADED,d),this.state===M.KEY_LOADING&&(this.state=M.IDLE),d}),this.hls.trigger(v.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&o.encryptedFragments.length&&this.keyLoader.loadClear(e,o.encryptedFragments),i=Math.max(e.start,i||0),this.config.lowLatencyMode&&e.sn!=="initSegment"){const d=o.partList;if(d&&s){i>e.end&&o.fragmentHint&&(e=o.fragmentHint);const h=this.getNextPart(d,e,i);if(h>-1){const u=d[h];this.log(`Loading part sn: ${e.sn} p: ${u.index} cc: ${e.cc} of playlist [${o.startSN}-${o.endSN}] parts [0-${h}-${d.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=u.start+u.duration,this.state=M.FRAG_LOADING;let f;return a?f=a.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,u,t,s)).catch(g=>this.handleFragLoadError(g)):f=this.doFragPartsLoad(e,u,t,s).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(v.FRAG_LOADING,{frag:e,part:u,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!e.url||this.loadedEndOfParts(d,i))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${o?"of ["+o.startSN+"-"+o.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),W(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=M.FRAG_LOADING;const l=this.config.progressive;let c;return l&&a?c=a.then(d=>!d||this.fragContextChanged(d==null?void 0:d.frag)?null:this.fragmentLoader.load(e,s)).catch(d=>this.handleFragLoadError(d)):c=Promise.all([this.fragmentLoader.load(e,l?s:void 0),a]).then(([d])=>(!l&&d&&s&&s(d),d)).catch(d=>this.handleFragLoadError(d)),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")):c}doFragPartsLoad(e,t,i,s){return new Promise((n,o)=>{var a;const l=[],c=(a=i.details)==null?void 0:a.partList,d=h=>{this.fragmentLoader.loadPart(e,h,s).then(u=>{l[h.index]=u;const f=u.part;this.hls.trigger(v.FRAG_LOADED,u);const g=va(i,e.sn,h.index+1)||ya(c,e.sn,h.index+1);if(g)d(g);else return n({frag:e,part:f,partsLoaded:l})}).catch(o)};d(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===D.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(v.ERROR,t)}else this.hls.trigger(v.ERROR,{type:q.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==M.PARSING){!this.fragCurrent&&this.state!==M.STOPPED&&this.state!==M.ERROR&&(this.state=M.IDLE);return}const{frag:i,part:s,level:n}=t,o=self.performance.now();i.stats.parsing.end=o,s&&(s.stats.parsing.end=o),this.updateLevelTiming(i,s,n,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:s,sn:n,part:o}=e;if(!(t!=null&&t[s]))return this.warn(`Levels object was unset while buffering fragment ${n} of level ${s}. The current chunk will not be buffered.`),null;const a=t[s],l=o>-1?va(a,n,o):null,c=l?l.fragment:xh(a,n,i);return c?(i&&i!==c&&(c.stats=i.stats),{frag:c,part:l,level:a}):null}bufferFragmentData(e,t,i,s){var n;if(!e||this.state!==M.PARSING)return;const{data1:o,data2:a}=e;let l=o;if(o&&a&&(l=$t(o,a)),!((n=l)!=null&&n.length))return;const c={type:e.type,frag:t,part:i,chunkMeta:s,parent:t.type,data:l};this.hls.trigger(v.BUFFER_APPENDING,c),e.dropped&&e.independent&&!i&&this.flushBufferGap(t)}flushBufferGap(e){const t=this.media;if(!t)return;if(!fe.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,s=fe.bufferInfo(t,i,0),n=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),a=Math.max(Math.min(e.start-o,s.end-o),i+o);e.start-a>o&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){const i=this.getLoadPosition();return W(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){const{config:{maxBufferHole:s}}=this,n=fe.bufferInfo(e,t,s);if(n.len===0&&n.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(t,i);if(o&&n.nextStart<o.end)return fe.bufferInfo(e,t,Math.max(n.nextStart,s))}return n}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e){const t=this.config,i=e||t.maxBufferLength;return t.maxMaxBufferLength>=i?(t.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${t.maxMaxBufferLength}s`),!0):!1}getAppendedFrag(e,t=Z.MAIN){const i=this.fragmentTracker.getAppendedFrag(e,Z.MAIN);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,s=i.length;if(!s)return null;const{config:n}=this,o=i[0].start;let a;if(t.live){const l=n.initialLiveManifestSize;if(s<l)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${l})`),null;!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1&&(a=this.getInitialLiveFragment(t,i),this.startPosition=a?this.hls.liveSyncPosition||a.start:e)}else e<=o&&(a=i[0]);if(!a){const l=n.lowLatencyMode?t.partEnd:t.fragmentEnd;a=this.getFragmentAtPosition(e,l,t)}return this.mapToInitFragWhenRequired(a)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===ke.OK||i===ke.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,s,n){const o=e.gap,a=this.getNextFragment(this.nextLoadPosition,t);if(a===null)return a;if(e=a,o&&e&&!e.gap&&i.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s);if(l!==null&&i.len+l.len>=n)return this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let s=-1,n=!1,o=!0;for(let a=0,l=e.length;a<l;a++){const c=e[a];if(o=o&&!c.independent,s>-1&&i<c.start)break;const d=c.loaded;d?s=-1:(n||c.independent||o)&&c.fragment===t&&(s=a),n=d}return s}loadedEndOfParts(e,t){const i=e[e.length-1];return i&&t>i.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let s=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=Eh(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){const o=t[n-e.startSN];i.cc===o.cc&&(s=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=Ih(t,i.cc),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const n=this.hls.liveSyncPosition;n!==null&&(s=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){const{config:s}=this;let{fragPrevious:n}=this,{fragments:o,endSN:a}=i;const{fragmentHint:l}=i,c=s.maxFragLookUpTolerance,d=i.partList,h=!!(s.lowLatencyMode&&d!=null&&d.length&&l);h&&l&&!this.bitrateTest&&(o=o.concat(l),a=l.sn);let u;if(e<t){const f=e>t-c?0:c;u=Qi(n,o,e,f)}else u=o[o.length-1];if(u){const f=u.sn-i.startSN,g=this.fragmentTracker.getState(u);if((g===ke.OK||g===ke.PARTIAL&&u.gap)&&(n=u),n&&u.sn===n.sn&&(!h||d[0].fragment.sn>u.sn)&&n&&u.level===n.level){const m=o[f+1];u.sn<a&&this.fragmentTracker.getState(m)!==ke.OK?u=m:u=null}}return u}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,n=i.currentTime,o=e.fragments[0].start,a=e.edge,l=n>=o-t.maxFragLookUpTolerance&&n<=a;if(s!==null&&i.duration>s&&(n<s||!l)){const c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!l&&i.readyState<4||n<a-c)&&(this.loadedmetadata||(this.nextLoadPosition=s),i.readyState&&(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${s.toFixed(3)}`),i.currentTime=s))}}alignPlaylists(e,t){const{levels:i,levelLastLoaded:s,fragPrevious:n}=this,o=s!==null?i[s]:null,a=e.fragments.length;if(!a)return this.warn("No fragments in live playlist"),0;const l=e.fragments[0].start,c=!t,d=e.alignedSliding&&W(l);if(c||!d&&!l){Bh(n,o,e);const h=e.fragments[0].start;return this.log(`Live playlist sliding: ${h.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${n?n.sn:"na"} fragments: ${a}`),h}return l}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;if(i<t&&(i=-1),i===-1||this.lastCurrentTime===-1){const s=this.startTimeOffset!==null,n=s?this.startTimeOffset:e.startTimeOffset;n!==null&&W(n)?(i=t+n,n<0&&(i+=e.totalduration),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Start time offset ${n} found in ${s?"multivariant":"media"} playlist, adjust startPosition to ${i}`),this.startPosition=i):e.live?i=this.hls.liveSyncPosition||t:this.startPosition=i=0,this.lastCurrentTime=i}this.nextLoadPosition=i}getLoadPosition(){const{media:e}=this;let t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&e.sn!=="initSegment"&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==M.FRAG_LOADING_WAITING_RETRY)&&(this.state=M.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const d=this.getCurrentContext(t.chunkMeta);d&&(t.frag=d.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var s;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(s=this.fragCurrent)==null?void 0:s.url}`);return}const n=t.details===D.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction,{action:a,retryCount:l=0,retryConfig:c}=o||{};if(o&&a===Ye.RetryRequest&&c){this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition);const d=Wr(c,l);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${l+1}/${c.maxNumRetry} in ${d}ms`),o.resolved=!0,this.retryDate=self.performance.now()+d,this.state=M.FRAG_LOADING_WAITING_RETRY}else c&&o?(this.resetFragmentErrors(e),l<c.maxNumRetry?n||(o.resolved=!0):C.warn(`${t.details} reached or exceeded max retry (${l})`)):this.state=M.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===M.PARSING||this.state===M.PARSED){const t=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,t),s=i&&i.len>.5;s&&this.reduceMaxBufferLength(i.len);const n=!s;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${t} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===Z.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==M.STOPPED&&(this.state=M.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const s=fe.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,i),this.state===M.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=M.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=this.levels?this.levels[e].details:null;t!=null&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(e.level),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){var n;const o=i.details;if(!o){this.warn("level.details undefined");return}if(Object.keys(e.elementaryStreams).reduce((l,c)=>{const d=e.elementaryStreams[c];if(d){const h=d.endPTS-d.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${h})`),l||!1;const u=s?0:pa(o,e,d.startPTS,d.endPTS,d.startDTS,d.endDTS);return this.hls.trigger(v.LEVEL_PTS_UPDATED,{details:o,level:i,drift:u,type:c,frag:e,start:d.startPTS,end:d.endPTS}),!0}return l},!1))i.fragmentError=0;else if(((n=this.transmuxer)==null?void 0:n.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of level ${i.id} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=M.PARSED,this.hls.trigger(v.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.resetTransmuxer(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function Ra(){return self.SourceBuffer||self.WebKitSourceBuffer}function Kh(){const r=Ls();if(!r)return!1;const e=Ra(),t=r&&typeof r.isTypeSupported=="function"&&r.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),i=!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function";return!!t&&!!i}function Xh(){var r;const e=Ra();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}function qh(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Zh(){const r=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(r);return{worker:new self.Worker(e),objectURL:e}}function Jh(r){const e=new self.URL(r,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}function pt(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Da{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,s){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!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=$t(this.cachedData,e),this.cachedData=null);let i=Ss(e,0),s=i?i.length:0,n;const o=this._audioTrack,a=this._id3Track,l=i?Pd(i):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&W(l))&&(this.basePTS=Qh(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:lt.audioId3,duration:Number.POSITIVE_INFINITY});s<c;){if(this.canParse(e,s)){const d=this.appendFrame(o,e,s);d?(this.frameIndex++,this.lastPTS=d.sample.pts,s+=d.length,n=s):s=c}else kd(e,s)?(i=Ss(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:lt.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,n=s):s++;if(s===c&&n!==c){const d=_t(e,n);this.cachedData?this.cachedData=$t(this.cachedData,d):this.cachedData=d}}return{audioTrack:o,videoTrack:pt(),id3Track:a,textTrack:pt()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:pt(),id3Track:this._id3Track,textTrack:pt()}}destroy(){}}const Qh=(r,e,t)=>{if(W(r))return r*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};function _h(r,e,t,i){let s,n,o,a;const l=navigator.userAgent.toLowerCase(),c=i,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=((e[t+2]&192)>>>6)+1;const h=(e[t+2]&60)>>>2;if(h>d.length-1){r.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!0,reason:`invalid ADTS sampling index:${h}`});return}return o=(e[t+2]&1)<<2,o|=(e[t+3]&192)>>>6,C.log(`manifest codec:${i}, ADTS type:${s}, samplingIndex:${h}`),/firefox/i.test(l)?h>=6?(s=5,a=new Array(4),n=h-3):(s=2,a=new Array(2),n=h):l.indexOf("android")!==-1?(s=2,a=new Array(2),n=h):(s=5,a=new Array(4),i&&(i.indexOf("mp4a.40.29")!==-1||i.indexOf("mp4a.40.5")!==-1)||!i&&h>=6?n=h-3:((i&&i.indexOf("mp4a.40.2")!==-1&&(h>=6&&o===1||/vivaldi/i.test(l))||!i&&o===1)&&(s=2,a=new Array(2)),n=h)),a[0]=s<<3,a[0]|=(h&14)>>1,a[1]|=(h&1)<<7,a[1]|=o<<3,s===5&&(a[1]|=(n&14)>>1,a[2]=(n&1)<<7,a[2]|=8,a[3]=0),{config:a,samplerate:d[h],channelCount:o,codec:"mp4a.40."+s,manifestCodec:c}}function ka(r,e){return r[e]===255&&(r[e+1]&246)===240}function Pa(r,e){return r[e+1]&1?7:9}function _r(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function $h(r,e){return e+5<r.length}function Fs(r,e){return e+1<r.length&&ka(r,e)}function eu(r,e){return $h(r,e)&&ka(r,e)&&_r(r,e)<=r.length-e}function tu(r,e){if(Fs(r,e)){const t=Pa(r,e);if(e+t>=r.length)return!1;const i=_r(r,e);if(i<=t)return!1;const s=e+i;return s===r.length||Fs(r,s)}return!1}function Oa(r,e,t,i,s){if(!r.samplerate){const n=_h(e,t,i,s);if(!n)return;r.config=n.config,r.samplerate=n.samplerate,r.channelCount=n.channelCount,r.codec=n.codec,r.manifestCodec=n.manifestCodec,C.log(`parsed codec:${r.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function Ma(r){return 9216e4/r}function iu(r,e){const t=Pa(r,e);if(e+t<=r.length){const i=_r(r,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function Fa(r,e,t,i,s){const n=Ma(r.samplerate),o=i+s*n,a=iu(e,t);let l;if(a){const{frameLength:h,headerLength:u}=a,f=u+h,g=Math.max(0,t+f-e.length);g?(l=new Uint8Array(f-u),l.set(e.subarray(t+u,e.length),0)):l=e.subarray(t+u,t+f);const p={unit:l,pts:o};return g||r.samples.push(p),{sample:p,length:f,missing:g}}const c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:o},length:c,missing:-1}}class su extends Da{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let i=(Ss(e,0)||[]).length;for(let s=e.length;i<s;i++)if(tu(e,i))return C.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return eu(e,t)}appendFrame(e,t,i){Oa(e,this.observer,t,i,e.manifestCodec);const s=Fa(e,t,i,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}}const ru=/\/emsg[-/]ID3/i;class nu{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,s){const n=this.videoTrack=pt("video",1),o=this.audioTrack=pt("audio",1),a=this.txtTrack=pt("text",1);if(this.id3Track=pt("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=Xo(e);if(l.video){const{id:c,timescale:d,codec:h}=l.video;n.id=c,n.timescale=a.timescale=d,n.codec=h}if(l.audio){const{id:c,timescale:d,codec:h}=l.audio;o.id=c,o.timescale=d,o.codec=h}a.id=Wo.text,n.sampleDuration=0,n.duration=o.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return e=e.length>16384?e.subarray(0,16384):e,re(e,["moof"]).length>0}demux(e,t){this.timeOffset=t;let i=e;const s=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=$t(this.remainderData,e));const a=Xd(i);this.remainderData=a.remainder,s.samples=a.valid||new Uint8Array}else s.samples=i;const o=this.extractID3Track(s,t);return n.samples=Zo(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(t,this.timeOffset);return i.samples=Zo(e,t),{videoTrack:t,audioTrack:pt(),id3Track:s,textTrack:pt()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const s=re(e.samples,["emsg"]);s&&s.forEach(n=>{const o=Jd(n);if(ru.test(o.schemeIdUri)){const a=W(o.presentationTime)?o.presentationTime/o.timeScale:t+o.presentationTimeDelta/o.timeScale;let l=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=o.payload;i.samples.push({data:c,len:c.byteLength,dts:a,pts:a,type:lt.emsg,duration:l})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}let Ns=null;const ou=[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],au=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],lu=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],cu=[0,1,1,4];function Na(r,e,t,i,s){if(t+24>e.length)return;const n=Ba(e,t);if(n&&t+n.frameLength<=e.length){const o=n.samplesPerFrame*9e4/n.sampleRate,a=i+s*o,l={unit:e.subarray(t,t+n.frameLength),pts:a,dts:a};return r.config=[],r.channelCount=n.channelCount,r.samplerate=n.sampleRate,r.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function Ba(r,e){const t=r[e+1]>>3&3,i=r[e+1]>>1&3,s=r[e+2]>>4&15,n=r[e+2]>>2&3;if(t!==1&&s!==0&&s!==15&&n!==3){const o=r[e+2]>>1&1,a=r[e+3]>>6,l=t===3?3-i:i===3?3:4,c=ou[l*14+s-1]*1e3,h=au[(t===3?0:t===2?1:2)*3+n],u=a===3?1:2,f=lu[t][i],g=cu[i],p=f*8*g,m=Math.floor(f*c/h+o)*g;if(Ns===null){const b=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ns=b?parseInt(b[1]):0}return!!Ns&&Ns<=87&&i===2&&c>=224e3&&a===0&&(r[e+3]=r[e+3]|128),{sampleRate:h,channelCount:u,frameLength:m,samplesPerFrame:p}}}function $r(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function Ua(r,e){return e+1<r.length&&$r(r,e)}function du(r,e){return $r(r,e)&&4<=r.length-e}function hu(r,e){if(e+1<r.length&&$r(r,e)){const i=Ba(r,e);let s=4;i!=null&&i.frameLength&&(s=i.frameLength);const n=e+s;return n===r.length||Ua(r,n)}return!1}class Ha{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(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,s=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");s.set(e.subarray(i,i+n)),this.word=new DataView(s.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);const i=this.word>>>32-t;if(e>32&&C.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)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(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const 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)}skipScalingList(e){let t=8,i=8,s;for(let n=0;n<e;n++)i!==0&&(s=this.readEG(),i=(t+s+256)%256),t=i===0?t:i}readSPS(){let e=0,t=0,i=0,s=0,n,o,a;const l=this.readUByte.bind(this),c=this.readBits.bind(this),d=this.readUEG.bind(this),h=this.readBoolean.bind(this),u=this.skipBits.bind(this),f=this.skipEG.bind(this),g=this.skipUEG.bind(this),p=this.skipScalingList.bind(this);l();const m=l();if(c(5),u(3),l(),g(),m===100||m===110||m===122||m===244||m===44||m===83||m===86||m===118||m===128){const E=d();if(E===3&&u(1),g(),g(),u(1),h())for(o=E!==3?8:12,a=0;a<o;a++)h()&&(a<6?p(16):p(64))}g();const A=d();if(A===0)d();else if(A===1)for(u(1),f(),f(),n=d(),a=0;a<n;a++)f();g(),u(1);const T=d(),b=d(),y=c(1);y===0&&u(1),u(1),h()&&(e=d(),t=d(),i=d(),s=d());let x=[1,1];if(h()&&h())switch(l()){case 1:x=[1,1];break;case 2:x=[12,11];break;case 3:x=[10,11];break;case 4:x=[16,11];break;case 5:x=[40,33];break;case 6:x=[24,11];break;case 7:x=[20,11];break;case 8:x=[32,11];break;case 9:x=[80,33];break;case 10:x=[18,11];break;case 11:x=[15,11];break;case 12:x=[64,33];break;case 13:x=[160,99];break;case 14:x=[4,3];break;case 15:x=[3,2];break;case 16:x=[2,1];break;case 255:{x=[l()<<8|l(),l()<<8|l()];break}}return{width:Math.ceil((T+1)*16-e*2-t*2),height:(2-y)*(b+1)*16-(y?2:4)*(i+s),pixelRatio:x}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class uu{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Jr(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,i){const s=e[t].unit;if(s.length<=16)return;const n=s.subarray(16,s.length-s.length%16),o=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(o).then(a=>{const l=new Uint8Array(a);s.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,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){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let s=0;for(let n=32;n<e.length-16;n+=160,s+=16)i.set(e.subarray(n,n+16),s);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let s=0;for(let n=32;n<e.length-16;n+=160,s+=16)e.set(i.subarray(s,s+16),n);return e}decryptAvcSample(e,t,i,s,n){const o=Qo(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,s)})}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){s();return}const n=e[t].units;for(;!(i>=n.length);i++){const o=n[i];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,t,i,s,o),!this.decrypter.isSync()))return}}}}const Ne=188;class Bt{constructor(e,t,i){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=e,this.config=t,this.typeSupported=i}static probe(e){const t=Bt.syncOffset(e);return t>0&&C.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),t!==-1}static syncOffset(e){const t=e.length;let i=Math.min(Ne*5,e.length-Ne)+1,s=0;for(;s<i;){let n=!1,o=-1,a=0;for(let l=s;l<t;l+=Ne)if(e[l]===71){if(a++,o===-1&&(o=l,o!==0&&(i=Math.min(o+Ne*99,e.length-Ne)+1)),n||(n=en(e,l)===0),n&&a>1&&(o===0&&a>2||l+Ne>i))return o}else{if(a)return-1;break}s++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Wo[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,s){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=Bt.createTrack("video"),this._audioTrack=Bt.createTrack("audio",s),this._id3Track=Bt.createTrack("id3"),this._txtTrack=Bt.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,this._duration=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_avcTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}demux(e,t,i=!1,s=!1){i||(this.sampleAes=null);let n;const o=this._avcTrack,a=this._audioTrack,l=this._id3Track,c=this._txtTrack;let d=o.pid,h=o.pesData,u=a.pid,f=l.pid,g=a.pesData,p=l.pesData,m=null,A=this.pmtParsed,T=this._pmtId,b=e.length;if(this.remainderData&&(e=$t(this.remainderData,e),b=e.length,this.remainderData=null),b<Ne&&!s)return this.remainderData=e,{audioTrack:a,videoTrack:o,id3Track:l,textTrack:c};const y=Math.max(0,Bt.syncOffset(e));b-=(b-y)%Ne,b<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,b,e.buffer.byteLength-b));let x=0;for(let S=y;S<b;S+=Ne)if(e[S]===71){const R=!!(e[S+1]&64),w=en(e,S),I=(e[S+3]&48)>>4;let O;if(I>1){if(O=S+5+e[S+4],O===S+Ne)continue}else O=S+4;switch(w){case d:R&&(h&&(n=pi(h))&&this.parseAVCPES(o,c,n,!1),h={data:[],size:0}),h&&(h.data.push(e.subarray(O,S+Ne)),h.size+=S+Ne-O);break;case u:if(R){if(g&&(n=pi(g)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,n);break;case"mp3":this.parseMPEGPES(a,n);break}g={data:[],size:0}}g&&(g.data.push(e.subarray(O,S+Ne)),g.size+=S+Ne-O);break;case f:R&&(p&&(n=pi(p))&&this.parseID3PES(l,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(O,S+Ne)),p.size+=S+Ne-O);break;case 0:R&&(O+=e[O]+1),T=this._pmtId=fu(e,O);break;case T:{R&&(O+=e[O]+1);const P=gu(e,O,this.typeSupported,i);d=P.avc,d>0&&(o.pid=d),u=P.audio,u>0&&(a.pid=u,a.segmentCodec=P.segmentCodec),f=P.id3,f>0&&(l.pid=f),m!==null&&!A&&(C.warn(`MPEG-TS PMT found at ${S} after unknown PID '${m}'. Backtracking to sync byte @${y} to parse all TS packets.`),m=null,S=y-188),A=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=w;break}}else x++;if(x>0){const S=new Error(`Found ${x} TS packet/s that do not start with 0x47`);this.observer.emit(v.ERROR,v.ERROR,{type:q.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:S,reason:S.message})}o.pesData=h,a.pesData=g,l.pesData=p;const E={audioTrack:a,videoTrack:o,id3Track:l,textTrack:c};return s&&this.extractRemainingSamples(E),E}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._avcTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:s,textTrack:n}=e,o=i.pesData,a=t.pesData,l=s.pesData;let c;if(o&&(c=pi(o))?(this.parseAVCPES(i,n,c,!0),i.pesData=null):i.pesData=o,a&&(c=pi(a))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,c);break;case"mp3":this.parseMPEGPES(t,c);break}t.pesData=null}else a!=null&&a.size&&C.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;l&&(c=pi(l))?(this.parseID3PES(s,c),s.pesData=null):s.pesData=l}demuxSampleAes(e,t,i){const s=this.demux(e,i,!0,!this.config.progressive),n=this.sampleAes=new uu(this.observer,this.config,t);return this.decrypt(s,n)}decrypt(e,t){return new Promise(i=>{const{audioTrack:s,videoTrack:n}=e;s.samples&&s.segmentCodec==="aac"?t.decryptAacSamples(s.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._duration=0}parseAVCPES(e,t,i,s){const n=this.parseAVCNALu(e,i.data);let o=this.avcSample,a,l=!1;i.data=null,o&&n.length&&!e.audFound&&(tn(o,e),o=this.avcSample=Bs(!1,i.pts,i.dts,"")),n.forEach(c=>{switch(c.type){case 1:{a=!0,o||(o=this.avcSample=Bs(!0,i.pts,i.dts,"")),o.frame=!0;const d=c.data;if(l&&d.length>4){const h=new Ha(d).readSliceType();(h===2||h===4||h===7||h===9)&&(o.key=!0)}break}case 5:a=!0,o||(o=this.avcSample=Bs(!0,i.pts,i.dts,"")),o.key=!0,o.frame=!0;break;case 6:{a=!0,Jo(c.data,1,i.pts,t.samples);break}case 7:if(a=!0,l=!0,!e.sps){const d=c.data,u=new Ha(d).readSPS();e.width=u.width,e.height=u.height,e.pixelRatio=u.pixelRatio,e.sps=[d],e.duration=this._duration;const f=d.subarray(1,4);let g="avc1.";for(let p=0;p<3;p++){let m=f[p].toString(16);m.length<2&&(m="0"+m),g+=m}e.codec=g}break;case 8:a=!0,e.pps||(e.pps=[c.data]);break;case 9:a=!1,e.audFound=!0,o&&tn(o,e),o=this.avcSample=Bs(!1,i.pts,i.dts,"");break;case 12:a=!0;break;default:a=!1,o&&(o.debug+="unknown NAL "+c.type+" ");break}o&&a&&o.units.push(c)}),s&&o&&(tn(o,e),this.avcSample=null)}getLastNalUnit(e){var t;let i=this.avcSample,s;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const n=i.units;s=n[n.length-1]}return s}parseAVCNALu(e,t){const i=t.byteLength;let s=e.naluState||0;const n=s,o=[];let a=0,l,c,d,h=-1,u=0;for(s===-1&&(h=0,u=t[0]&31,s=0,a=1);a<i;){if(l=t[a++],!s){s=l?0:1;continue}if(s===1){s=l?0:2;continue}if(!l)s=3;else if(l===1){if(h>=0){const f={data:t.subarray(h,a-s-1),type:u};o.push(f)}else{const f=this.getLastNalUnit(e.samples);if(f&&(n&&a<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),c=a-s-1,c>0)){const g=new Uint8Array(f.data.byteLength+c);g.set(f.data,0),g.set(t.subarray(0,c),f.data.byteLength),f.data=g,f.state=0}}a<i?(d=t[a]&31,h=a,u=d,s=0):s=-1}else s=0}if(h>=0&&s>=0){const f={data:t.subarray(h,i),type:u,state:s};o.push(f)}if(o.length===0){const f=this.getLastNalUnit(e.samples);if(f){const g=new Uint8Array(f.data.byteLength+t.byteLength);g.set(f.data,0),g.set(t,f.data.byteLength),f.data=g}}return e.naluState=s,o}parseAACPES(e,t){let i=0;const s=this.aacOverFlow;let n=t.data;if(s){this.aacOverFlow=null;const h=s.missing,u=s.sample.unit.byteLength;if(h===-1){const f=new Uint8Array(u+n.byteLength);f.set(s.sample.unit,0),f.set(n,u),n=f}else{const f=u-h;s.sample.unit.set(n.subarray(0,h),f),e.samples.push(s.sample),i=s.missing}}let o,a;for(o=i,a=n.length;o<a-1&&!Fs(n,o);o++);if(o!==i){let h;const u=o<a-1;u?h=`AAC PES did not start with ADTS header,offset:${o}`:h="No ADTS header found in AAC PES";const f=new Error(h);if(C.warn(`parsing error: ${h}`),this.observer.emit(v.ERROR,v.ERROR,{type:q.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,levelRetry:u,error:f,reason:h}),!u)return}Oa(e,this.observer,n,o,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(s){const h=Ma(e.samplerate);l=s.sample.pts+h}else{C.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,d;for(;o<a;)if(d=Fa(e,n,o,l,c),o+=d.length,d.missing){this.aacOverFlow=d;break}else for(c++;o<a-1&&!Fs(n,o);o++);}parseMPEGPES(e,t){const i=t.data,s=i.length;let n=0,o=0;const a=t.pts;if(a===void 0){C.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;o<s;)if(Ua(i,o)){const l=Na(e,i,o,a,n);if(l)o+=l.length,n++;else break}else o++}parseID3PES(e,t){if(t.pts===void 0){C.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=Ce({},t,{type:this._avcTrack?lt.emsg:lt.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Bs(r,e,t,i){return{key:r,frame:!1,pts:e,dts:t,units:[],debug:i,length:0}}function en(r,e){return((r[e+1]&31)<<8)+r[e+2]}function fu(r,e){return(r[e+10]&31)<<8|r[e+11]}function gu(r,e,t,i){const s={audio:-1,avc:-1,id3:-1,segmentCodec:"aac"},n=(r[e+1]&15)<<8|r[e+2],o=e+3+n-4,a=(r[e+10]&15)<<8|r[e+11];for(e+=12+a;e<o;){const l=en(r,e);switch(r[e]){case 207:if(!i){C.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:s.audio===-1&&(s.audio=l);break;case 21:s.id3===-1&&(s.id3=l);break;case 219:if(!i){C.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:s.avc===-1&&(s.avc=l);break;case 3:case 4:t.mpeg!==!0&&t.mp3!==!0?C.log("MPEG audio found, not supported in this browser"):s.audio===-1&&(s.audio=l,s.segmentCodec="mp3");break;case 36:C.warn("Unsupported HEVC stream type found");break}e+=((r[e+3]&15)<<8|r[e+4])+5}return s}function pi(r){let e=0,t,i,s,n,o;const a=r.data;if(!r||r.size===0)return null;for(;a[0].length<19&&a.length>1;){const c=new Uint8Array(a[0].length+a[1].length);c.set(a[0]),c.set(a[1],a[0].length),a[0]=c,a.splice(1,1)}if(t=a[0],(t[0]<<16)+(t[1]<<8)+t[2]===1){if(i=(t[4]<<8)+t[5],i&&i>r.size-6)return null;const c=t[7];c&192&&(n=(t[9]&14)*536870912+(t[10]&255)*4194304+(t[11]&254)*16384+(t[12]&255)*128+(t[13]&254)/2,c&64?(o=(t[14]&14)*536870912+(t[15]&255)*4194304+(t[16]&254)*16384+(t[17]&255)*128+(t[18]&254)/2,n-o>54e5&&(C.warn(`${Math.round((n-o)/9e4)}s delta between PTS and DTS, align them`),n=o)):o=n),s=t[8];let d=s+9;if(r.size<=d)return null;r.size-=d;const h=new Uint8Array(r.size);for(let u=0,f=a.length;u<f;u++){t=a[u];let g=t.byteLength;if(d)if(d>g){d-=g;continue}else t=t.subarray(d),g-=d,d=0;h.set(t,e),e+=g}return i&&(i-=s+3),{data:h,pts:n,dts:o,len:i}}return null}function tn(r,e){if(r.units.length&&r.frame){if(r.pts===void 0){const t=e.samples,i=t.length;if(i){const s=t[i-1];r.pts=s.pts,r.dts=s.dts}else{e.dropped++;return}}e.samples.push(r)}r.debug.length&&C.log(r.pts+"/"+r.dts+":"+r.debug)}class pu extends Da{resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let i=(Ss(e,0)||[]).length;for(let s=e.length;i<s;i++)if(hu(e,i))return C.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return du(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return Na(e,t,i,this.basePTS,this.frameIndex)}}class Ga{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}}}const Ut=Math.pow(2,32)-1;class L{static init(){L.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in L.types)L.types.hasOwnProperty(e)&&(L.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const 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]);L.HDLR_TYPES={video:t,audio:i};const s=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]);L.STTS=L.STSC=L.STCO=n,L.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),L.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),L.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),L.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const o=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);L.FTYP=L.box(L.types.ftyp,o,l,o,a),L.DINF=L.box(L.types.dinf,L.box(L.types.dref,s))}static box(e,...t){let i=8,s=t.length;const n=s;for(;s--;)i+=t[s].byteLength;const 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),s=0,i=8;s<n;s++)o.set(t[s],i),i+=t[s].byteLength;return o}static hdlr(e){return L.box(L.types.hdlr,L.HDLR_TYPES[e])}static mdat(e){return L.box(L.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(Ut+1)),s=Math.floor(t%(Ut+1));return L.box(L.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,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(e){return L.box(L.types.mdia,L.mdhd(e.timescale,e.duration),L.hdlr(e.type),L.minf(e))}static mfhd(e){return L.box(L.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"?L.box(L.types.minf,L.box(L.types.smhd,L.SMHD),L.DINF,L.stbl(e)):L.box(L.types.minf,L.box(L.types.vmhd,L.VMHD),L.DINF,L.stbl(e))}static moof(e,t,i){return L.box(L.types.moof,L.mfhd(e),L.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=L.trak(e[t]);return L.box.apply(null,[L.types.moov,L.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(L.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=L.trex(e[t]);return L.box.apply(null,[L.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(Ut+1)),s=Math.floor(t%(Ut+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,s>>24,s>>16&255,s>>8&255,s&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 L.box(L.types.mvhd,n)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let s,n;for(s=0;s<t.length;s++)n=t[s].flags,i[s+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return L.box(L.types.sdtp,i)}static stbl(e){return L.box(L.types.stbl,L.stsd(e),L.box(L.types.stts,L.STTS),L.box(L.types.stsc,L.STSC),L.box(L.types.stsz,L.STSZ),L.box(L.types.stco,L.STCO))}static avc1(e){let t=[],i=[],s,n,o;for(s=0;s<e.sps.length;s++)n=e.sps[s],o=n.byteLength,t.push(o>>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(n));for(s=0;s<e.pps.length;s++)n=e.pps[s],o=n.byteLength,i.push(o>>>8&255),i.push(o&255),i=i.concat(Array.prototype.slice.call(n));const a=L.box(L.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,c=e.height,d=e.pixelRatio[0],h=e.pixelRatio[1];return L.box(L.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,c>>8&255,c&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,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static mp4a(e){const t=e.samplerate;return L.box(L.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0]),L.box(L.types.esds,L.esds(e)))}static mp3(e){const t=e.samplerate;return L.box(L.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0]))}static stsd(e){return e.type==="audio"?e.segmentCodec==="mp3"&&e.codec==="mp3"?L.box(L.types.stsd,L.STSD,L.mp3(e)):L.box(L.types.stsd,L.STSD,L.mp4a(e)):L.box(L.types.stsd,L.STSD,L.avc1(e))}static tkhd(e){const t=e.id,i=e.duration*e.timescale,s=e.width,n=e.height,o=Math.floor(i/(Ut+1)),a=Math.floor(i%(Ut+1));return L.box(L.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,s>>8&255,s&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){const i=L.sdtp(e),s=e.id,n=Math.floor(t/(Ut+1)),o=Math.floor(t%(Ut+1));return L.box(L.types.traf,L.box(L.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),L.box(L.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])),L.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,L.box(L.types.trak,L.tkhd(e),L.mdia(e))}static trex(e){const t=e.id;return L.box(L.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){const i=e.samples||[],s=i.length,n=12+16*s,o=new Uint8Array(n);let a,l,c,d,h,u;for(t+=8+n,o.set([e.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),a=0;a<s;a++)l=i[a],c=l.duration,d=l.size,h=l.flags,u=l.cts,o.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,d>>>24&255,d>>>16&255,d>>>8&255,d&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,u>>>24&255,u>>>16&255,u>>>8&255,u&255],12+16*a);return L.box(L.types.trun,o)}static initSegment(e){L.types||L.init();const t=L.moov(e),i=new Uint8Array(L.FTYP.byteLength+t.byteLength);return i.set(L.FTYP),i.set(t,L.FTYP.byteLength),i}}L.types=void 0,L.HDLR_TYPES=void 0,L.STTS=void 0,L.STSC=void 0,L.STCO=void 0,L.STSZ=void 0,L.VMHD=void 0,L.SMHD=void 0,L.STSD=void 0,L.FTYP=void 0,L.DINF=void 0;const Va=9e4;function sn(r,e,t=1,i=!1){const s=r*e*t;return i?Math.round(s):s}function mu(r,e,t=1,i=!1){return sn(r,e,1/t,i)}function _i(r,e=!1){return sn(r,1e3,1/Va,e)}function vu(r,e=1){return sn(r,Va,1/e)}const yu=10*1e3,ja=1024,Au=1152;let Us=null,rn=null;class nn{constructor(e,t,i,s=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,Us===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Us=o?parseInt(o[1]):0}if(rn===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);rn=n?parseInt(n[1]):0}}destroy(){}resetTimeStamp(e){C.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){C.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){C.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1}getVideoStartPts(e){let t=!1;const i=e.reduce((s,n)=>{const o=n.pts-s;return o<-4294967296?(t=!0,$e(s,n.pts)):o>0?s:n.pts},e[0].pts);return t&&C.debug("PTS rollover detected"),i}remux(e,t,i,s,n,o,a,l){let c,d,h,u,f,g,p=n,m=n;const A=e.pid>-1,T=t.pid>-1,b=t.samples.length,y=e.samples.length>0,x=a&&b>0||b>1;if((!A||y)&&(!T||x)||this.ISGenerated||a){this.ISGenerated||(h=this.generateIS(e,t,n,o));const S=this.isVideoContiguous;let R=-1,w;if(x&&(R=bu(t.samples),!S&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,R>0){C.warn(`[mp4-remuxer]: Dropped ${R} out of ${b} video samples due to a missing keyframe`);const I=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(R),t.dropped+=R,m+=(t.samples[0].pts-I)/t.inputTimeScale,w=m}else R===-1&&(C.warn(`[mp4-remuxer]: No keyframe found out of ${b} video samples`),g=!1);if(this.ISGenerated){if(y&&x){const I=this.getVideoStartPts(t.samples),P=($e(e.samples[0].pts,I)-I)/t.inputTimeScale;p+=Math.max(0,P),m+=Math.max(0,-P)}if(y){if(e.samplerate||(C.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),h=this.generateIS(e,t,n,o)),d=this.remuxAudio(e,p,this.isAudioContiguous,o,T||x||l===Z.AUDIO?m:void 0),x){const I=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(C.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),h=this.generateIS(e,t,n,o)),c=this.remuxVideo(t,m,S,I)}}else x&&(c=this.remuxVideo(t,m,S,0));c&&(c.firstKeyFrame=R,c.independent=R!==-1,c.firstKeyFramePTS=w)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=za(i,n,this._initPTS,this._initDTS)),s.samples.length&&(u=Wa(s,n,this._initPTS))),{audio:d,video:c,initSegment:h,independent:g,text:u,id3:f}}generateIS(e,t,i,s){const n=e.samples,o=t.samples,a=this.typeSupported,l={},c=this._initPTS;let d=!c||s,h="audio/mp4",u,f,g;if(d&&(u=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(h="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break}l.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):L.initSegment([e]),metadata:{channelCount:e.channelCount}},d&&(g=e.inputTimeScale,!c||g!==c.timescale?u=f=n[0].pts-Math.round(g*i):d=!1)}if(t.sps&&t.pps&&o.length&&(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:L.initSegment([t]),metadata:{width:t.width,height:t.height}},d))if(g=t.inputTimeScale,!c||g!==c.timescale){const p=this.getVideoStartPts(o),m=Math.round(g*i);f=Math.min(f,$e(o[0].dts,p)-m),u=Math.min(u,p-m)}else d=!1;if(Object.keys(l).length)return this.ISGenerated=!0,d?(this._initPTS={baseTime:u,timescale:g},this._initDTS={baseTime:f,timescale:g}):u=g=void 0,{tracks:l,initPTS:u,timescale:g}}remuxVideo(e,t,i,s){const n=e.inputTimeScale,o=e.samples,a=[],l=o.length,c=this._initPTS;let d=this.nextAvcDts,h=8,u=this.videoSampleDuration,f,g,p=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,A=!1;if(!i||d===null){const F=t*n,U=o[0].pts-$e(o[0].dts,o[0].pts);d=F-U}const T=c.baseTime*n/c.timescale;for(let F=0;F<l;F++){const U=o[F];U.pts=$e(U.pts-T,d),U.dts=$e(U.dts-T,d),U.dts<o[F>0?F-1:F].dts&&(A=!0)}A&&o.sort(function(F,U){const Q=F.dts-U.dts,Y=F.pts-U.pts;return Q||Y}),f=o[0].dts,g=o[o.length-1].dts;const b=g-f,y=b?Math.round(b/(l-1)):u||e.inputTimeScale/30;if(i){const F=f-d,U=F>y,Q=F<-1;if((U||Q)&&(U?C.warn(`AVC: ${_i(F,!0)} ms (${F}dts) hole between fragments detected, filling it`):C.warn(`AVC: ${_i(-F,!0)} ms (${F}dts) overlapping between fragments detected`),!Q||d>=o[0].pts)){f=d;const Y=o[0].pts-F;o[0].dts=f,o[0].pts=Y,C.log(`Video: First PTS/DTS adjusted: ${_i(Y,!0)}/${_i(f,!0)}, delta: ${_i(F,!0)} ms`)}}f=Math.max(0,f);let x=0,E=0;for(let F=0;F<l;F++){const U=o[F],Q=U.units,Y=Q.length;let z=0;for(let K=0;K<Y;K++)z+=Q[K].data.length;E+=z,x+=Y,U.length=z,U.dts=Math.max(U.dts,f),p=Math.min(U.pts,p),m=Math.max(U.pts,m)}g=o[l-1].dts;const S=E+4*x+8;let R;try{R=new Uint8Array(S)}catch(F){this.observer.emit(v.ERROR,v.ERROR,{type:q.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,error:F,bytes:S,reason:`fail allocating video mdat ${S}`});return}const w=new DataView(R.buffer);w.setUint32(0,S),R.set(L.types.mdat,4);let I=!1,O=Number.POSITIVE_INFINITY,P=Number.POSITIVE_INFINITY,B=Number.NEGATIVE_INFINITY,J=Number.NEGATIVE_INFINITY;for(let F=0;F<l;F++){const U=o[F],Q=U.units;let Y=0;for(let X=0,ie=Q.length;X<ie;X++){const ee=Q[X],ne=ee.data,se=ee.data.byteLength;w.setUint32(h,se),h+=4,R.set(ne,h),h+=se,Y+=4+se}let z;if(F<l-1)u=o[F+1].dts-U.dts,z=o[F+1].pts-U.pts;else{const X=this.config,ie=F>0?U.dts-o[F-1].dts:y;if(z=F>0?U.pts-o[F-1].pts:y,X.stretchShortVideoTrack&&this.nextAudioPts!==null){const ee=Math.floor(X.maxBufferHole*n),ne=(s?p+s*n:this.nextAudioPts)-U.pts;ne>ee?(u=ne-ie,u<0?u=ie:I=!0,C.log(`[mp4-remuxer]: It is approximately ${ne/90} ms to the next segment; using duration ${u/90} ms for the last video frame.`)):u=ie}else u=ie}const K=Math.round(U.pts-U.dts);O=Math.min(O,u),B=Math.max(B,u),P=Math.min(P,z),J=Math.max(J,z),a.push(new Ya(U.key,u,Y,K))}if(a.length){if(Us){if(Us<70){const F=a[0].flags;F.dependsOn=2,F.isNonSync=0}}else if(rn&&J-P<B-O&&y/B<.025&&a[0].cts===0){C.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let F=f;for(let U=0,Q=a.length;U<Q;U++){const Y=F+a[U].duration,z=F+a[U].cts;if(U<Q-1){const K=Y+a[U+1].cts;a[U].duration=K-z}else a[U].duration=U?a[U-1].duration:y;a[U].cts=0,F=Y}}}u=I||!u?y:u,this.nextAvcDts=d=g+u,this.videoSampleDuration=u,this.isVideoContiguous=!0;const H=L.moof(e.sequenceNumber++,f,Ce({},e,{samples:a})),V="video",j={data1:H,data2:R,startPTS:p/n,endPTS:(m+u)/n,startDTS:f/n,endDTS:d/n,type:V,hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,j}remuxAudio(e,t,i,s,n){const o=e.inputTimeScale,a=e.samplerate?e.samplerate:o,l=o/a,c=e.segmentCodec==="aac"?ja:Au,d=c*l,h=this._initPTS,u=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=n!==void 0;let p=e.samples,m=u?0:8,A=this.nextAudioPts||-1;const T=t*o,b=h.baseTime*o/h.timescale;if(this.isAudioContiguous=i=i||p.length&&A>0&&(s&&Math.abs(T-A)<9e3||Math.abs($e(p[0].pts-b,T)-A)<20*d),p.forEach(function(V){V.pts=$e(V.pts-b,T)}),!i||A<0){if(p=p.filter(V=>V.pts>=0),!p.length)return;n===0?A=0:s&&!g?A=Math.max(0,T):A=p[0].pts}if(e.segmentCodec==="aac"){const V=this.config.maxAudioFramesDrift;for(let j=0,F=A;j<p.length;j++){const U=p[j],Q=U.pts,Y=Q-F,z=Math.abs(1e3*Y/o);if(Y<=-V*d&&g)j===0&&(C.warn(`Audio frame @ ${(Q/o).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*Y/o)} ms.`),this.nextAudioPts=A=F=Q);else if(Y>=V*d&&z<yu&&g){let K=Math.round(Y/d);F=Q-K*d,F<0&&(K--,F+=d),j===0&&(this.nextAudioPts=A=F),C.warn(`[mp4-remuxer]: Injecting ${K} audio frame @ ${(F/o).toFixed(3)}s due to ${Math.round(1e3*Y/o)} ms gap.`);for(let X=0;X<K;X++){const ie=Math.max(F,0);let ee=Ga.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);ee||(C.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),ee=U.unit.subarray()),p.splice(j,0,{unit:ee,pts:ie}),F+=d,j++}}U.pts=F,F+=d}}let y=null,x=null,E,S=0,R=p.length;for(;R--;)S+=p[R].unit.byteLength;for(let V=0,j=p.length;V<j;V++){const F=p[V],U=F.unit;let Q=F.pts;if(x!==null){const z=f[V-1];z.duration=Math.round((Q-x)/l)}else if(i&&e.segmentCodec==="aac"&&(Q=A),y=Q,S>0){S+=m;try{E=new Uint8Array(S)}catch(z){this.observer.emit(v.ERROR,v.ERROR,{type:q.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,error:z,bytes:S,reason:`fail allocating audio mdat ${S}`});return}u||(new DataView(E.buffer).setUint32(0,S),E.set(L.types.mdat,4))}else return;E.set(U,m);const Y=U.byteLength;m+=Y,f.push(new Ya(!0,c,Y,0)),x=Q}const w=f.length;if(!w)return;const I=f[f.length-1];this.nextAudioPts=A=x+l*I.duration;const O=u?new Uint8Array(0):L.moof(e.sequenceNumber++,y/l,Ce({},e,{samples:f}));e.samples=[];const P=y/o,B=A/o,H={data1:O,data2:E,startPTS:P,endPTS:B,startDTS:P,endDTS:B,type:"audio",hasAudio:!0,hasVideo:!1,nb:w};return this.isAudioContiguous=!0,H}remuxEmptyAudio(e,t,i,s){const n=e.inputTimeScale,o=e.samplerate?e.samplerate:n,a=n/o,l=this.nextAudioPts,c=this._initDTS,d=c.baseTime*9e4/c.timescale,h=(l!==null?l:s.startDTS*n)+d,u=s.endDTS*n+d,f=a*ja,g=Math.ceil((u-h)/f),p=Ga.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(C.warn("[mp4-remuxer]: remux empty Audio"),!p){C.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const m=[];for(let A=0;A<g;A++){const T=h+A*f;m.push({unit:p,pts:T,dts:T})}return e.samples=m,this.remuxAudio(e,t,i,!1)}}function $e(r,e){let t;if(e===null)return r;for(e<r?t=-8589934592:t=8589934592;Math.abs(r-e)>4294967296;)r+=t;return r}function bu(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function za(r,e,t,i){const s=r.samples.length;if(!s)return;const n=r.inputTimeScale;for(let a=0;a<s;a++){const l=r.samples[a];l.pts=$e(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=$e(l.dts-i.baseTime*n/i.timescale,e*n)/n}const o=r.samples;return r.samples=[],{samples:o}}function Wa(r,e,t){const i=r.samples.length;if(!i)return;const s=r.inputTimeScale;for(let o=0;o<i;o++){const a=r.samples[o];a.pts=$e(a.pts-t.baseTime*9e4/t.timescale,e*s)/s}r.samples.sort((o,a)=>o.pts-a.pts);const n=r.samples;return r.samples=[],{samples:n}}class Ya{constructor(e,t,i,s){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=i,this.cts=s,this.flags=new xu(e)}}class xu{constructor(e){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=e?2:1,this.isNonSync=e?0:1}}class Tu{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(jd(e,s)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const s=this.initData=Xo(e);t||(t=Ka(s.audio,de.AUDIO)),i||(i=Ka(s.video,de.VIDEO));const n={};s.audio&&s.video?n.audiovideo={container:"video/mp4",codec:t+","+i,initSegment:e,id:"main"}:s.audio?n.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:s.video?n.video={container:"video/mp4",codec:i,initSegment:e,id:"main"}:C.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(e,t,i,s,n,o){var a,l;let{initPTS:c,lastEndTime:d}=this;const h={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};W(d)||(d=this.lastEndTime=n||0);const u=t.samples;if(!(u!=null&&u.length))return h;const f={initPTS:void 0,timescale:1};let g=this.initData;if((a=g)!=null&&a.length||(this.generateInitSegment(u),g=this.initData),!((l=g)!=null&&l.length))return C.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),h;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const p=Wd(u,g),m=zd(g,u),A=m===null?n:m;(Eu(c,A,n,p)||f.timescale!==c.timescale&&o)&&(f.initPTS=A-n,c&&c.timescale===1&&C.warn(`Adjusting initPTS by ${f.initPTS-c.baseTime}`),this.initPTS=c={baseTime:f.initPTS,timescale:1});const T=e?A-c.baseTime/c.timescale:d,b=T+p;Kd(g,u,c.baseTime/c.timescale),p>0?this.lastEndTime=b:(C.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const y=!!g.audio,x=!!g.video;let E="";y&&(E+="audio"),x&&(E+="video");const S={data1:u,startPTS:T,startDTS:T,endPTS:b,endDTS:b,type:E,hasAudio:y,hasVideo:x,nb:1,dropped:0};return h.audio=S.type==="audio"?S:void 0,h.video=S.type!=="audio"?S:void 0,h.initSegment=f,h.id3=za(i,n,c,c),s.samples.length&&(h.text=Wa(s,n,c)),h}}function Eu(r,e,t,i){if(r===null)return!0;const s=Math.max(i,1),n=e-r.baseTime/r.timescale;return Math.abs(n-t)>s}function Ka(r,e){const t=r==null?void 0:r.codec;return t&&t.length>4?t:t==="hvc1"||t==="hev1"?"hvc1.1.6.L120.90":t==="av01"?"av01.0.04M.08":t==="avc1"||e===de.VIDEO?"avc1.42e01e":"mp4a.40.5"}let Lt;try{Lt=self.performance.now.bind(self.performance)}catch{C.debug("Unable to use Performance API on this environment"),Lt=typeof self<"u"&&self.Date.now}const on=[{demux:nu,remux:Tu},{demux:Bt,remux:nn},{demux:su,remux:nn},{demux:pu,remux:nn}];class Xa{constructor(e,t,i,s,n){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=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.vendor=s,this.id=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){const n=i.transmuxing;n.executeStart=Lt();let o=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:l}=this;s&&(this.currentTransmuxState=s);const{contiguous:c,discontinuity:d,trackSwitch:h,accurateTimeOffset:u,timeOffset:f,initSegmentChange:g}=s||a,{audioCodec:p,videoCodec:m,defaultInitPts:A,duration:T,initSegmentData:b}=l,y=Su(o,t);if(y&&y.method==="AES-128"){const R=this.getDecrypter();if(R.isSync()){let w=R.softwareDecrypt(o,y.key.buffer,y.iv.buffer);if(i.part>-1&&(w=R.flush()),!w)return n.executeEnd=Lt(),an(i);o=new Uint8Array(w)}else return this.decryptionPromise=R.webCryptoDecrypt(o,y.key.buffer,y.iv.buffer).then(w=>{const I=this.push(w,null,i);return this.decryptionPromise=null,I}),this.decryptionPromise}const x=this.needsProbing(d,h);if(x){const R=this.configureTransmuxer(o);if(R)return C.warn(`[transmuxer] ${R.message}`),this.observer.emit(v.ERROR,v.ERROR,{type:q.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message}),n.executeEnd=Lt(),an(i)}(d||h||g||x)&&this.resetInitSegment(b,p,m,T,t),(d||g||x)&&this.resetInitialTimestamp(A),c||this.resetContiguity();const E=this.transmux(o,y,f,u,i),S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,n.executeEnd=Lt(),E}flush(e){const t=e.transmuxing;t.executeStart=Lt();const{decrypter:i,currentTransmuxState:s,decryptionPromise:n}=this;if(n)return n.then(()=>this.flush(e));const o=[],{timeOffset:a}=s;if(i){const h=i.flush();h&&o.push(this.push(h,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c)return t.executeEnd=Lt(),[an(e)];const d=l.flush(a);return Hs(d)?d.then(h=>(this.flushRemux(o,h,e),o)):(this.flushRemux(o,d,e),o)}flushRemux(e,t,i){const{audioTrack:s,videoTrack:n,id3Track:o,textTrack:a}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;C.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const d=this.remuxer.remux(s,n,o,a,c,l,!0,this.id);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=Lt()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,s,n){const{demuxer:o,remuxer:a}=this;!o||!a||(o.resetInitSegment(e,t,i,s),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,s,n){let o;return t&&t.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,t,i,s,n):o=this.transmuxUnencrypted(e,i,s,n),o}transmuxUnencrypted(e,t,i,s){const{audioTrack:n,videoTrack:o,id3Track:a,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,o,a,l,t,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,i,s,n){return this.demuxer.demuxSampleAes(e,t,i).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,i,s,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:s,vendor:n}=this;let o;for(let h=0,u=on.length;h<u;h++)if(on[h].demux.probe(e)){o=on[h];break}if(!o)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,l=this.remuxer,c=o.remux,d=o.demux;(!l||!(l instanceof c))&&(this.remuxer=new c(i,t,s,n)),(!a||!(a instanceof d))&&(this.demuxer=new d(i,t,s),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Jr(this.config)),e}}function Su(r,e){let t=null;return r.byteLength>0&&e!=null&&e.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const an=r=>({remuxResult:{},chunkMeta:r});function Hs(r){return"then"in r&&r.then instanceof Function}class Iu{constructor(e,t,i,s,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=s,this.defaultInitPts=n||null}}class Cu{constructor(e,t,i,s,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=s,this.timeOffset=n,this.initSegmentChange=o}}var qa={exports:{}};(function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(l,c,d){this.fn=l,this.context=c,this.once=d||!1}function n(l,c,d,h,u){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new s(d,h||l,u),g=t?t+c:c;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],d,h;if(this._eventsCount===0)return c;for(h in d=this._events)e.call(d,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},a.prototype.listeners=function(c){var d=t?t+c:c,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var u=0,f=h.length,g=new Array(f);u<f;u++)g[u]=h[u].fn;return g},a.prototype.listenerCount=function(c){var d=t?t+c:c,h=this._events[d];return h?h.fn?1:h.length:0},a.prototype.emit=function(c,d,h,u,f,g){var p=t?t+c:c;if(!this._events[p])return!1;var m=this._events[p],A=arguments.length,T,b;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),A){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,d),!0;case 3:return m.fn.call(m.context,d,h),!0;case 4:return m.fn.call(m.context,d,h,u),!0;case 5:return m.fn.call(m.context,d,h,u,f),!0;case 6:return m.fn.call(m.context,d,h,u,f,g),!0}for(b=1,T=new Array(A-1);b<A;b++)T[b-1]=arguments[b];m.fn.apply(m.context,T)}else{var y=m.length,x;for(b=0;b<y;b++)switch(m[b].once&&this.removeListener(c,m[b].fn,void 0,!0),A){case 1:m[b].fn.call(m[b].context);break;case 2:m[b].fn.call(m[b].context,d);break;case 3:m[b].fn.call(m[b].context,d,h);break;case 4:m[b].fn.call(m[b].context,d,h,u);break;default:if(!T)for(x=1,T=new Array(A-1);x<A;x++)T[x-1]=arguments[x];m[b].fn.apply(m[b].context,T)}}return!0},a.prototype.on=function(c,d,h){return n(this,c,d,h,!1)},a.prototype.once=function(c,d,h){return n(this,c,d,h,!0)},a.prototype.removeListener=function(c,d,h,u){var f=t?t+c:c;if(!this._events[f])return this;if(!d)return o(this,f),this;var g=this._events[f];if(g.fn)g.fn===d&&(!u||g.once)&&(!h||g.context===h)&&o(this,f);else{for(var p=0,m=[],A=g.length;p<A;p++)(g[p].fn!==d||u&&!g[p].once||h&&g[p].context!==h)&&m.push(g[p]);m.length?this._events[f]=m.length===1?m[0]:m:o(this,f)}return this},a.prototype.removeAllListeners=function(c){var d;return c?(d=t?t+c:c,this._events[d]&&o(this,d)):(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,r.exports=a})(qa);var wu=qa.exports,ln=ud(wu);const cn=Ls()||{isTypeSupported:()=>!1};class Za{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const o=(c,d)=>{d=d||{},d.frag=this.frag,d.id=this.id,c===v.ERROR&&(this.error=d.error),this.hls.trigger(c,d)};this.observer=new ln,this.observer.on(v.FRAG_DECRYPTED,o),this.observer.on(v.ERROR,o);const a={mp4:cn.isTypeSupported("video/mp4"),mpeg:cn.isTypeSupported("audio/mpeg"),mp3:cn.isTypeSupported('audio/mp4; codecs="mp3"')},l=navigator.vendor;if(this.useWorker&&typeof Worker<"u"&&(n.workerPath||qh())){try{n.workerPath?(C.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=Jh(n.workerPath)):(C.log(`injecting Web Worker for "${t}"`),this.workerContext=Zh()),this.onwmsg=h=>this.onWorkerMessage(h);const{worker:d}=this.workerContext;d.addEventListener("message",this.onwmsg),d.onerror=h=>{const u=new Error(`${h.message} (${h.filename}:${h.lineno})`);n.enableWorker=!1,C.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(v.ERROR,{type:q.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:u})},d.postMessage({cmd:"init",typeSupported:a,vendor:l,id:t,config:JSON.stringify(n)})}catch(d){C.warn(`Error setting up "${t}" Web Worker, fallback to inline`,d),this.resetWorker(),this.error=null,this.transmuxer=new Xa(this.observer,a,n,l,t)}return}this.transmuxer=new Xa(this.observer,a,n,l,t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,i,s,n,o,a,l,c,d){var h,u;c.transmuxing.start=self.performance.now();const{transmuxer:f}=this,g=o?o.start:n.start,p=n.decryptdata,m=this.frag,A=!(m&&n.cc===m.cc),T=!(m&&c.level===m.level),b=m?c.sn-m.sn:-1,y=this.part?c.part-this.part.index:-1,x=b===0&&c.id>1&&c.id===(m==null?void 0:m.stats.chunkCount),E=!T&&(b===1||b===0&&(y===1||x&&y<=0)),S=self.performance.now();(T||b||n.stats.parsing.start===0)&&(n.stats.parsing.start=S),o&&(y||!E)&&(o.stats.parsing.start=S);const R=!(m&&((h=n.initSegment)==null?void 0:h.url)===((u=m.initSegment)==null?void 0:u.url)),w=new Cu(A,E,l,T,g,R);if(!E||A||R){C.log(`[transmuxer-interface, ${n.type}]: Starting new transmux session for sn: ${c.sn} p: ${c.part} level: ${c.level} id: ${c.id}
66
+ */const hd=Symbol();class Cr{constructor(e,t,i){this.i=0,this.status=0,this.autoRun=!0,this.o=e,this.o.addController(this);const s=typeof t=="object"?t:{task:t,args:i};this.t=s.task,this.h=s.args,this.l=s.onComplete,this.u=s.onError,s.autoRun!==void 0&&(this.autoRun=s.autoRun),this.taskComplete=new Promise((n,o)=>{this.v=n,this._=o})}hostUpdated(){this.performTask()}async performTask(){var e;const t=(e=this.h)===null||e===void 0?void 0:e.call(this);this.shouldRun(t)&&await this.run(t)}shouldRun(e){return this.autoRun&&this.k(e)}async run(e){var t,i,s;let n,o;e!=null||(e=(t=this.h)===null||t===void 0?void 0:t.call(this)),this.status!==2&&this.status!==3||(this.taskComplete=new Promise((l,c)=>{this.v=l,this._=c})),this.status=1,queueMicrotask(()=>this.o.requestUpdate());const a=++this.i;try{n=await this.t(e)}catch(l){o=l}if(this.i===a){if(n===hd)this.status=0;else{if(o===void 0){try{(i=this.l)===null||i===void 0||i.call(this,n)}catch{}this.status=2,this.v(n)}else{try{(s=this.u)===null||s===void 0||s.call(this,o)}catch{}this.status=3,this._(o)}this.m=n,this.T=o}this.o.requestUpdate()}}get value(){return this.m}get error(){return this.T}render(e){var t,i,s,n;switch(this.status){case 0:return(t=e.initial)===null||t===void 0?void 0:t.call(e);case 1:return(i=e.pending)===null||i===void 0?void 0:i.call(e);case 2:return(s=e.complete)===null||s===void 0?void 0:s.call(e,this.value);case 3:return(n=e.error)===null||n===void 0?void 0:n.call(e,this.error);default:this.status}}k(e){const t=this.p;return this.p=e,Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.some((i,s)=>pr(i,t[s])):e!==t}}function ud(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var ko={exports:{}};(function(r,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,o=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(l,c,d){if(d=d||{},l=l.trim(),c=c.trim(),!c){if(!d.alwaysNormalize)return l;var h=a.parseURL(l);if(!h)throw new Error("Error trying to parse base URL.");return h.path=a.normalizePath(h.path),a.buildURLFromParts(h)}var u=a.parseURL(c);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return d.alwaysNormalize?(u.path=a.normalizePath(u.path),a.buildURLFromParts(u)):c;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 g=s.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(p.netLoc=f.netLoc,u.path[0]!=="/"))if(!u.path)p.path=f.path,u.params||(p.params=f.params,u.query||(p.query=f.query));else{var m=f.path,A=m.substring(0,m.lastIndexOf("/")+1)+u.path;p.path=a.normalizePath(A)}return p.path===null&&(p.path=d.alwaysNormalize?a.normalizePath(u.path):u.path),a.buildURLFromParts(p)},parseURL:function(l){var c=i.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[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}};r.exports=a})()})(ko);var wr=ko.exports;function Po(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(r);e&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(r,s).enumerable})),t.push.apply(t,i)}return t}function je(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Po(Object(t),!0).forEach(function(i){fd(r,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Po(Object(t)).forEach(function(i){Object.defineProperty(r,i,Object.getOwnPropertyDescriptor(t,i))})}return r}function fd(r,e,t){return e=pd(e),e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function Ce(){return Ce=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(r[i]=t[i])}return r},Ce.apply(this,arguments)}function gd(r,e){if(typeof r!="object"||r===null)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var i=t.call(r,e||"default");if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function pd(r){var e=gd(r,"string");return typeof e=="symbol"?e:String(e)}const W=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)};let v=function(r){return r.MEDIA_ATTACHING="hlsMediaAttaching",r.MEDIA_ATTACHED="hlsMediaAttached",r.MEDIA_DETACHING="hlsMediaDetaching",r.MEDIA_DETACHED="hlsMediaDetached",r.BUFFER_RESET="hlsBufferReset",r.BUFFER_CODECS="hlsBufferCodecs",r.BUFFER_CREATED="hlsBufferCreated",r.BUFFER_APPENDING="hlsBufferAppending",r.BUFFER_APPENDED="hlsBufferAppended",r.BUFFER_EOS="hlsBufferEos",r.BUFFER_FLUSHING="hlsBufferFlushing",r.BUFFER_FLUSHED="hlsBufferFlushed",r.MANIFEST_LOADING="hlsManifestLoading",r.MANIFEST_LOADED="hlsManifestLoaded",r.MANIFEST_PARSED="hlsManifestParsed",r.LEVEL_SWITCHING="hlsLevelSwitching",r.LEVEL_SWITCHED="hlsLevelSwitched",r.LEVEL_LOADING="hlsLevelLoading",r.LEVEL_LOADED="hlsLevelLoaded",r.LEVEL_UPDATED="hlsLevelUpdated",r.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",r.LEVELS_UPDATED="hlsLevelsUpdated",r.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",r.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",r.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",r.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",r.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",r.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",r.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",r.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",r.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",r.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",r.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",r.CUES_PARSED="hlsCuesParsed",r.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",r.INIT_PTS_FOUND="hlsInitPtsFound",r.FRAG_LOADING="hlsFragLoading",r.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",r.FRAG_LOADED="hlsFragLoaded",r.FRAG_DECRYPTED="hlsFragDecrypted",r.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",r.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",r.FRAG_PARSING_METADATA="hlsFragParsingMetadata",r.FRAG_PARSED="hlsFragParsed",r.FRAG_BUFFERED="hlsFragBuffered",r.FRAG_CHANGED="hlsFragChanged",r.FPS_DROP="hlsFpsDrop",r.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",r.ERROR="hlsError",r.DESTROYING="hlsDestroying",r.KEY_LOADING="hlsKeyLoading",r.KEY_LOADED="hlsKeyLoaded",r.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",r.BACK_BUFFER_REACHED="hlsBackBufferReached",r}({}),q=function(r){return r.NETWORK_ERROR="networkError",r.MEDIA_ERROR="mediaError",r.KEY_SYSTEM_ERROR="keySystemError",r.MUX_ERROR="muxError",r.OTHER_ERROR="otherError",r}({}),D=function(r){return r.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",r.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",r.KEY_SYSTEM_NO_SESSION="keySystemNoSession",r.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",r.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",r.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",r.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",r.MANIFEST_LOAD_ERROR="manifestLoadError",r.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",r.MANIFEST_PARSING_ERROR="manifestParsingError",r.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",r.LEVEL_EMPTY_ERROR="levelEmptyError",r.LEVEL_LOAD_ERROR="levelLoadError",r.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",r.LEVEL_PARSING_ERROR="levelParsingError",r.LEVEL_SWITCH_ERROR="levelSwitchError",r.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",r.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",r.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",r.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",r.FRAG_LOAD_ERROR="fragLoadError",r.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",r.FRAG_DECRYPT_ERROR="fragDecryptError",r.FRAG_PARSING_ERROR="fragParsingError",r.FRAG_GAP="fragGap",r.REMUX_ALLOC_ERROR="remuxAllocError",r.KEY_LOAD_ERROR="keyLoadError",r.KEY_LOAD_TIMEOUT="keyLoadTimeOut",r.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",r.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",r.BUFFER_APPEND_ERROR="bufferAppendError",r.BUFFER_APPENDING_ERROR="bufferAppendingError",r.BUFFER_STALLED_ERROR="bufferStalledError",r.BUFFER_FULL_ERROR="bufferFullError",r.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",r.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",r.INTERNAL_EXCEPTION="internalException",r.INTERNAL_ABORTED="aborted",r.UNKNOWN="unknown",r}({});const Qt=function(){},Lr={trace:Qt,debug:Qt,log:Qt,warn:Qt,info:Qt,error:Qt};let Xi=Lr;function md(r){const e=self.console[r];return e?e.bind(self.console,`[${r}] >`):Qt}function vd(r,...e){e.forEach(function(t){Xi[t]=r[t]?r[t].bind(r):md(t)})}function yd(r,e){if(self.console&&r===!0||typeof r=="object"){vd(r,"debug","log","info","warn","error");try{Xi.log(`Debug logs enabled for "${e}" in hls.js version 1.4.6`)}catch{Xi=Lr}}else Xi=Lr}const C=Xi,Ad=/^(\d+)x(\d+)$/,Oo=/(.+?)=(".*?"|.*?)(?:,|$)/g;class me{constructor(e){typeof e=="string"&&(e=me.parseAttrList(e));for(const t in e)e.hasOwnProperty(t)&&(t.substring(0,2)==="X-"&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(t)),this[t]=e[t])}decimalInteger(e){const 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;const i=new Uint8Array(t.length/2);for(let s=0;s<t.length/2;s++)i[s]=parseInt(t.slice(s*2,s*2+2),16);return i}else return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}bool(e){return this[e]==="YES"}decimalResolution(e){const t=Ad.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const i={},s='"';for(Oo.lastIndex=0;(t=Oo.exec(e))!==null;){let n=t[2];n.indexOf(s)===0&&n.lastIndexOf(s)===n.length-1&&(n=n.slice(1,-1));const o=t[1].trim();i[o]=n}return i}}function bd(r){return r!=="ID"&&r!=="CLASS"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function xd(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"}class Mo{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const i=t.attr;for(const s in i)if(Object.prototype.hasOwnProperty.call(e,s)&&e[s]!==i[s]){C.warn(`DATERANGE tag attribute: "${s}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=s;break}e=Ce(new me({}),i,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const i=new Date(this.attr["END-DATE"]);W(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return e!==null?new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(W(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 isValid(){return!!this.id&&!this._badValueForSameId&&W(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class Es{constructor(){this.aborted=!1,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}}}var de={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Fo{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[de.AUDIO]:null,[de.VIDEO]:null,[de.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,t){const i=e.split("@",2),s=[];i.length===1?s[0]=t?t.byteRangeEndOffset:0:s[0]=parseInt(i[1]),s[1]=parseInt(i[0])+s[0],this._byteRange=s}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=wr.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class Rr extends Fo{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=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.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new Es,this.urlId=0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const i=Object.keys(this.levelkeys);if(i.length===1)return this._decryptdata=this.levelkeys[i[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!W(this.programDateTime))return null;const e=W(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),i=t.length;if(i>1||i===1&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,s,n,o=!1){const{elementaryStreams:a}=this,l=a[e];if(!l){a[e]={startPTS:t,endPTS:i,startDTS:s,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,s),l.endDTS=Math.max(l.endDTS,n)}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[de.AUDIO]=null,e[de.VIDEO]=null,e[de.AUDIOVIDEO]=null}}class Td extends Fo{constructor(e,t,i,s,n){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new Es,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=s;const 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(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}const Ed=10;class Sd{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,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.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,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=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,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=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t,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,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?W(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Ed}get drift(){const 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(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end: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 lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function Dr(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function Id(r){const e=No(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Cd(r){const e=function(i,s,n){const o=i[s];i[s]=i[n],i[n]=o};e(r,0,3),e(r,1,2),e(r,4,5),e(r,6,7)}function wd(r){const e=r.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),s=i[i.length-1].split(",");if(s.length===2){const n=s[0]==="base64",o=s[1];n?(i.splice(-1,1),t=Dr(o)):t=Id(o)}}return t}function No(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}var ve={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ze={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Bo(r){switch(r){case ze.FAIRPLAY:return ve.FAIRPLAY;case ze.PLAYREADY:return ve.PLAYREADY;case ze.WIDEVINE:return ve.WIDEVINE;case ze.CLEARKEY:return ve.CLEARKEY}}var Uo={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Ld(r){if(r===Uo.WIDEVINE)return ve.WIDEVINE}function Ho(r){switch(r){case ve.FAIRPLAY:return ze.FAIRPLAY;case ve.PLAYREADY:return ze.PLAYREADY;case ve.WIDEVINE:return ze.WIDEVINE;case ve.CLEARKEY:return ze.CLEARKEY}}function kr(r){const{drmSystems:e,widevineLicenseUrl:t}=r,i=e?[ve.FAIRPLAY,ve.WIDEVINE,ve.PLAYREADY,ve.CLEARKEY].filter(s=>!!e[s]):[];return!i[ve.WIDEVINE]&&t&&i.push(ve.WIDEVINE),i}const Go=function(){return typeof self<"u"&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Rd(r,e,t,i){let s;switch(r){case ve.FAIRPLAY:s=["cenc","sinf"];break;case ve.WIDEVINE:case ve.PLAYREADY:s=["cenc"];break;case ve.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return Dd(s,e,t,i)}function Dd(r,e,t,i){return[{initDataTypes:r,persistentState:i.persistentState||"not-allowed",distinctiveIdentifier:i.distinctiveIdentifier||"not-allowed",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 _t(r,e,t){return Uint8Array.prototype.slice?r.slice(e,t):new Uint8Array(Array.prototype.slice.call(r,e,t))}const Pr=(r,e)=>e+10<=r.length&&r[e]===73&&r[e+1]===68&&r[e+2]===51&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128,Vo=(r,e)=>e+10<=r.length&&r[e]===51&&r[e+1]===68&&r[e+2]===73&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128,Ss=(r,e)=>{const t=e;let i=0;for(;Pr(r,e);){i+=10;const s=Is(r,e+6);i+=s,Vo(r,e+10)&&(i+=10),e+=i}if(i>0)return r.subarray(t,t+i)},Is=(r,e)=>{let t=0;return t=(r[e]&127)<<21,t|=(r[e+1]&127)<<14,t|=(r[e+2]&127)<<7,t|=r[e+3]&127,t},kd=(r,e)=>Pr(r,e)&&Is(r,e+6)+10<=r.length-e,Pd=r=>{const e=zo(r);for(let t=0;t<e.length;t++){const i=e[t];if(jo(i))return Ud(i)}},jo=r=>r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp",Od=r=>{const e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=Is(r,4),i=10;return{type:e,size:t,data:r.subarray(i,i+t)}},zo=r=>{let e=0;const t=[];for(;Pr(r,e);){const i=Is(r,e+6);e+=10;const s=e+i;for(;e+8<s;){const n=Od(r.subarray(e)),o=Md(n);o&&t.push(o),e+=n.size+10}Vo(r,e)&&(e+=10)}return t},Md=r=>r.type==="PRIV"?Fd(r):r.type[0]==="W"?Bd(r):Nd(r),Fd=r=>{if(r.size<2)return;const e=ft(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}},Nd=r=>{if(r.size<2)return;if(r.type==="TXXX"){let t=1;const i=ft(r.data.subarray(t),!0);t+=i.length+1;const s=ft(r.data.subarray(t));return{key:r.type,info:i,data:s}}const e=ft(r.data.subarray(1));return{key:r.type,data:e}},Bd=r=>{if(r.type==="WXXX"){if(r.size<2)return;let t=1;const i=ft(r.data.subarray(t),!0);t+=i.length+1;const s=ft(r.data.subarray(t));return{key:r.type,info:i,data:s}}const e=ft(r.data);return{key:r.type,data:e}},Ud=r=>{if(r.data.byteLength===8){const e=new Uint8Array(r.data),t=e[3]&1;let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}},ft=(r,e=!1)=>{const t=Hd();if(t){const c=t.decode(r);if(e){const d=c.indexOf("\0");return d!==-1?c.substring(0,d):c}return c.replace(/\0/g,"")}const i=r.length;let s,n,o,a="",l=0;for(;l<i;){if(s=r[l++],s===0&&e)return a;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:n=r[l++],a+=String.fromCharCode((s&31)<<6|n&63);break;case 14:n=r[l++],o=r[l++],a+=String.fromCharCode((s&15)<<12|(n&63)<<6|(o&63)<<0);break}}return a};let Or;function Hd(){return!Or&&typeof self.TextDecoder<"u"&&(Or=new self.TextDecoder("utf-8")),Or}const gt={hexDump:function(r){let e="";for(let t=0;t<r.length;t++){let i=r[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}},Cs=Math.pow(2,32)-1,Gd=[].push,Wo={video:1,audio:2,id3:3,text:4};function De(r){return String.fromCharCode.apply(null,r)}function Yo(r,e){const t=r[e]<<8|r[e+1];return t<0?65536+t:t}function _(r,e){const t=Ko(r,e);return t<0?4294967296+t:t}function Ko(r,e){return r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}function Mr(r,e,t){r[e]=t>>24,r[e+1]=t>>16&255,r[e+2]=t>>8&255,r[e+3]=t&255}function re(r,e){const t=[];if(!e.length)return t;const i=r.byteLength;for(let s=0;s<i;){const n=_(r,s),o=De(r.subarray(s+4,s+8)),a=n>1?s+n:i;if(o===e[0])if(e.length===1)t.push(r.subarray(s+8,a));else{const l=re(r.subarray(s+8,a),e.slice(1));l.length&&Gd.apply(t,l)}s=a}return t}function Vd(r){const e=[],t=r[0];let i=8;const s=_(r,i);i+=4;const n=0,o=0;t===0?i+=8:i+=16,i+=2;let a=r.length+o;const l=Yo(r,i);i+=2;for(let c=0;c<l;c++){let d=i;const h=_(r,d);d+=4;const u=h&2147483647;if((h&2147483648)>>>31===1)return C.warn("SIDX has hierarchical references (not supported)"),null;const g=_(r,d);d+=4,e.push({referenceSize:u,subsegmentDuration:g,info:{duration:g/s,start:a,end:a+u-1}}),a+=u,d+=4,i=d}return{earliestPresentationTime:n,timescale:s,version:t,referencesCount:l,references:e}}function Xo(r){const e=[],t=re(r,["moov","trak"]);for(let s=0;s<t.length;s++){const n=t[s],o=re(n,["tkhd"])[0];if(o){let a=o[0],l=a===0?12:20;const c=_(o,l),d=re(n,["mdia","mdhd"])[0];if(d){a=d[0],l=a===0?12:20;const h=_(d,l),u=re(n,["mdia","hdlr"])[0];if(u){const f=De(u.subarray(8,12)),g={soun:de.AUDIO,vide:de.VIDEO}[f];if(g){const p=re(n,["mdia","minf","stbl","stsd"])[0];let m;p&&(m=De(p.subarray(12,16))),e[c]={timescale:h,type:g},e[g]={timescale:h,id:c,codec:m}}}}}}return re(r,["moov","mvex","trex"]).forEach(s=>{const n=_(s,4),o=e[n];o&&(o.default={duration:_(s,12),flags:_(s,20)})}),e}function jd(r,e){if(!r||!e)return r;const t=e.keyId;return t&&e.isCommonEncryption&&re(r,["moov","trak"]).forEach(s=>{const o=re(s,["mdia","minf","stbl","stsd"])[0].subarray(8);let a=re(o,["enca"]);const l=a.length>0;l||(a=re(o,["encv"])),a.forEach(c=>{const d=l?c.subarray(28):c.subarray(78);re(d,["sinf"]).forEach(u=>{const f=qo(u);if(f){const g=f.subarray(8,24);g.some(p=>p!==0)||(C.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${gt.hexDump(g)} -> ${gt.hexDump(t)}`),f.set(t,8))}})})}),r}function qo(r){const e=re(r,["schm"])[0];if(e){const t=De(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return re(r,["schi","tenc"])[0]}return C.error("[eme] missing 'schm' box"),null}function zd(r,e){return re(e,["moof","traf"]).reduce((t,i)=>{const s=re(i,["tfdt"])[0],n=s[0],o=re(i,["tfhd"]).reduce((a,l)=>{const c=_(l,4),d=r[c];if(d){let h=_(s,4);if(n===1){if(h===Cs)return C.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),a;h*=Cs+1,h+=_(s,8)}const u=d.timescale||9e4,f=h/u;if(isFinite(f)&&(a===null||f<a))return f}return a},null);return o!==null&&isFinite(o)&&(t===null||o<t)?o:t},null)}function Wd(r,e){let t=0,i=0,s=0;const n=re(r,["moof","traf"]);for(let o=0;o<n.length;o++){const a=n[o],l=re(a,["tfhd"])[0],c=_(l,4),d=e[c];if(!d)continue;const h=d.default,u=_(l,0)|(h==null?void 0:h.flags);let f=h==null?void 0:h.duration;u&8&&(u&2?f=_(l,12):f=_(l,8));const g=d.timescale||9e4,p=re(a,["trun"]);for(let m=0;m<p.length;m++){if(t=Yd(p[m]),!t&&f){const A=_(p[m],4);t=f*A}d.type===de.VIDEO?i+=t/g:d.type===de.AUDIO&&(s+=t/g)}}if(i===0&&s===0){let o=0;const a=re(r,["sidx"]);for(let l=0;l<a.length;l++){const c=Vd(a[l]);c!=null&&c.references&&(o+=c.references.reduce((d,h)=>d+h.info.duration||0,0))}return o}return i||s}function Yd(r){const e=_(r,0);let t=8;e&1&&(t+=4),e&4&&(t+=4);let i=0;const s=_(r,4);for(let n=0;n<s;n++){if(e&256){const o=_(r,t);i+=o,t+=4}e&512&&(t+=4),e&1024&&(t+=4),e&2048&&(t+=4)}return i}function Kd(r,e,t){re(e,["moof","traf"]).forEach(i=>{re(i,["tfhd"]).forEach(s=>{const n=_(s,4),o=r[n];if(!o)return;const a=o.timescale||9e4;re(i,["tfdt"]).forEach(l=>{const c=l[0];let d=_(l,4);if(c===0)d-=t*a,d=Math.max(d,0),Mr(l,4,d);else{d*=Math.pow(2,32),d+=_(l,8),d-=t*a,d=Math.max(d,0);const h=Math.floor(d/(Cs+1)),u=Math.floor(d%(Cs+1));Mr(l,4,h),Mr(l,8,u)}})})})}function Xd(r){const e={valid:null,remainder:null},t=re(r,["moof"]);if(t){if(t.length<2)return e.remainder=r,e}else return e;const i=t[t.length-1];return e.valid=_t(r,0,i.byteOffset-8),e.remainder=_t(r,i.byteOffset-8),e}function $t(r,e){const t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function Zo(r,e){const t=[],i=e.samples,s=e.timescale,n=e.id;let o=!1;return re(i,["moof"]).map(l=>{const c=l.byteOffset-8;re(l,["traf"]).map(h=>{const u=re(h,["tfdt"]).map(f=>{const g=f[0];let p=_(f,4);return g===1&&(p*=Math.pow(2,32),p+=_(f,8)),p/s})[0];return u!==void 0&&(r=u),re(h,["tfhd"]).map(f=>{const g=_(f,4),p=_(f,0)&16777215,m=(p&1)!==0,A=(p&2)!==0,x=(p&8)!==0;let b=0;const y=(p&16)!==0;let T=0;const E=(p&32)!==0;let S=8;g===n&&(m&&(S+=8),A&&(S+=4),x&&(b=_(f,S),S+=4),y&&(T=_(f,S),S+=4),E&&(S+=4),e.type==="video"&&(o=qd(e.codec)),re(h,["trun"]).map(R=>{const w=R[0],I=_(R,0)&16777215,O=(I&1)!==0;let P=0;const B=(I&4)!==0,J=(I&256)!==0;let H=0;const V=(I&512)!==0;let j=0;const F=(I&1024)!==0,U=(I&2048)!==0;let Q=0;const Y=_(R,4);let z=8;O&&(P=_(R,z),z+=4),B&&(z+=4);let K=P+c;for(let X=0;X<Y;X++){if(J?(H=_(R,z),z+=4):H=b,V?(j=_(R,z),z+=4):j=T,F&&(z+=4),U&&(w===0?Q=_(R,z):Q=Ko(R,z),z+=4),e.type===de.VIDEO){let ie=0;for(;ie<j;){const ee=_(i,K);if(K+=4,Zd(o,i[K])){const ne=i.subarray(K,K+ee);Jo(ne,o?2:1,r+Q/s,t)}K+=ee,ie+=ee+4}}r+=H/s}}))})})}),t}function qd(r){if(!r)return!1;const e=r.indexOf("."),t=e<0?r:r.substring(0,e);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function Zd(r,e){if(r){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Jo(r,e,t,i){const s=Qo(r);let n=0;n+=e;let o=0,a=0,l=!1,c=0;for(;n<s.length;){o=0;do{if(n>=s.length)break;c=s[n++],o+=c}while(c===255);a=0;do{if(n>=s.length)break;c=s[n++],a+=c}while(c===255);const d=s.length-n;if(!l&&o===4&&n<s.length){if(l=!0,s[n++]===181){const u=Yo(s,n);if(n+=2,u===49){const f=_(s,n);if(n+=4,f===1195456820){const g=s[n++];if(g===3){const p=s[n++],m=31&p,A=64&p,x=A?2+m*3:0,b=new Uint8Array(x);if(A){b[0]=p;for(let y=1;y<x;y++)b[y]=s[n++]}i.push({type:g,payloadType:o,pts:t,bytes:b})}}}}}else if(o===5&&a<d){if(l=!0,a>16){const h=[];for(let g=0;g<16;g++){const p=s[n++].toString(16);h.push(p.length==1?"0"+p:p),(g===3||g===5||g===7||g===9)&&h.push("-")}const u=a-16,f=new Uint8Array(u);for(let g=0;g<u;g++)f[g]=s[n++];i.push({payloadType:o,pts:t,uuid:h.join(""),userData:ft(f),userDataBytes:f})}}else if(a<d)n+=a;else if(a>d)break}}function Qo(r){const e=r.byteLength,t=[];let i=1;for(;i<e-2;)r[i]===0&&r[i+1]===0&&r[i+2]===3?(t.push(i+2),i+=2):i++;if(t.length===0)return r;const s=e-t.length,n=new Uint8Array(s);let o=0;for(i=0;i<s;o++,i++)o===t[0]&&(o++,t.shift()),n[i]=r[o];return n}function Jd(r){const e=r[0];let t="",i="",s=0,n=0,o=0,a=0,l=0,c=0;if(e===0){for(;De(r.subarray(c,c+1))!=="\0";)t+=De(r.subarray(c,c+1)),c+=1;for(t+=De(r.subarray(c,c+1)),c+=1;De(r.subarray(c,c+1))!=="\0";)i+=De(r.subarray(c,c+1)),c+=1;i+=De(r.subarray(c,c+1)),c+=1,s=_(r,12),n=_(r,16),a=_(r,20),l=_(r,24),c=28}else if(e===1){c+=4,s=_(r,c),c+=4;const h=_(r,c);c+=4;const u=_(r,c);for(c+=4,o=4294967296*h+u,Number.isSafeInteger(o)||(o=Number.MAX_SAFE_INTEGER,C.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),a=_(r,c),c+=4,l=_(r,c),c+=4;De(r.subarray(c,c+1))!=="\0";)t+=De(r.subarray(c,c+1)),c+=1;for(t+=De(r.subarray(c,c+1)),c+=1;De(r.subarray(c,c+1))!=="\0";)i+=De(r.subarray(c,c+1)),c+=1;i+=De(r.subarray(c,c+1)),c+=1}const d=r.subarray(c,r.byteLength);return{schemeIdUri:t,value:i,timeScale:s,presentationTime:o,presentationTimeDelta:n,eventDuration:a,id:l,payload:d}}function Qd(r,...e){const t=e.length;let i=8,s=t;for(;s--;)i+=e[s].byteLength;const 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(r,4),s=0,i=8;s<t;s++)n.set(e[s],i),i+=e[s].byteLength;return n}function _d(r,e,t){if(r.byteLength!==16)throw new RangeError("Invalid system id");let i,s;if(e){i=1,s=new Uint8Array(e.length*16);for(let a=0;a<e.length;a++){const l=e[a];if(l.byteLength!==16)throw new RangeError("Invalid key");s.set(l,a*16)}}else i=0,s=new Uint8Array;let n;i>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;const o=new Uint8Array(4);return t&&t.byteLength>0&&new DataView(o.buffer).setUint32(0,t.byteLength,!1),Qd([112,115,115,104],new Uint8Array([i,0,0,0]),r,n,s,o,t||new Uint8Array)}function $d(r){if(!(r instanceof ArrayBuffer)||r.byteLength<32)return null;const e={version:0,systemId:"",kids:null,data:null},t=new DataView(r),i=t.getUint32(0);if(r.byteLength!==i&&i>44||t.getUint32(4)!==1886614376||(e.version=t.getUint32(8)>>>24,e.version>1))return null;e.systemId=gt.hexDump(new Uint8Array(r,12,16));const n=t.getUint32(28);if(e.version===0){if(i-32<n)return null;e.data=new Uint8Array(r,32,n)}else if(e.version===1){e.kids=[];for(let o=0;o<n;o++)e.kids.push(new Uint8Array(r,32+o*16,16))}return e}let ws={};class qi{static clearKeyUriToKeyIdMap(){ws={}}constructor(e,t,i,s=[1],n=null){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=s,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&e!=="AES-128"}isSupported(){if(this.method){if(this.method==="AES-128"||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case ze.FAIRPLAY:case ze.WIDEVINE:case ze.PLAYREADY:case ze.CLEARKEY:return["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(this.method==="AES-128"&&this.uri&&!this.iv){typeof e!="number"&&(this.method==="AES-128"&&!this.iv&&C.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const i=eh(e);return new qi(this.method,this.uri,"identity",this.keyFormatVersions,i)}const t=wd(this.uri);if(t)switch(this.keyFormat){case ze.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case ze.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=_d(i,null,t);const s=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),n=String.fromCharCode.apply(null,Array.from(s)),o=n.substring(n.indexOf("<"),n.length),c=new DOMParser().parseFromString(o,"text/xml").getElementsByTagName("KID")[0];if(c){const d=c.childNodes[0]?c.childNodes[0].nodeValue:c.getAttribute("VALUE");if(d){const h=Dr(d).subarray(0,16);Cd(h),this.keyId=h}}break}default:{let i=t.subarray(0,16);if(i.length!==16){const s=new Uint8Array(16);s.set(i,16-i.length),i=s}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=ws[this.uri];if(!i){const s=Object.keys(ws).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,s),ws[this.uri]=i}this.keyId=i}return this}}function eh(r){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}const _o=/\{\$([a-zA-Z0-9-_]+)\}/g;function $o(r){return _o.test(r)}function We(r,e,t){if(r.variableList!==null||r.hasVariableRefs)for(let i=t.length;i--;){const s=t[i],n=e[s];n&&(e[s]=Fr(r,n))}}function Fr(r,e){if(r.variableList!==null||r.hasVariableRefs){const t=r.variableList;return e.replace(_o,i=>{const s=i.substring(2,i.length-1),n=t==null?void 0:t[s];return n===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),i):n})}return e}function ea(r,e,t){let i=r.variableList;i||(r.variableList=i={});let s,n;if("QUERYPARAM"in e){s=e.QUERYPARAM;try{const o=new self.URL(t).searchParams;if(o.has(s))n=o.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${t}"`)}catch(o){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else s=e.NAME,n=e.VALUE;s in i?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):i[s]=n||""}function th(r,e,t){const i=e.IMPORT;if(t&&i in t){let s=r.variableList;s||(r.variableList=s={}),s[i]=t[i]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function Ls(){if(!(typeof self>"u"))return self.MediaSource||self.WebKitMediaSource}const ih={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}},ta=Ls();function sh(r,e){const t=ih[e];return!!t&&t[r.slice(0,4)]===!0}function Nr(r,e){var t;return(t=ta==null?void 0:ta.isTypeSupported(`${e||"video"}/mp4;codecs="${r}"`))!=null?t:!1}const ia=/#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,sa=/#EXT-X-MEDIA:(.*)/g,rh=/^#EXT(?:INF|-X-TARGETDURATION):/m,ra=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),nh=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(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)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class at{static findGroup(e,t){for(let i=0;i<e.length;i++){const s=e[i];if(s.id===t)return s}}static convertAVC1ToAVCOTI(e){const t=e.split(".");if(t.length>2){let i=t.shift()+".";return i+=parseInt(t.shift()).toString(16),i+=("000"+parseInt(t.shift()).toString(16)).slice(-4),i}return e}static resolve(e,t){return wr.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return rh.test(e)}static parseMasterPlaylist(e,t){const i=$o(e),s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];ia.lastIndex=0;let o;for(;(o=ia.exec(e))!=null;)if(o[1]){var a;const c=new me(o[1]);We(s,c,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const d=Fr(s,o[2]),h={attrs:c,bitrate:c.decimalInteger("AVERAGE-BANDWIDTH")||c.decimalInteger("BANDWIDTH"),name:c.NAME,url:at.resolve(d,t)},u=c.decimalResolution("RESOLUTION");u&&(h.width=u.width,h.height=u.height),oh((c.CODECS||"").split(/[ ,]+/).filter(f=>f),h),h.videoCodec&&h.videoCodec.indexOf("avc1")!==-1&&(h.videoCodec=at.convertAVC1ToAVCOTI(h.videoCodec)),(a=h.unknownCodecs)!=null&&a.length||n.push(h),s.levels.push(h)}else if(o[3]){const c=o[3],d=o[4];switch(c){case"SESSION-DATA":{const h=new me(d);We(s,h,["DATA-ID","LANGUAGE","VALUE","URI"]);const u=h["DATA-ID"];u&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[u]=h);break}case"SESSION-KEY":{const h=na(d,t,s);h.encrypted&&h.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(h)):C.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);break}case"DEFINE":{{const h=new me(d);We(s,h,["NAME","VALUE","QUERYPARAM"]),ea(s,h,t)}break}case"CONTENT-STEERING":{const h=new me(d);We(s,h,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:at.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=oa(d);break}}}const l=n.length>0&&n.length<s.levels.length;return s.levels=l?n:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,i){let s;const n={},o=i.levels,a={AUDIO:o.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:o.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(sa.lastIndex=0;(s=sa.exec(e))!==null;){const c=new me(s[1]),d=c.TYPE;if(d){const h=a[d],u=n[d]||[];n[d]=u,We(i,c,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const f={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",instreamId:c["INSTREAM-ID"],name:c.NAME||c.LANGUAGE||"",type:d,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:c.LANGUAGE,url:c.URI?at.resolve(c.URI,t):""};if(h!=null&&h.length){const g=at.findGroup(h,f.groupId)||h[0];aa(f,g,"audioCodec"),aa(f,g,"textCodec")}u.push(f)}}return n}static parseLevelPlaylist(e,t,i,s,n,o){const a=new Sd(t),l=a.fragments;let c=null,d=0,h=0,u=0,f=0,g=null,p=new Rr(s,t),m,A,x,b=-1,y=!1;for(ra.lastIndex=0,a.m3u8=e,a.hasVariableRefs=$o(e);(m=ra.exec(e))!==null;){y&&(y=!1,p=new Rr(s,t),p.start=u,p.sn=d,p.cc=f,p.level=i,c&&(p.initSegment=c,p.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null));const R=m[1];if(R){p.duration=parseFloat(R);const w=(" "+m[2]).slice(1);p.title=w||null,p.tagList.push(w?["INF",R,w]:["INF",R])}else if(m[3]){if(W(p.duration)){p.start=u,x&&da(p,x,a),p.sn=d,p.level=i,p.cc=f,p.urlId=n,l.push(p);const w=(" "+m[3]).slice(1);p.relurl=Fr(a,w),la(p,g),g=p,u+=p.duration,d++,h=0,y=!0}}else if(m[4]){const w=(" "+m[4]).slice(1);g?p.setByteRange(w,g):p.setByteRange(w)}else if(m[5])p.rawProgramDateTime=(" "+m[5]).slice(1),p.tagList.push(["PROGRAM-DATE-TIME",p.rawProgramDateTime]),b===-1&&(b=l.length);else{if(m=m[0].match(nh),!m){C.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A<m.length&&!(typeof m[A]<"u");A++);const w=(" "+m[A]).slice(1),I=(" "+m[A+1]).slice(1),O=m[A+2]?(" "+m[A+2]).slice(1):"";switch(w){case"PLAYLIST-TYPE":a.type=I.toUpperCase();break;case"MEDIA-SEQUENCE":d=a.startSN=parseInt(I);break;case"SKIP":{const P=new me(I);We(a,P,["RECENTLY-REMOVED-DATERANGES"]);const B=P.decimalInteger("SKIPPED-SEGMENTS");if(W(B)){a.skippedSegments=B;for(let H=B;H--;)l.unshift(null);d+=B}const J=P.enumeratedString("RECENTLY-REMOVED-DATERANGES");J&&(a.recentlyRemovedDateranges=J.split(" "));break}case"TARGETDURATION":a.targetduration=Math.max(parseInt(I),1);break;case"VERSION":a.version=parseInt(I);break;case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"#":(I||O)&&p.tagList.push(O?[I,O]:[I]);break;case"DISCONTINUITY":f++,p.tagList.push(["DIS"]);break;case"GAP":p.gap=!0,p.tagList.push([w]);break;case"BITRATE":p.tagList.push([w,I]);break;case"DATERANGE":{const P=new me(I);We(a,P,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),We(a,P,P.clientAttrs);const B=new Mo(P,a.dateRanges[P.ID]);B.isValid||a.skippedSegments?a.dateRanges[B.id]=B:C.warn(`Ignoring invalid DATERANGE tag: "${I}"`),p.tagList.push(["EXT-X-DATERANGE",I]);break}case"DEFINE":{{const P=new me(I);We(a,P,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in P?th(a,P,o):ea(a,P,t)}break}case"DISCONTINUITY-SEQUENCE":f=parseInt(I);break;case"KEY":{const P=na(I,t,a);if(P.isSupported()){if(P.method==="NONE"){x=void 0;break}x||(x={}),x[P.keyFormat]&&(x=Ce({},x)),x[P.keyFormat]=P}else C.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${I}"`);break}case"START":a.startTimeOffset=oa(I);break;case"MAP":{const P=new me(I);if(We(a,P,["BYTERANGE","URI"]),p.duration){const B=new Rr(s,t);ca(B,P,i,x),c=B,p.initSegment=c,c.rawProgramDateTime&&!p.rawProgramDateTime&&(p.rawProgramDateTime=c.rawProgramDateTime)}else ca(p,P,i,x),c=p,y=!0;break}case"SERVER-CONTROL":{const P=new me(I);a.canBlockReload=P.bool("CAN-BLOCK-RELOAD"),a.canSkipUntil=P.optionalFloat("CAN-SKIP-UNTIL",0),a.canSkipDateRanges=a.canSkipUntil>0&&P.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=P.optionalFloat("PART-HOLD-BACK",0),a.holdBack=P.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const P=new me(I);a.partTarget=P.decimalFloatingPoint("PART-TARGET");break}case"PART":{let P=a.partList;P||(P=a.partList=[]);const B=h>0?P[P.length-1]:void 0,J=h++,H=new me(I);We(a,H,["BYTERANGE","URI"]);const V=new Td(H,p,t,J,B);P.push(V),p.duration+=V.duration;break}case"PRELOAD-HINT":{const P=new me(I);We(a,P,["URI"]),a.preloadHint=P;break}case"RENDITION-REPORT":{const P=new me(I);We(a,P,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(P);break}default:C.warn(`line parsed but not handled: ${m}`);break}}}g&&!g.relurl?(l.pop(),u-=g.duration,a.partList&&(a.fragmentHint=g)):a.partList&&(la(p,g),p.cc=f,a.fragmentHint=p,x&&da(p,x,a));const T=l.length,E=l[0],S=l[T-1];if(u+=a.skippedSegments*a.targetduration,u>0&&T&&S){a.averagetargetduration=u/T;const R=S.sn;a.endSN=R!=="initSegment"?R:0,a.live||(S.endList=!0),E&&(a.startCC=E.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(u+=a.fragmentHint.duration),a.totalduration=u,a.endCC=f,b>0&&ah(l,b),a}}function na(r,e,t){var i,s;const n=new me(r);We(t,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const o=(i=n.METHOD)!=null?i:"",a=n.URI,l=n.hexadecimalInteger("IV"),c=n.KEYFORMATVERSIONS,d=(s=n.KEYFORMAT)!=null?s:"identity";a&&n.IV&&!l&&C.error(`Invalid IV: ${n.IV}`);const h=a?at.resolve(a,e):"",u=(c||"1").split("/").map(Number).filter(Number.isFinite);return new qi(o,h,d,u,l)}function oa(r){const t=new me(r).decimalFloatingPoint("TIME-OFFSET");return W(t)?t:null}function oh(r,e){["video","audio","text"].forEach(t=>{const i=r.filter(s=>sh(s,t));if(i.length){const s=i.filter(n=>n.lastIndexOf("avc1",0)===0||n.lastIndexOf("mp4a",0)===0);e[`${t}Codec`]=s.length>0?s[0]:i[0],r=r.filter(n=>i.indexOf(n)===-1)}}),e.unknownCodecs=r}function aa(r,e,t){const i=e[t];i&&(r[t]=i)}function ah(r,e){let t=r[e];for(let i=e;i--;){const s=r[i];if(!s)return;s.programDateTime=t.programDateTime-s.duration*1e3,t=s}}function la(r,e){r.rawProgramDateTime?r.programDateTime=Date.parse(r.rawProgramDateTime):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime),W(r.programDateTime)||(r.programDateTime=null,r.rawProgramDateTime=null)}function ca(r,e,t,i){r.relurl=e.URI,e.BYTERANGE&&r.setByteRange(e.BYTERANGE),r.level=t,r.sn="initSegment",i&&(r.levelkeys=i),r.initSegment=null}function da(r,e,t){r.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(s=>e[s].isCommonEncryption)&&i.push(r)}var ae={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Z={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function ha(r){const{type:e}=r;switch(e){case ae.AUDIO_TRACK:return Z.AUDIO;case ae.SUBTITLE_TRACK:return Z.SUBTITLE;default:return Z.MAIN}}function Br(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class lh{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{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)}unregisterListeners(){const{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)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,n=i||s,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(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ae.MANIFEST,url:i,deliveryDirectives:null})}onLevelLoading(e,t){const{id:i,level:s,url:n,deliveryDirectives:o}=t;this.load({id:i,level:s,responseType:"text",type:ae.LEVEL,url:n,deliveryDirectives:o})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:ae.AUDIO_TRACK,url:n,deliveryDirectives:o})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:ae.SUBTITLE_TRACK,url:n,deliveryDirectives:o})}load(e){var t;const i=this.hls.config;let s=this.getInternalLoader(e);if(s){const c=s.context;if(c&&c.url===e.url){C.trace("[playlist-loader]: playlist request ongoing");return}C.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let n;if(e.type===ae.MANIFEST?n=i.manifestLoadPolicy.default:n=Ce({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),(t=e.deliveryDirectives)!=null&&t.part){let c;if(e.type===ae.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===ae.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===ae.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const d=c.partTarget,h=c.targetduration;if(d&&h){const u=Math.max(d*3,h*.8)*1e3;n=Ce({},n,{maxTimeToFirstByteMs:Math.min(u,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(u,n.maxTimeToFirstByteMs)})}}}const 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:(c,d,h,u)=>{const f=this.getInternalLoader(h);this.resetInternalLoader(h.type);const g=c.data;if(g.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(c,h,new Error("no EXTM3U delimiter"),u||null,d);return}d.parsing.start=performance.now(),at.isMediaPlaylist(g)?this.handleTrackOrLevelPlaylist(c,d,h,u||null,f):this.handleMasterPlaylist(c,d,h,u)},onError:(c,d,h,u)=>{this.handleNetworkError(d,h,!1,c,u)},onTimeout:(c,d,h)=>{this.handleNetworkError(d,h,!0,void 0,c)}};s.load(e,a,l)}handleMasterPlaylist(e,t,i,s){const n=this.hls,o=e.data,a=Br(e,i),l=at.parseMasterPlaylist(o,a);if(l.playlistParsingError){this.handleManifestParsingError(e,i,l.playlistParsingError,s,t);return}const{contentSteering:c,levels:d,sessionData:h,sessionKeys:u,startTimeOffset:f,variableList:g}=l;this.variableList=g;const{AUDIO:p=[],SUBTITLES:m,"CLOSED-CAPTIONS":A}=at.parseMasterPlaylistMedia(o,a,l);p.length&&!p.some(b=>!b.url)&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(C.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:!1,autoselect:!1,forced:!1,id:-1,attrs:new me({}),bitrate:0,url:""})),n.trigger(v.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:m,captions:A,contentSteering:c,url:a,stats:t,networkDetails:s,sessionData:h,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,i,s,n){const o=this.hls,{id:a,level:l,type:c}=i,d=Br(e,i),h=W(a)?a:0,u=W(l)?l:h,f=ha(i),g=at.parseLevelPlaylist(e.data,d,u,f,h,this.variableList);if(c===ae.MANIFEST){const p={attrs:new me({}),bitrate:0,details:g,name:"",url:d};o.trigger(v.MANIFEST_LOADED,{levels:[p],audioTracks:[],url:d,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=g,this.handlePlaylistLoaded(g,e,t,i,s,n)}handleManifestParsingError(e,t,i,s,n){this.hls.trigger(v.ERROR,{type:q.NETWORK_ERROR,details:D.MANIFEST_PARSING_ERROR,fatal:t.type===ae.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:n})}handleNetworkError(e,t,i=!1,s,n){let o=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===ae.LEVEL?o+=`: ${e.level} id: ${e.id}`:(e.type===ae.AUDIO_TRACK||e.type===ae.SUBTITLE_TRACK)&&(o+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(o);C.warn(`[playlist-loader]: ${o}`);let l=D.UNKNOWN,c=!1;const d=this.getInternalLoader(e);switch(e.type){case ae.MANIFEST:l=i?D.MANIFEST_LOAD_TIMEOUT:D.MANIFEST_LOAD_ERROR,c=!0;break;case ae.LEVEL:l=i?D.LEVEL_LOAD_TIMEOUT:D.LEVEL_LOAD_ERROR,c=!1;break;case ae.AUDIO_TRACK:l=i?D.AUDIO_TRACK_LOAD_TIMEOUT:D.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case ae.SUBTITLE_TRACK:l=i?D.SUBTITLE_TRACK_LOAD_TIMEOUT:D.SUBTITLE_LOAD_ERROR,c=!1;break}d&&this.resetInternalLoader(e.type);const h={type:q.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:d,context:e,error:a,networkDetails:t,stats:n};if(s){const u=(t==null?void 0:t.url)||e.url;h.response=je({url:u,data:void 0},s)}this.hls.trigger(v.ERROR,h)}handlePlaylistLoaded(e,t,i,s,n,o){const a=this.hls,{type:l,level:c,id:d,groupId:h,deliveryDirectives:u}=s,f=Br(t,s),g=ha(s),p=typeof s.level=="number"&&g===Z.MAIN?c:void 0;if(!e.fragments.length){const A=new Error("No Segments found in Playlist");a.trigger(v.ERROR,{type:q.NETWORK_ERROR,details:D.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:A,reason:A.message,response:t,context:s,level:p,parent:g,networkDetails:n,stats:i});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const m=e.playlistParsingError;if(m){a.trigger(v.ERROR,{type:q.NETWORK_ERROR,details:D.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:m,reason:m.message,response:t,context:s,level:p,parent:g,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 ae.MANIFEST:case ae.LEVEL:a.trigger(v.LEVEL_LOADED,{details:e,level:p||0,id:d||0,stats:i,networkDetails:n,deliveryDirectives:u});break;case ae.AUDIO_TRACK:a.trigger(v.AUDIO_TRACK_LOADED,{details:e,id:d||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:u});break;case ae.SUBTITLE_TRACK:a.trigger(v.SUBTITLE_TRACK_LOADED,{details:e,id:d||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:u});break}}}function ua(r,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=r,e.dispatchEvent(t)}function fa(r,e){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues&&!r.cues.getCueById(e.id))try{if(r.addCue(e),!r.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){C.debug(`[texttrack-utils]: ${i}`);const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,r.addCue(s)}t==="disabled"&&(r.mode=t)}function gi(r){const e=r.mode;if(e==="disabled"&&(r.mode="hidden"),r.cues)for(let t=r.cues.length;t--;)r.removeCue(r.cues[t]);e==="disabled"&&(r.mode=e)}function Ur(r,e,t,i){const s=r.mode;if(s==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){const n=dh(r.cues,e,t);for(let o=0;o<n.length;o++)(!i||i(n[o]))&&r.removeCue(n[o])}s==="disabled"&&(r.mode=s)}function ch(r,e){if(e<r[0].startTime)return 0;const t=r.length-1;if(e>r[t].endTime)return-1;let i=0,s=t;for(;i<=s;){const n=Math.floor((s+i)/2);if(e<r[n].startTime)s=n-1;else if(e>r[n].startTime&&i<t)i=n+1;else return n}return r[i].startTime-e<e-r[s].startTime?i:s}function dh(r,e,t){const i=[],s=ch(r,e);if(s>-1)for(let n=s,o=r.length;n<o;n++){const a=r[n];if(a.startTime>=e&&a.endTime<=t)i.push(a);else if(a.startTime>t)return i}return i}var lt={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const hh=.25;function Hr(){if(!(typeof self>"u"))return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const Rs=(()=>{const r=Hr();try{new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Gr(r,e){return r.getTime()/1e3-e}function uh(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class fh{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{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.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(v.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{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.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(v.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(gi(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const i=e[t];if(i.kind==="metadata"&&i.label==="id3")return ua(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:s}}}=this;if(!i&&!s)return;const{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=Hr();for(let a=0;a<n.length;a++){const l=n[a].type;if(l===lt.emsg&&!i||!s)continue;const c=zo(n[a].data);if(c){const d=n[a].pts;let h=d+n[a].duration;h>Rs&&(h=Rs),h-d<=0&&(h=d+hh);for(let f=0;f<c.length;f++){const g=c[f];if(!jo(g)){this.updateId3CueEnds(d,l);const p=new o(d,h,"");p.value=g,l&&(p.type=l),this.id3Track.addCue(p)}}}}}updateId3CueEnds(e,t){var i;const s=(i=this.id3Track)==null?void 0:i.cues;if(s)for(let n=s.length;n--;){const o=s[n];o.type===t&&o.startTime<e&&o.endTime===Rs&&(o.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){const{id3Track:n,hls:o}=this;if(!o)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:l}}=o;if(n&&(a||l)){let c;s==="audio"?c=d=>d.type===lt.audioId3&&l:s==="video"?c=d=>d.type===lt.emsg&&a:c=d=>d.type===lt.audioId3&&l||d.type===lt.emsg&&a,Ur(n,t,i,c)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:s}=this,{dateRanges:n}=t,o=Object.keys(n);if(s){const d=Object.keys(i).filter(h=>!o.includes(h));for(let h=d.length;h--;){const u=d[h];Object.keys(i[u].cues).forEach(f=>{s.removeCue(i[u].cues[f])}),delete i[u]}}const a=t.fragments[t.fragments.length-1];if(o.length===0||!W(a==null?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=a.programDateTime/1e3-a.start,c=Hr();for(let d=0;d<o.length;d++){const h=o[d],u=n[h],f=i[h],g=(f==null?void 0:f.cues)||{};let p=(f==null?void 0:f.durationKnown)||!1;const m=Gr(u.startDate,l);let A=Rs;const x=u.endDate;if(x)A=Gr(x,l),p=!0;else if(u.endOnNext&&!p){const y=o.reduce((T,E)=>{const S=n[E];return S.class===u.class&&S.id!==E&&S.startDate>u.startDate&&T.push(S),T},[]).sort((T,E)=>T.startDate.getTime()-E.startDate.getTime())[0];y&&(A=Gr(y.startDate,l),p=!0)}const b=Object.keys(u.attr);for(let y=0;y<b.length;y++){const T=b[y];if(!bd(T))continue;let E=g[T];if(E)p&&!f.durationKnown&&(E.endTime=A);else{let S=u.attr[T];E=new c(m,A,""),xd(T)&&(S=uh(S)),E.value={key:T,data:S},E.type=lt.dateRange,E.id=h,this.id3Track.addCue(E),g[T]=E}}i[h]={cues:g,dateRange:u,durationKnown:p}}}}class gh{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(e===null)return null;const{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:n,liveSyncDurationCount:o,lowLatencyMode:a}=this.config,l=this.hls.userConfig;let c=a&&i||t;(l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=n!==void 0?n:o*s);const d=s,h=1;return c+Math.min(this.stallCount*h,d)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,i=this.levelDetails;if(e===null||t===null||i===null)return null;const s=i.edge,n=e-t-this.edgeStalled,o=s-i.totalduration,a=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(o,n),a)}get drift(){const{levelDetails:e}=this;return e===null?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(v.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(v.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(v.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(v.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var i;t.details===D.BUFFER_STALLED_ERROR&&(this.stallCount++,(i=this.levelDetails)!=null&&i.live&&C.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:n}=this.config;if(!s||n===1)return;const o=this.targetLatency;if(o===null)return;const a=i-o,l=Math.min(this.maxLatency,o+t.targetduration),c=a<l;if(t.live&&c&&a>.05&&this.forwardBufferLength>1){const d=Math.min(2,Math.max(1,n)),h=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;e.playbackRate=Math.min(d,Math.max(1,h))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const Vr=["NONE","TYPE-0","TYPE-1",null];var Zi={No:"",Yes:"YES",v2:"v2"};function ph(r,e){const{canSkipUntil:t,canSkipDateRanges:i,endSN:s}=r,n=e!==void 0?e-s:0;return t&&n<t?i?Zi.v2:Zi.Yes:Zi.No}class ga{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){const 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}}class Ji{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=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.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.unknownCodecs=e.unknownCodecs,this.codecSet=[e.videoCodec,e.audioCodec].filter(t=>t).join(",").replace(/\.[^.,]+/g,"")}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get attrs(){return this._attrs[this._urlId]}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get uri(){return this.url[this._urlId]||""}get urlId(){return this._urlId}set urlId(e){const t=e%this.url.length;this._urlId!==t&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=t)}get audioGroupId(){var e;return(e=this.audioGroupIds)==null?void 0:e[this.urlId]}get textGroupId(){var e;return(e=this.textGroupIds)==null?void 0:e[this.urlId]}addFallback(e){this.url.push(e.url),this._attrs.push(e.attrs)}}function jr(r,e){const t=e.startPTS;if(W(t)){let i=0,s;e.sn>r.sn?(i=t-r.start,s=r):(i=r.start-t,s=e),s.duration!==i&&(s.duration=i)}else e.sn>r.sn?r.cc===e.cc&&r.minEndPTS?e.start=r.start+(r.minEndPTS-r.start):e.start=r.start+r.duration:e.start=Math.max(r.start-e.duration,0)}function pa(r,e,t,i,s,n){i-t<=0&&(C.warn("Fragment should have a positive duration",e),i=t+e.duration,n=s+e.duration);let a=t,l=i;const c=e.startPTS,d=e.endPTS;if(W(c)){const m=Math.abs(c-t);W(e.deltaPTS)?e.deltaPTS=Math.max(m,e.deltaPTS):e.deltaPTS=m,a=Math.max(t,c),t=Math.min(t,c),s=Math.min(s,e.startDTS),l=Math.min(i,d),i=Math.max(i,d),n=Math.max(n,e.endDTS)}const h=t-e.start;e.start!==0&&(e.start=t),e.duration=i-e.start,e.startPTS=t,e.maxStartPTS=a,e.startDTS=s,e.endPTS=i,e.minEndPTS=l,e.endDTS=n;const u=e.sn;if(!r||u<r.startSN||u>r.endSN)return 0;let f;const g=u-r.startSN,p=r.fragments;for(p[g]=e,f=g;f>0;f--)jr(p[f],p[f-1]);for(f=g;f<p.length-1;f++)jr(p[f],p[f+1]);return r.fragmentHint&&jr(p[p.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,h}function mh(r,e){let t=null;const i=r.fragments;for(let l=i.length-1;l>=0;l--){const c=i[l].initSegment;if(c){t=c;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let s=0,n;if(Ah(r,e,(l,c)=>{l.relurl&&(s=l.cc-c.cc),W(l.startPTS)&&W(l.endPTS)&&(c.start=c.startPTS=l.startPTS,c.startDTS=l.startDTS,c.maxStartPTS=l.maxStartPTS,c.endPTS=l.endPTS,c.endDTS=l.endDTS,c.minEndPTS=l.minEndPTS,c.duration=l.endPTS-l.startPTS,c.duration&&(n=c),e.PTSKnown=e.alignedSliding=!0),c.elementaryStreams=l.elementaryStreams,c.loader=l.loader,c.stats=l.stats,c.urlId=l.urlId,l.initSegment&&(c.initSegment=l.initSegment,t=l.initSegment)}),t&&(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(c=>{var d;(!c.initSegment||c.initSegment.relurl===((d=t)==null?void 0:d.relurl))&&(c.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some(l=>!l),e.deltaUpdateFailed){C.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=vh(r.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const o=e.fragments;if(s){C.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l<o.length;l++)o[l].cc+=s}e.skippedSegments&&(e.startCC=e.fragments[0].cc),yh(r.partList,e.partList,(l,c)=>{c.elementaryStreams=l.elementaryStreams,c.stats=l.stats}),n?pa(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):ma(r,e),o.length&&(e.totalduration=e.edge-o[0].start),e.driftStartTime=r.driftStartTime,e.driftStart=r.driftStart;const a=e.advancedDateTime;if(e.advanced&&a){const l=e.edge;e.driftStart||(e.driftStartTime=a,e.driftStart=l),e.driftEndTime=a,e.driftEnd=l}else e.driftEndTime=r.driftEndTime,e.driftEnd=r.driftEnd,e.advancedDateTime=r.advancedDateTime}function vh(r,e,t){const i=Ce({},r);return t&&t.forEach(s=>{delete i[s]}),Object.keys(e).forEach(s=>{const n=new Mo(e[s].attr,i[s]);n.isValid?i[s]=n:C.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[s].attr)}"`)}),i}function yh(r,e,t){if(r&&e){let i=0;for(let s=0,n=r.length;s<=n;s++){const o=r[s],a=e[s+i];o&&a&&o.index===a.index&&o.fragment.sn===a.fragment.sn?t(o,a):i--}}}function Ah(r,e,t){const i=e.skippedSegments,s=Math.max(r.startSN,e.startSN)-e.startSN,n=(r.fragmentHint?1:0)+(i?e.endSN:Math.min(r.endSN,e.endSN))-e.startSN,o=e.startSN-r.startSN,a=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=r.fragmentHint?r.fragments.concat(r.fragmentHint):r.fragments;for(let c=s;c<=n;c++){const d=l[o+c];let h=a[c];i&&!h&&c<i&&(h=e.fragments[c]=d),d&&h&&t(d,h)}}function ma(r,e){const t=e.startSN+e.skippedSegments-r.startSN,i=r.fragments;t<0||t>=i.length||zr(e,i[t].start)}function zr(r,e){if(e){const t=r.fragments;for(let i=r.skippedSegments;i<t.length;i++)t[i].start+=e;r.fragmentHint&&(r.fragmentHint.start+=e)}}function bh(r,e=1/0){let t=1e3*r.targetduration;if(r.updated){const i=r.fragments,s=4;if(i.length&&t*s>e){const n=i[i.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function xh(r,e,t){if(!(r!=null&&r.details))return null;const i=r.details;let s=i.fragments[e-i.startSN];return s||(s=i.fragmentHint,s&&s.sn===e)?s:e<i.startSN&&t&&t.sn===e?t:null}function va(r,e,t){var i;return r!=null&&r.details?ya((i=r.details)==null?void 0:i.partList,e,t):null}function ya(r,e,t){if(r)for(let i=r.length;i--;){const s=r[i];if(s.index===t&&s.fragment.sn===e)return s}return null}function Ds(r){switch(r.details){case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_TIMEOUT:case D.LEVEL_LOAD_TIMEOUT:case D.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Aa(r,e){const t=Ds(e);return r.default[`${t?"timeout":"error"}Retry`]}function Wr(r,e){const t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function ba(r){return je(je({},r),{errorRetry:null,timeoutRetry:null})}function ks(r,e,t,i){return!!r&&e<r.maxNumRetry&&(Th(i)||!!t)}function Th(r){return r===0&&navigator.onLine===!1||!!r&&(r<400||r>499)}const xa={search:function(r,e){let t=0,i=r.length-1,s=null,n=null;for(;t<=i;){s=(t+i)/2|0,n=r[s];const o=e(n);if(o>0)t=s+1;else if(o<0)i=s-1;else return n}return null}};function Eh(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!W(e))return null;const i=r[0].programDateTime;if(e<(i||0))return null;const s=r[r.length-1].endProgramDateTime;if(e>=(s||0))return null;t=t||0;for(let n=0;n<r.length;++n){const o=r[n];if(Sh(e,t,o))return o}return null}function Qi(r,e,t=0,i=0){let s=null;if(r?s=e[r.sn-e[0].sn+1]||null:t===0&&e[0].start===0&&(s=e[0]),s&&Yr(t,i,s)===0)return s;const n=xa.search(e,Yr.bind(null,t,i));return n&&(n!==r||!s)?n:s}function Yr(r=0,e=0,t){if(t.start<=r&&t.start+t.duration>r)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=r?1:t.start-i>r&&t.start?-1:0}function Sh(r,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>r}function Ih(r,e){return xa.search(r,t=>t.cc<e?1:t.cc>e?-1:0)}const Ch=3e5;var Ye={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},ct={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class wh{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=C.log.bind(C,"[info]:"),this.warn=C.warn.bind(C,"[warning]:"),this.error=C.error.bind(C,"[error]:"),this.registerListeners()}registerListeners(){const 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(){const 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,this.penalizedRenditions={}}startLoad(e){this.playlistError=0}stopLoad(){}getVariantLevelIndex(e){return(e==null?void 0:e.type)===Z.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const s=this.hls,n=t.context;switch(t.details){case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Ye.SendAlternateToPenaltyBox;return}case D.LEVEL_EMPTY_ERROR:case D.LEVEL_PARSING_ERROR:{var o,a;const l=t.parent===Z.MAIN?t.level:s.loadLevel;t.details===D.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(a=o.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l))}return;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:typeof(n==null?void 0:n.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case D.AUDIO_TRACK_LOAD_ERROR:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.SUBTITLE_LOAD_ERROR:case D.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const l=s.levels[s.loadLevel];if(l&&(n.type===ae.AUDIO_TRACK&&n.groupId===l.audioGroupId||n.type===ae.SUBTITLE_TRACK&&n.groupId===l.textGroupId)){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=Ye.SendAlternateToPenaltyBox,t.errorAction.flags=ct.MoveAllAlternatesMatchingHost;return}}return;case D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const l=s.levels[s.loadLevel],c=l==null?void 0:l.attrs["HDCP-LEVEL"];c&&(t.errorAction={action:Ye.SendAlternateToPenaltyBox,flags:ct.MoveAllAlternatesMatchingHDCP,hdcpLevel:c})}return;case D.BUFFER_ADD_CODEC_ERROR:case D.REMUX_ALLOC_ERROR:t.errorAction=this.getLevelSwitchAction(t,(i=t.level)!=null?i:s.loadLevel);return;case D.INTERNAL_EXCEPTION:case D.BUFFER_APPENDING_ERROR:case D.BUFFER_APPEND_ERROR:case D.BUFFER_FULL_ERROR:case D.LEVEL_SWITCH_ERROR:case D.BUFFER_STALLED_ERROR:case D.BUFFER_SEEK_OVER_HOLE:case D.BUFFER_NUDGE_ON_STALL:t.errorAction={action:Ye.DoNothing,flags:ct.None};return}if(t.type===q.KEY_SYSTEM_ERROR){const l=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l);return}}getPlaylistRetryOrSwitchAction(e,t){var i;const s=this.hls,n=Aa(s.config.playlistLoadPolicy,e),o=this.playlistError++,a=(i=e.response)==null?void 0:i.code;if(ks(n,o,Ds(e),a))return{action:Ye.RetryRequest,flags:ct.None,retryConfig:n,retryCount:o};const c=this.getLevelSwitchAction(e,t);return n&&(c.retryConfig=n,c.retryCount=o),c}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:o}=t.config,a=Aa(e.details.startsWith("key")?o:n,e),l=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(s){var c;e.details!==D.FRAG_GAP&&s.fragmentError++;const h=(c=e.response)==null?void 0:c.code;if(ks(a,l,Ds(e),h))return{action:Ye.RetryRequest,flags:ct.None,retryConfig:a,retryCount:l}}const d=this.getLevelSwitchAction(e,i);return a&&(d.retryConfig=a,d.retryCount=l),d}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const s=this.hls.levels[t];if(s&&(s.loadError++,i.autoLevelEnabled)){var n,o;let a=-1;const{levels:l,loadLevel:c,minAutoLevel:d,maxAutoLevel:h}=i,u=(n=e.frag)==null?void 0:n.type,{type:f,groupId:g}=(o=e.context)!=null?o:{};for(let p=l.length;p--;){const m=(p+c)%l.length;if(m!==c&&m>=d&&m<=h&&l[m].loadError===0){const A=l[m];if(e.details===D.FRAG_GAP&&e.frag){const x=l[m].details;if(x){const b=Qi(e.frag,x.fragments,e.frag.start);if(b!=null&&b.gap)continue}}else{if(f===ae.AUDIO_TRACK&&g===A.audioGroupId||f===ae.SUBTITLE_TRACK&&g===A.textGroupId)continue;if(u===Z.AUDIO&&s.audioGroupId===A.audioGroupId||u===Z.SUBTITLE&&s.textGroupId===A.textGroupId)continue}a=m;break}}if(a>-1&&i.loadLevel!==a)return e.levelRetry=!0,this.playlistError=0,{action:Ye.SendAlternateToPenaltyBox,flags:ct.None,nextAutoLevel:a}}return{action:Ye.SendAlternateToPenaltyBox,flags:ct.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case Ye.DoNothing:break;case Ye.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==D.FRAG_GAP&&(t.fatal=!0);break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:s,hdcpLevel:n,nextAutoLevel:o}=i;switch(s){case ct.None:this.switchLevel(e,o);break;case ct.MoveAllAlternatesMatchingHost:i.resolved||(i.resolved=this.redundantFailover(e));break;case ct.MoveAllAlternatesMatchingHDCP:n&&(t.maxHdcpLevel=Vr[Vr.indexOf(n)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(e,o)}switchLevel(e,t){t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}redundantFailover(e){const{hls:t,penalizedRenditions:i}=this,s=e.parent===Z.MAIN?e.level:t.loadLevel,n=t.levels[s],o=n.url.length,a=e.frag?e.frag.urlId:n.urlId;n.urlId===a&&(!e.frag||n.details)&&this.penalizeRendition(n,e);for(let l=1;l<o;l++){const c=(a+l)%o,d=i[c];if(!d||Lh(d,e,i[a]))return this.warn(`Switching to Redundant Stream ${c+1}/${o}: "${n.url[c]}" after ${e.details}`),this.playlistError=0,t.levels.forEach(h=>{h.urlId=c}),t.nextLoadLevel=s,!0}return!1}penalizeRendition(e,t){const{penalizedRenditions:i}=this,s=i[e.urlId]||{lastErrorPerfMs:0,errors:[],details:void 0};s.lastErrorPerfMs=performance.now(),s.errors.push(t),s.details=e.details,i[e.urlId]=s}}function Lh(r,e,t){if(performance.now()-r.lastErrorPerfMs>Ch)return!0;const i=r.details;if(e.details===D.FRAG_GAP&&i&&e.frag){const s=e.frag.start,n=Qi(null,i.fragments,s);if(n&&!n.gap)return!0}if(t&&r.errors.length<t.errors.length){const s=r.errors[r.errors.length-1];if(i&&s.frag&&e.frag&&Math.abs(s.frag.start-e.frag.start)>i.targetduration*3)return!0}return!1}class Kr{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=C.log.bind(C,`${t}:`),this.warn=C.warn.bind(C,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){clearTimeout(this.timer),this.timer=-1}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t){const i=t==null?void 0:t.renditionReports;if(i){let s=-1;for(let n=0;n<i.length;n++){const o=i[n];let a;try{a=new self.URL(o.URI,t.url).href}catch(l){C.warn(`Could not construct new URL for Rendition Report: ${l}`),a=o.URI||""}if(a===e){s=n;break}else a===e.substring(0,a.length)&&(s=n)}if(s!==-1){const n=i[s],o=parseInt(n["LAST-MSN"])||(t==null?void 0:t.lastPartSn);let a=parseInt(n["LAST-PART"])||(t==null?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const l=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&l>t.partTarget&&(a+=1)}return new ga(o,a>=0?a:void 0,Zi.No)}}}loadPlaylist(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,i){const{details:s,stats:n}=t,o=self.performance.now(),a=n.loading.first?Math.max(0,o-n.loading.first):0;if(s.advancedDateTime=Date.now()-a,s.live||i!=null&&i.live){if(s.reloaded(i),i&&this.log(`live playlist ${e} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:"MISSED"}`),i&&s.fragments.length>0&&mh(i,s),!this.canLoad||!s.live)return;let l,c,d;if(s.canBlockReload&&s.endSN&&s.advanced){const m=this.hls.config.lowLatencyMode,A=s.lastPartSn,x=s.endSN,b=s.lastPartIndex,y=b!==-1,T=A===x,E=m?0:b;y?(c=T?x+1:A,d=T?E:b+1):c=x+1;const S=s.age,R=S+s.ageHeader;let w=Math.min(R-s.partTarget,s.targetduration*1.5);if(w>0){if(i&&w>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${w} with playlist age: ${s.age}`),w=0;else{const I=Math.floor(w/s.targetduration);if(c+=I,d!==void 0){const O=Math.round(w%s.targetduration/s.partTarget);d+=O}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${S.toFixed(2)}s goal: ${w} skip sn ${I} to part ${d}`)}s.tuneInGoal=w}if(l=this.getDeliveryDirectives(s,t.deliveryDirectives,c,d),m||!T){this.loadPlaylist(l);return}}else s.canBlockReload&&(l=this.getDeliveryDirectives(s,t.deliveryDirectives,c,d));const h=this.hls.mainForwardBufferInfo,u=h?h.end-h.len:0,f=(s.edge-u)*1e3,g=bh(s,f);s.updated&&o>this.requestScheduled+g&&(this.requestScheduled=n.loading.start),c!==void 0&&s.canBlockReload?this.requestScheduled=n.loading.first+g-(s.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+g<o?this.requestScheduled=o:this.requestScheduled-o<=0&&(this.requestScheduled+=g);let p=this.requestScheduled-o;p=Math.max(0,p),this.log(`reload live playlist ${e} in ${Math.round(p)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(l),p)}else this.clearTimer()}getDeliveryDirectives(e,t,i,s){let n=ph(e,i);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,n=Zi.No),new ga(i,s,n)}checkRetry(e){const t=e.details,i=Ds(e),s=e.errorAction,{action:n,retryCount:o=0,retryConfig:a}=s||{},l=!!s&&!!a&&(n===Ye.RetryRequest||!s.resolved&&n===Ye.SendAlternateToPenaltyBox);if(l){var c;if(this.requestScheduled=-1,o>=a.maxNumRetry)return!1;if(i&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const d=Wr(a,o);this.timer=self.setTimeout(()=>this.loadPlaylist(),d),this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" in ${d}ms`)}e.levelRetry=!0,s.resolved=!0}return l}}let Xr;class Rh extends Kr{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-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(){const{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.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(v.FRAG_LOADED,this.onFragLoaded,this),e.on(v.ERROR,this.onError,this)}_unregisterListeners(){const{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.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(v.FRAG_LOADED,this.onFragLoaded,this),e.off(v.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}startLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.startLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=[],s={};let n;t.levels.forEach(o=>{var a;const l=o.attrs;((a=o.audioCodec)==null?void 0:a.indexOf("mp4a.40.34"))!==-1&&(Xr||(Xr=/chrome|firefox/i.test(navigator.userAgent)),Xr&&(o.audioCodec=void 0));const{AUDIO:c,CODECS:d,"FRAME-RATE":h,"PATHWAY-ID":u,RESOLUTION:f,SUBTITLES:g}=l,m=`${`${u||"."}-`}${o.bitrate}-${f}-${h}-${d}`;n=s[m],n?n.addFallback(o):(n=new Ji(o),s[m]=n,i.push(n)),Ps(n,"audio",c),Ps(n,"text",g)}),this.filterAndSortMediaOptions(i,t)}filterAndSortMediaOptions(e,t){let i=[],s=[],n=!1,o=!1,a=!1,l=e.filter(({audioCodec:f,videoCodec:g,width:p,height:m,unknownCodecs:A})=>(n||(n=!!(p&&m)),o||(o=!!g),a||(a=!!f),!(A!=null&&A.length)&&(!f||Nr(f,"audio"))&&(!g||Nr(g,"video"))));if((n||o)&&a&&(l=l.filter(({videoCodec:f,width:g,height:p})=>!!f||!!(g&&p))),l.length===0){Promise.resolve().then(()=>{if(this.hls){const f=new Error("no level with compatible codecs found in manifest");this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:f,reason:f.message})}});return}t.audioTracks&&(i=t.audioTracks.filter(f=>!f.audioCodec||Nr(f.audioCodec,"audio")),Ta(i)),t.subtitles&&(s=t.subtitles,Ta(s));const c=l.slice(0);l.sort((f,g)=>f.attrs["HDCP-LEVEL"]!==g.attrs["HDCP-LEVEL"]?(f.attrs["HDCP-LEVEL"]||"")>(g.attrs["HDCP-LEVEL"]||"")?1:-1:f.bitrate!==g.bitrate?f.bitrate-g.bitrate:f.attrs["FRAME-RATE"]!==g.attrs["FRAME-RATE"]?f.attrs.decimalFloatingPoint("FRAME-RATE")-g.attrs.decimalFloatingPoint("FRAME-RATE"):f.attrs.SCORE!==g.attrs.SCORE?f.attrs.decimalFloatingPoint("SCORE")-g.attrs.decimalFloatingPoint("SCORE"):n&&f.height!==g.height?f.height-g.height:0);let d=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let f=0;f<c.length;f++)if(c[f].pathwayId===l[0].pathwayId){d=c[f];break}}this._levels=l;for(let f=0;f<l.length;f++)if(l[f]===d){this._firstLevel=f,this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${d.bitrate}`);break}const h=a&&!o,u={levels:l,audioTracks:i,subtitleTracks:s,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:a,video:o,altAudio:!h&&i.some(f=>!!f.url)};this.hls.trigger(v.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const d=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(v.ERROR,{type:q.OTHER_ERROR,details:D.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:d,reason:d.message}),h)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,o=t[e],a=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,i===e&&o.details&&s&&n===a)return;this.log(`Switching to level ${e}${a?" with Pathway "+a:""} from level ${i}${n?" with Pathway "+n:""}`);const l=Ce({},o,{level:e,maxBitrate:o.maxBitrate,attrs:o.attrs,uri:o.uri,urlId:o.urlId});delete l._attrs,delete l._urlId,this.hls.trigger(v.LEVEL_SWITCHING,l);const c=o.details;if(!c||c.live){const d=this.switchParams(o.uri,s==null?void 0:s.details);this.loadPlaylist(d)}}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){const e=this.hls.config.startLevel;return e!==void 0?e:this._firstLevel}else return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===ae.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragLoaded(e,{frag:t}){if(t!==void 0&&t.type===Z.MAIN){const i=this._levels[t.level];i!==void 0&&(i.loadError=0)}}onLevelLoaded(e,t){var i;const{level:s,details:n}=t,o=this._levels[s];if(!o){var a;this.warn(`Invalid level index ${s}`),(a=t.deliveryDirectives)!=null&&a.skip&&(n.deltaUpdateFailed=!0);return}s===this.currentLevelIndex?(o.fragmentError===0&&(o.loadError=0),this.playlistLoaded(s,t,o.details)):(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}onAudioTrackSwitched(e,t){const i=this.currentLevel;if(!i)return;const s=this.hls.audioTracks[t.id].groupId;if(i.audioGroupIds&&i.audioGroupId!==s){let n=-1;for(let o=0;o<i.audioGroupIds.length;o++)if(i.audioGroupIds[o]===s){n=o;break}n!==-1&&n!==i.urlId&&(i.urlId=n,this.canLoad&&this.startLoad())}}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){const s=i.urlId;let n=i.uri;if(e)try{n=e.addDirectives(n)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}const o=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${o?" Pathway "+o:""} URI ${s+1}/${i.url.length} ${n}`),this.clearTimer(),this.hls.trigger(v.LEVEL_LOADING,{url:n,level:t,id:s,deliveryDirectives:e||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,t){const i=(n,o)=>o!==t,s=this._levels.filter((n,o)=>o!==e?!0:n.url.length>1&&t!==void 0?(n.url=n.url.filter(i),n.audioGroupIds&&(n.audioGroupIds=n.audioGroupIds.filter(i)),n.textGroupIds&&(n.textGroupIds=n.textGroupIds.filter(i)),n.urlId=0,!0):(this.steering&&this.steering.removeLevel(n),!1));this.hls.trigger(v.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){t.forEach((i,s)=>{const{details:n}=i;n!=null&&n.fragments&&n.fragments.forEach(o=>{o.level=s})}),this._levels=t}}function Ps(r,e,t){t&&(e==="audio"?(r.audioGroupIds||(r.audioGroupIds=[]),r.audioGroupIds[r.url.length-1]=t):e==="text"&&(r.textGroupIds||(r.textGroupIds=[]),r.textGroupIds[r.url.length-1]=t))}function Ta(r){const e={};r.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}var ke={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Dh{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=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=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(){const{hls:e}=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.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let s=i.length;s--;){const n=i[s];if(!n)break;const o=n.end;if(n.start<=e&&o!==null&&e<=o)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:i}=this,s=Object.keys(i);for(let n=s.length;n--;){const o=i[s[n]];if((o==null?void 0:o.body.type)===t&&o.buffered){const a=o.body;if(a.start<=e&&e<=a.end)return a}}return null}detectEvictedFragments(e,t,i,s){this.timeRanges&&(this.timeRanges[e]=t);const n=(s==null?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const a=this.fragments[o];if(!a||n>=a.body.sn)return;if(!a.buffered&&!a.loaded){a.body.type===i&&this.removeFragment(a.body);return}const l=a.range[e];l&&l.time.some(c=>{const d=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return d&&this.removeFragment(a.body),d})})}detectPartialFragments(e){const t=this.timeRanges,{frag:i,part:s}=e;if(!t||i.sn==="initSegment")return;const n=pi(i),o=this.fragments[n];if(!o)return;const a=!i.relurl;Object.keys(t).forEach(l=>{const c=i.elementaryStreams[l];if(!c)return;const d=t[l],h=a||c.partial===!0;o.range[l]=this.getBufferedTimes(i,s,h,d)}),o.loaded=null,Object.keys(o.range).length?(o.buffered=!0,o.body.endList&&(this.endListFragments[o.body.type]=o),Os(o)||this.removeParts(i.sn-1,i.type)):this.removeFragment(o.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=i.filter(s=>s.fragment.sn>=e))}fragBuffered(e,t){const i=pi(e);let s=this.fragments[i];!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)}getBufferedTimes(e,t,i,s){const n={time:[],partial:i},o=e.start,a=e.end,l=e.minEndPTS||a,c=e.maxStartPTS||o;for(let d=0;d<s.length;d++){const h=s.start(d)-this.bufferPadding,u=s.end(d)+this.bufferPadding;if(c>=h&&l<=u){n.time.push({startPTS:Math.max(o,s.start(d)),endPTS:Math.min(a,s.end(d))});break}else if(o<u&&a>h)n.partial=!0,n.time.push({startPTS:Math.max(o,s.start(d)),endPTS:Math.min(a,s.end(d))});else if(a<=h)break}return n}getPartialFragment(e){let t=null,i,s,n,o=0;const{bufferPadding:a,fragments:l}=this;return Object.keys(l).forEach(c=>{const d=l[c];d&&Os(d)&&(s=d.body.start-a,n=d.body.end+a,e>=s&&e<=n&&(i=Math.min(e-s,n-e),o<=i&&(t=d.body,o=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Os(t))}getState(e){const t=pi(e),i=this.fragments[t];return i?i.buffered?Os(i)?ke.PARTIAL:ke.OK:ke.APPENDING:ke.NOT_LOADED}isTimeBuffered(e,t,i){let s,n;for(let o=0;o<i.length;o++){if(s=i.start(o)-this.bufferPadding,n=i.end(o)+this.bufferPadding,e>=s&&t<=n)return!0;if(t<=s)return!1}return!1}onFragLoaded(e,t){const{frag:i,part:s}=t;if(i.sn==="initSegment"||i.bitrateTest)return;const n=s?null:t,o=pi(i);this.fragments[o]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:s,timeRanges:n}=t;if(i.sn==="initSegment")return;const o=i.type;if(s){let a=this.activePartLists[o];a||(this.activePartLists[o]=a=[]),a.push(s)}this.timeRanges=n,Object.keys(n).forEach(a=>{const l=n[a];this.detectEvictedFragments(a,l,o,s)})}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=pi(e);return!!this.fragments[t]}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,s,n){s&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const a=this.fragments[o];if(!a)return;const l=a.body;l.type!==i||s&&!l.gap||l.start<t&&l.end>e&&(a.buffered||n)&&this.removeFragment(l)})}removeFragment(e){const t=pi(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const s=e.sn;this.activePartLists[e.type]=i.filter(n=>n.fragment.sn!==s)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function Os(r){var e,t,i;return r.buffered&&(r.body.gap||((e=r.range.video)==null?void 0:e.partial)||((t=r.range.audio)==null?void 0:t.partial)||((i=r.range.audiovideo)==null?void 0:i.partial))}function pi(r){return`${r.type}_${r.level}_${r.urlId}_${r.sn}`}const Ea=Math.pow(2,17);class kh{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){const i=e.url;if(!i)return Promise.reject(new wt({type:q.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const s=this.config,n=s.fLoader,o=s.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap){l(Ia(e));return}const c=this.loader=e.loader=n?new n(s):new o(s),d=Sa(e),h=ba(s.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Ea};e.stats=c.stats,c.load(d,u,{onSuccess:(f,g,p,m)=>{this.resetLoader(e,c);let A=f.data;p.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(A.slice(0,16)),A=A.slice(16)),a({frag:e,part:null,payload:A,networkDetails:m})},onError:(f,g,p,m)=>{this.resetLoader(e,c),l(new wt({type:q.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:je({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:m}))},onAbort:(f,g,p)=>{this.resetLoader(e,c),l(new wt({type:q.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,c),l(new wt({type:q.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:p,stats:f}))},onProgress:(f,g,p,m)=>{t&&t({frag:e,part:null,payload:p,networkDetails:m})}})})}loadPart(e,t,i){this.abort();const s=this.config,n=s.fLoader,o=s.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Ia(e,t));return}const c=this.loader=e.loader=n?new n(s):new o(s),d=Sa(e,t),h=ba(s.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ea};t.stats=c.stats,c.load(d,u,{onSuccess:(f,g,p,m)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const A={frag:e,part:t,payload:f.data,networkDetails:m};i(A),a(A)},onError:(f,g,p,m)=>{this.resetLoader(e,c),l(new wt({type:q.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:je({url:d.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:m}))},onAbort:(f,g,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new wt({type:q.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,c),l(new wt({type:q.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(e,t){const i=e.stats,s=t.stats,n=s.total;if(i.loaded+=s.loaded,n){const l=Math.round(e.duration/t.duration),c=Math.min(Math.round(i.loaded/n),l),h=(l-c)*Math.round(i.loaded/c);i.total=i.loaded+h}else i.total=Math.max(i.loaded,i.total);const o=i.loading,a=s.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 Sa(r,e=null){const t=e||r,i={frag:r,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},s=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(W(s)&&W(n)){var o;let a=s,l=n;if(r.sn==="initSegment"&&((o=r.decryptdata)==null?void 0:o.method)==="AES-128"){const c=n-s;c%16&&(l=n+(16-c%16)),s!==0&&(i.resetIV=!0,a=s-16)}i.rangeStart=a,i.rangeEnd=l}return i}function Ia(r,e){const t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),i={type:q.MEDIA_ERROR,details:D.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(i.part=e),(e||r).stats.aborted=!0,new wt(i)}class wt extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Ph{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const t in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[t].loader;if(i){if(e&&e!==i.context.frag.type)return;i.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=D.KEY_LOAD_ERROR,i,s,n){return new wt({type:q.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:s})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:s}=e;for(let n=0;n<t.length;n++){const o=t[n];if(s<=o.cc&&(i==="initSegment"||o.sn==="initSegment"||i<o.sn)){this.emeController.selectKeySystemFormat(o).then(a=>{o.setKeyFormat(a)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,c))}const o=n.uri;if(!o)return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${o}"`)));let a=this.keyUriToKeyInfo[o];if((i=a)!=null&&i.decryptdata.key)return n.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});if((s=a)!=null&&s.keyLoadPromise){var l;switch((l=a.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then(c=>(n.key=c.keyInfo.decryptdata.key,{frag:e,keyInfo:a}))}}switch(a=this.keyUriToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const s=this.emeController.loadKey(i);if(s)return(e.keyLoadPromise=s.then(n=>(e.mediaKeySessionContext=n,i))).catch(n=>{throw e.keyLoadPromise=null,n})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,s=i.loader,n=new s(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((o,a)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=i.keyLoadPolicy.default,d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,f,g,p)=>{const{frag:m,keyInfo:A,url:x}=g;if(!m.decryptdata||A!==this.keyUriToKeyInfo[x])return a(this.createKeyLoadError(m,D.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));A.decryptdata.key=m.decryptdata.key=new Uint8Array(u.data),m.keyLoader=null,A.loader=null,o({frag:m,keyInfo:A})},onError:(u,f,g,p)=>{this.resetLoader(f),a(this.createKeyLoadError(t,D.KEY_LOAD_ERROR,new Error(`HTTP Error ${u.code} loading key ${u.text}`),g,je({url:l.url,data:void 0},u)))},onTimeout:(u,f,g)=>{this.resetLoader(f),a(this.createKeyLoadError(t,D.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(u,f,g)=>{this.resetLoader(f),a(this.createKeyLoadError(t,D.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};n.load(l,d,h)})}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[s],n&&n.destroy()}}class Oh{constructor(){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?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}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(){}}const Mh={length:0,start:()=>0,end:()=>0};class fe{static isBuffered(e,t){try{if(e){const i=fe.getBuffered(e);for(let s=0;s<i.length;s++)if(t>=i.start(s)&&t<=i.end(s))return!0}}catch{}return!1}static bufferInfo(e,t,i){try{if(e){const s=fe.getBuffered(e),n=[];let o;for(o=0;o<s.length;o++)n.push({start:s.start(o),end:s.end(o)});return this.bufferedInfo(n,t,i)}}catch{}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.sort(function(c,d){const h=c.start-d.start;return h||d.end-c.end});let s=[];if(i)for(let c=0;c<e.length;c++){const d=s.length;if(d){const h=s[d-1].end;e[c].start-h<i?e[c].end>h&&(s[d-1].end=e[c].end):s.push(e[c])}else s.push(e[c])}else s=e;let n=0,o,a=t,l=t;for(let c=0;c<s.length;c++){const d=s[c].start,h=s[c].end;if(t+i>=d&&t<h)a=d,l=h,n=l-t;else if(t+i<d){o=d;break}}return{len:n,start:a||0,end:l||0,nextStart:o}}static getBuffered(e){try{return e.buffered}catch(t){return C.log("failed to get media.buffered",t),Mh}}}class qr{constructor(e,t,i,s=0,n=-1,o=!1){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=Ms(),this.buffering={audio:Ms(),video:Ms(),audiovideo:Ms()},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=n,this.partial=o}}function Ms(){return{start:0,executeStart:0,executeEnd:0,end:0}}function Ca(r,e){let t=null;for(let i=0,s=r.length;i<s;i++){const n=r[i];if(n&&n.cc===e){t=n;break}}return t}function Fh(r,e,t){return!!(e.details&&(t.endCC>t.startCC||r&&r.cc<t.startCC))}function Nh(r,e,t=0){const i=r.fragments,s=e.fragments;if(!s.length||!i.length){C.log("No fragments to align");return}const n=Ca(i,s[0].cc);if(!n||n&&!n.startPTS){C.log("No frag in previous level to align on");return}return n}function wa(r,e){if(r){const t=r.start+e;r.start=r.startPTS=t,r.endPTS=t+r.duration}}function Zr(r,e){const t=e.fragments;for(let i=0,s=t.length;i<s;i++)wa(t[i],r);e.fragmentHint&&wa(e.fragmentHint,r),e.alignedSliding=!0}function Bh(r,e,t){e&&(Uh(r,t,e),!t.alignedSliding&&e.details&&Hh(t,e.details),!t.alignedSliding&&e.details&&!t.skippedSegments&&ma(e.details,t))}function Uh(r,e,t){if(Fh(r,t,e)){const i=Nh(t.details,e);i&&W(i.start)&&(C.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),Zr(i.start,e))}}function Hh(r,e){if(!e.fragments.length||!r.hasProgramDateTime||!e.hasProgramDateTime)return;const t=e.fragments[0].programDateTime,i=r.fragments[0].programDateTime,s=(i-t)/1e3+e.fragments[0].start;s&&W(s)&&(C.log(`Adjusting PTS using programDateTime delta ${i-t}ms, sliding:${s.toFixed(3)} ${r.url} `),Zr(s,r))}function La(r,e){if(!r.hasProgramDateTime||!e.hasProgramDateTime)return;const t=r.fragments,i=e.fragments;if(!t.length||!i.length)return;const s=Math.round(i.length/2)-1,n=i[s],o=Ca(t,n.cc)||t[Math.round(t.length/2)-1],a=n.programDateTime,l=o.programDateTime;if(a===null||l===null)return;const c=(l-a)/1e3-(o.start-n.start);Zr(c,r)}class Gh{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class Vh{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function jh(r){const e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?_t(r,0,e-t):r}class zh{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){const t=new DataView(e),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=t.getUint32(s*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],n=i[1],o=i[2],a=i[3],l=this.invSubMix,c=l[0],d=l[1],h=l[2],u=l[3],f=new Uint32Array(256);let g=0,p=0,m=0;for(m=0;m<256;m++)m<128?f[m]=m<<1:f[m]=m<<1^283;for(m=0;m<256;m++){let A=p^p<<1^p<<2^p<<3^p<<4;A=A>>>8^A&255^99,e[g]=A,t[A]=g;const x=f[g],b=f[x],y=f[b];let T=f[A]*257^A*16843008;s[g]=T<<24|T>>>8,n[g]=T<<16|T>>>16,o[g]=T<<8|T>>>24,a[g]=T,T=y*16843009^b*65537^x*257^g*16843008,c[A]=T<<24|T>>>8,d[A]=T<<16|T>>>16,h[A]=T<<8|T>>>24,u[A]=T,g?(g=x^f[f[f[y^x]]],p^=f[f[p]]):g=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,s=0;for(;s<t.length&&i;)i=t[s]===this.key[s],s++;if(i)return;this.key=t;const n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);const o=this.ksRows=(n+6+1)*4;let a,l;const c=this.keySchedule=new Uint32Array(o),d=this.invKeySchedule=new Uint32Array(o),h=this.sBox,u=this.rcon,f=this.invSubMix,g=f[0],p=f[1],m=f[2],A=f[3];let x,b;for(a=0;a<o;a++){if(a<n){x=c[a]=t[a];continue}b=x,a%n===0?(b=b<<8|b>>>24,b=h[b>>>24]<<24|h[b>>>16&255]<<16|h[b>>>8&255]<<8|h[b&255],b^=u[a/n|0]<<24):n>6&&a%n===4&&(b=h[b>>>24]<<24|h[b>>>16&255]<<16|h[b>>>8&255]<<8|h[b&255]),c[a]=x=(c[a-n]^b)>>>0}for(l=0;l<o;l++)a=o-l,l&3?b=c[a]:b=c[a-4],l<4||a<=4?d[l]=b:d[l]=g[h[b>>>24]]^p[h[b>>>16&255]]^m[h[b>>>8&255]]^A[h[b&255]],d[l]=d[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const s=this.keySize+6,n=this.invKeySchedule,o=this.invSBox,a=this.invSubMix,l=a[0],c=a[1],d=a[2],h=a[3],u=this.uint8ArrayToUint32Array_(i);let f=u[0],g=u[1],p=u[2],m=u[3];const A=new Int32Array(e),x=new Int32Array(A.length);let b,y,T,E,S,R,w,I,O,P,B,J,H,V;const j=this.networkToHostOrderSwap;for(;t<A.length;){for(O=j(A[t]),P=j(A[t+1]),B=j(A[t+2]),J=j(A[t+3]),S=O^n[0],R=J^n[1],w=B^n[2],I=P^n[3],H=4,V=1;V<s;V++)b=l[S>>>24]^c[R>>16&255]^d[w>>8&255]^h[I&255]^n[H],y=l[R>>>24]^c[w>>16&255]^d[I>>8&255]^h[S&255]^n[H+1],T=l[w>>>24]^c[I>>16&255]^d[S>>8&255]^h[R&255]^n[H+2],E=l[I>>>24]^c[S>>16&255]^d[R>>8&255]^h[w&255]^n[H+3],S=b,R=y,w=T,I=E,H=H+4;b=o[S>>>24]<<24^o[R>>16&255]<<16^o[w>>8&255]<<8^o[I&255]^n[H],y=o[R>>>24]<<24^o[w>>16&255]<<16^o[I>>8&255]<<8^o[S&255]^n[H+1],T=o[w>>>24]<<24^o[I>>16&255]<<16^o[S>>8&255]<<8^o[R&255]^n[H+2],E=o[I>>>24]<<24^o[S>>16&255]<<16^o[R>>8&255]<<8^o[w&255]^n[H+3],x[t]=j(b^f),x[t+1]=j(E^g),x[t+2]=j(T^p),x[t+3]=j(y^m),f=O,g=P,p=B,m=J,t=t+4}return x.buffer}}const Wh=16;class Jr{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,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.useSoftware=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.subtle===null&&(this.useSoftware=!0)}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(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?jh(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i){return this.useSoftware?new Promise((s,n)=>{this.softwareDecrypt(new Uint8Array(e),t,i);const o=this.flush();o?s(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i)}softwareDecrypt(e,t,i){const{currentIV:s,currentResult:n,remainderData:o}=this;this.logOnce("JS AES decrypt"),o&&(e=$t(o,e),this.remainderData=null);const a=this.getValidChunk(e);if(!a.length)return null;s&&(i=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new zh),l.expandKey(t);const c=n;return this.currentResult=l.decrypt(a.buffer,0,i),this.currentIV=_t(a,-16).buffer,c||null}webCryptoDecrypt(e,t,i){const s=this.subtle;return(this.key!==t||!this.fastAesKey)&&(this.key=t,this.fastAesKey=new Vh(s,t)),this.fastAesKey.expandKey().then(n=>s?(this.logOnce("WebCrypto AES decrypt"),new Gh(s,new Uint8Array(i)).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(C.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i)))}onWebCryptoError(e,t,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i);const s=this.flush();if(s)return s.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%Wh;return i!==e.length&&(t=_t(e,0,i),this.remainderData=_t(e,i)),t}logOnce(e){this.logEnabled&&(C.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Yh={toString:function(r){let e="";const t=r.length;for(let i=0;i<t;i++)e+=`[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;return e}},M={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"};class Qr extends Oh{constructor(e,t,i,s,n){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=M.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=n,this.logPrefix=s,this.log=C.log.bind(C,`${s}:`),this.warn=C.warn.bind(C,`${s}:`),this.hls=e,this.fragmentLoader=new kh(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Jr(e.config),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const 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=M.STOPPED}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;const i=t.partList;if(i!=null&&i.length){const n=i[i.length-1];return fe.isBuffered(this.media,n.start+n.duration/2)}const s=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(s)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levels[this.levelLastLoaded])==null?void 0:e.details}}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),i.addEventListener("seeking",this.onvseeking),i.addEventListener("ended",this.onvended);const s=this.config;this.levels&&s.autoStartLoad&&this.state===M.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(){const e=this.media;e!=null&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:t,media:i,mediaBuffer:s,state:n}=this,o=i?i.currentTime:0,a=fe.bufferInfo(s||i,o,e.maxBufferHole);if(this.log(`media seeking to ${W(o)?o.toFixed(3):o}, state: ${n}`),this.state===M.ENDED)this.resetLoadingState();else if(t){const l=e.maxFragLookUpTolerance,c=t.start-l,d=t.start+t.duration+l;if(!a.len||d<a.start||c>a.end){const h=o>d;(o<c||h)&&(h&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}i&&(this.fragmentTracker.removeFragmentsInRange(o,1/0,this.playlistType,!0),this.lastCurrentTime=o),!this.loadedmetadata&&!a.len&&(this.nextLoadPosition=this.startPosition=o),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.stopLoad(),super.onHandlerDestroying()}onHandlerDestroyed(){this.state=M.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._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const s=n=>{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${n.part?" p: "+n.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,i,s).then(n=>{if(!n)return;const o=this.state;if(this.fragContextChanged(e)){(o===M.FRAG_LOADING||!this.fragCurrent&&o===M.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=M.IDLE);return}"payload"in n&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(v.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===M.STOPPED||this.state===M.ERROR||(this.warn(n),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===ke.APPENDING){const n=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,n),a=Math.max(e.duration,o?o.len:this.config.maxBufferLength);this.reduceMaxBufferLength(a)&&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)===ke.PARTIAL&&i.removeFragment(e))}flushMainBuffer(e,t,i=null){if(!(e-t))return;const s={startOffset:e,endOffset:t,type:i};this.hls.trigger(v.BUFFER_FLUSHING,s)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{if(!i||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:s}=this,{payload:n}=i,o=e.decryptdata;if(n&&n.byteLength>0&&o&&o.key&&o.iv&&o.method==="AES-128"){const a=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),o.key.buffer,o.iv.buffer).catch(l=>{throw s.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:e}),l}).then(l=>{const c=self.performance.now();return s.trigger(v.FRAG_DECRYPTED,{frag:e,payload:l,stats:{tstart:a,tdecrypt:c}}),i.payload=l,i})}return i}).then(i=>{const{fragCurrent:s,hls:n,levels:o}=this;if(!o)throw new Error("init load aborted, missing levels");const a=e.stats;this.state=M.IDLE,t.fragmentError=0,e.data=new Uint8Array(i.payload),a.parsing.start=a.buffering.start=self.performance.now(),a.parsing.end=a.buffering.end=self.performance.now(),i.frag===s&&n.trigger(v.FRAG_BUFFERED,{stats:a,frag:s,part:null,id:e.type}),this.tick()}).catch(i=>{this.state===M.STOPPED||this.state===M.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.level!==t.level||e.sn!==t.sn||e.urlId!==t.urlId}fragBufferedComplete(e,t){var i,s,n,o;const a=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===Z.MAIN?"level":"track"} ${e.level} (frag:[${((i=e.startPTS)!=null?i:NaN).toFixed(3)}-${((s=e.endPTS)!=null?s:NaN).toFixed(3)}] > buffer:${a?Yh.toString(fe.getBuffered(a)):"(detached)"})`),this.state=M.IDLE,a&&(!this.loadedmetadata&&e.type==Z.MAIN&&a.buffered.length&&((n=this.fragCurrent)==null?void 0:n.sn)===((o=this.fragPrevious)==null?void 0:o.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:s,partsLoaded:n}=e,o=!n||n.length===0||n.some(l=>!l),a=new qr(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!o);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,s){var n;const o=t==null?void 0: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)?(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${e.level}`),this.state=M.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(v.KEY_LOADED,d),this.state===M.KEY_LOADING&&(this.state=M.IDLE),d}),this.hls.trigger(v.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&o.encryptedFragments.length&&this.keyLoader.loadClear(e,o.encryptedFragments),i=Math.max(e.start,i||0),this.config.lowLatencyMode&&e.sn!=="initSegment"){const d=o.partList;if(d&&s){i>e.end&&o.fragmentHint&&(e=o.fragmentHint);const h=this.getNextPart(d,e,i);if(h>-1){const u=d[h];this.log(`Loading part sn: ${e.sn} p: ${u.index} cc: ${e.cc} of playlist [${o.startSN}-${o.endSN}] parts [0-${h}-${d.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=u.start+u.duration,this.state=M.FRAG_LOADING;let f;return a?f=a.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,u,t,s)).catch(g=>this.handleFragLoadError(g)):f=this.doFragPartsLoad(e,u,t,s).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(v.FRAG_LOADING,{frag:e,part:u,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!e.url||this.loadedEndOfParts(d,i))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${o?"of ["+o.startSN+"-"+o.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),W(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=M.FRAG_LOADING;const l=this.config.progressive;let c;return l&&a?c=a.then(d=>!d||this.fragContextChanged(d==null?void 0:d.frag)?null:this.fragmentLoader.load(e,s)).catch(d=>this.handleFragLoadError(d)):c=Promise.all([this.fragmentLoader.load(e,l?s:void 0),a]).then(([d])=>(!l&&d&&s&&s(d),d)).catch(d=>this.handleFragLoadError(d)),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")):c}doFragPartsLoad(e,t,i,s){return new Promise((n,o)=>{var a;const l=[],c=(a=i.details)==null?void 0:a.partList,d=h=>{this.fragmentLoader.loadPart(e,h,s).then(u=>{l[h.index]=u;const f=u.part;this.hls.trigger(v.FRAG_LOADED,u);const g=va(i,e.sn,h.index+1)||ya(c,e.sn,h.index+1);if(g)d(g);else return n({frag:e,part:f,partsLoaded:l})}).catch(o)};d(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===D.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(v.ERROR,t)}else this.hls.trigger(v.ERROR,{type:q.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==M.PARSING){!this.fragCurrent&&this.state!==M.STOPPED&&this.state!==M.ERROR&&(this.state=M.IDLE);return}const{frag:i,part:s,level:n}=t,o=self.performance.now();i.stats.parsing.end=o,s&&(s.stats.parsing.end=o),this.updateLevelTiming(i,s,n,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:s,sn:n,part:o}=e;if(!(t!=null&&t[s]))return this.warn(`Levels object was unset while buffering fragment ${n} of level ${s}. The current chunk will not be buffered.`),null;const a=t[s],l=o>-1?va(a,n,o):null,c=l?l.fragment:xh(a,n,i);return c?(i&&i!==c&&(c.stats=i.stats),{frag:c,part:l,level:a}):null}bufferFragmentData(e,t,i,s){var n;if(!e||this.state!==M.PARSING)return;const{data1:o,data2:a}=e;let l=o;if(o&&a&&(l=$t(o,a)),!((n=l)!=null&&n.length))return;const c={type:e.type,frag:t,part:i,chunkMeta:s,parent:t.type,data:l};this.hls.trigger(v.BUFFER_APPENDING,c),e.dropped&&e.independent&&!i&&this.flushBufferGap(t)}flushBufferGap(e){const t=this.media;if(!t)return;if(!fe.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,s=fe.bufferInfo(t,i,0),n=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),a=Math.max(Math.min(e.start-o,s.end-o),i+o);e.start-a>o&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){const i=this.getLoadPosition();return W(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){const{config:{maxBufferHole:s}}=this,n=fe.bufferInfo(e,t,s);if(n.len===0&&n.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(t,i);if(o&&n.nextStart<o.end)return fe.bufferInfo(e,t,Math.max(n.nextStart,s))}return n}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e){const t=this.config,i=e||t.maxBufferLength;return t.maxMaxBufferLength>=i?(t.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${t.maxMaxBufferLength}s`),!0):!1}getAppendedFrag(e,t=Z.MAIN){const i=this.fragmentTracker.getAppendedFrag(e,Z.MAIN);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,s=i.length;if(!s)return null;const{config:n}=this,o=i[0].start;let a;if(t.live){const l=n.initialLiveManifestSize;if(s<l)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${l})`),null;!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1&&(a=this.getInitialLiveFragment(t,i),this.startPosition=a?this.hls.liveSyncPosition||a.start:e)}else e<=o&&(a=i[0]);if(!a){const l=n.lowLatencyMode?t.partEnd:t.fragmentEnd;a=this.getFragmentAtPosition(e,l,t)}return this.mapToInitFragWhenRequired(a)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===ke.OK||i===ke.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,s,n){const o=e.gap,a=this.getNextFragment(this.nextLoadPosition,t);if(a===null)return a;if(e=a,o&&e&&!e.gap&&i.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s);if(l!==null&&i.len+l.len>=n)return this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let s=-1,n=!1,o=!0;for(let a=0,l=e.length;a<l;a++){const c=e[a];if(o=o&&!c.independent,s>-1&&i<c.start)break;const d=c.loaded;d?s=-1:(n||c.independent||o)&&c.fragment===t&&(s=a),n=d}return s}loadedEndOfParts(e,t){const i=e[e.length-1];return i&&t>i.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let s=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=Eh(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){const o=t[n-e.startSN];i.cc===o.cc&&(s=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=Ih(t,i.cc),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const n=this.hls.liveSyncPosition;n!==null&&(s=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){const{config:s}=this;let{fragPrevious:n}=this,{fragments:o,endSN:a}=i;const{fragmentHint:l}=i,c=s.maxFragLookUpTolerance,d=i.partList,h=!!(s.lowLatencyMode&&d!=null&&d.length&&l);h&&l&&!this.bitrateTest&&(o=o.concat(l),a=l.sn);let u;if(e<t){const f=e>t-c?0:c;u=Qi(n,o,e,f)}else u=o[o.length-1];if(u){const f=u.sn-i.startSN,g=this.fragmentTracker.getState(u);if((g===ke.OK||g===ke.PARTIAL&&u.gap)&&(n=u),n&&u.sn===n.sn&&(!h||d[0].fragment.sn>u.sn)&&n&&u.level===n.level){const m=o[f+1];u.sn<a&&this.fragmentTracker.getState(m)!==ke.OK?u=m:u=null}}return u}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,n=i.currentTime,o=e.fragments[0].start,a=e.edge,l=n>=o-t.maxFragLookUpTolerance&&n<=a;if(s!==null&&i.duration>s&&(n<s||!l)){const c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!l&&i.readyState<4||n<a-c)&&(this.loadedmetadata||(this.nextLoadPosition=s),i.readyState&&(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${s.toFixed(3)}`),i.currentTime=s))}}alignPlaylists(e,t){const{levels:i,levelLastLoaded:s,fragPrevious:n}=this,o=s!==null?i[s]:null,a=e.fragments.length;if(!a)return this.warn("No fragments in live playlist"),0;const l=e.fragments[0].start,c=!t,d=e.alignedSliding&&W(l);if(c||!d&&!l){Bh(n,o,e);const h=e.fragments[0].start;return this.log(`Live playlist sliding: ${h.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${n?n.sn:"na"} fragments: ${a}`),h}return l}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;if(i<t&&(i=-1),i===-1||this.lastCurrentTime===-1){const s=this.startTimeOffset!==null,n=s?this.startTimeOffset:e.startTimeOffset;n!==null&&W(n)?(i=t+n,n<0&&(i+=e.totalduration),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Start time offset ${n} found in ${s?"multivariant":"media"} playlist, adjust startPosition to ${i}`),this.startPosition=i):e.live?i=this.hls.liveSyncPosition||t:this.startPosition=i=0,this.lastCurrentTime=i}this.nextLoadPosition=i}getLoadPosition(){const{media:e}=this;let t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&e.sn!=="initSegment"&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==M.FRAG_LOADING_WAITING_RETRY)&&(this.state=M.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const d=this.getCurrentContext(t.chunkMeta);d&&(t.frag=d.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var s;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(s=this.fragCurrent)==null?void 0:s.url}`);return}const n=t.details===D.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction,{action:a,retryCount:l=0,retryConfig:c}=o||{};if(o&&a===Ye.RetryRequest&&c){this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition);const d=Wr(c,l);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${l+1}/${c.maxNumRetry} in ${d}ms`),o.resolved=!0,this.retryDate=self.performance.now()+d,this.state=M.FRAG_LOADING_WAITING_RETRY}else c&&o?(this.resetFragmentErrors(e),l<c.maxNumRetry?n||(o.resolved=!0):C.warn(`${t.details} reached or exceeded max retry (${l})`)):this.state=M.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===M.PARSING||this.state===M.PARSED){const t=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,t),s=i&&i.len>.5;s&&this.reduceMaxBufferLength(i.len);const n=!s;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${t} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===Z.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==M.STOPPED&&(this.state=M.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const s=fe.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,i),this.state===M.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=M.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=this.levels?this.levels[e].details:null;t!=null&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(e.level),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){var n;const o=i.details;if(!o){this.warn("level.details undefined");return}if(Object.keys(e.elementaryStreams).reduce((l,c)=>{const d=e.elementaryStreams[c];if(d){const h=d.endPTS-d.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${h})`),l||!1;const u=s?0:pa(o,e,d.startPTS,d.endPTS,d.startDTS,d.endDTS);return this.hls.trigger(v.LEVEL_PTS_UPDATED,{details:o,level:i,drift:u,type:c,frag:e,start:d.startPTS,end:d.endPTS}),!0}return l},!1))i.fragmentError=0;else if(((n=this.transmuxer)==null?void 0:n.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of level ${i.id} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=M.PARSED,this.hls.trigger(v.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.resetTransmuxer(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function Ra(){return self.SourceBuffer||self.WebKitSourceBuffer}function Kh(){const r=Ls();if(!r)return!1;const e=Ra(),t=r&&typeof r.isTypeSupported=="function"&&r.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),i=!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function";return!!t&&!!i}function Xh(){var r;const e=Ra();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}function qh(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Zh(){const r=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(r);return{worker:new self.Worker(e),objectURL:e}}function Jh(r){const e=new self.URL(r,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}function pt(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Da{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,s){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!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=$t(this.cachedData,e),this.cachedData=null);let i=Ss(e,0),s=i?i.length:0,n;const o=this._audioTrack,a=this._id3Track,l=i?Pd(i):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&W(l))&&(this.basePTS=Qh(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:lt.audioId3,duration:Number.POSITIVE_INFINITY});s<c;){if(this.canParse(e,s)){const d=this.appendFrame(o,e,s);d?(this.frameIndex++,this.lastPTS=d.sample.pts,s+=d.length,n=s):s=c}else kd(e,s)?(i=Ss(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:lt.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,n=s):s++;if(s===c&&n!==c){const d=_t(e,n);this.cachedData?this.cachedData=$t(this.cachedData,d):this.cachedData=d}}return{audioTrack:o,videoTrack:pt(),id3Track:a,textTrack:pt()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:pt(),id3Track:this._id3Track,textTrack:pt()}}destroy(){}}const Qh=(r,e,t)=>{if(W(r))return r*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};function _h(r,e,t,i){let s,n,o,a;const l=navigator.userAgent.toLowerCase(),c=i,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=((e[t+2]&192)>>>6)+1;const h=(e[t+2]&60)>>>2;if(h>d.length-1){r.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!0,reason:`invalid ADTS sampling index:${h}`});return}return o=(e[t+2]&1)<<2,o|=(e[t+3]&192)>>>6,C.log(`manifest codec:${i}, ADTS type:${s}, samplingIndex:${h}`),/firefox/i.test(l)?h>=6?(s=5,a=new Array(4),n=h-3):(s=2,a=new Array(2),n=h):l.indexOf("android")!==-1?(s=2,a=new Array(2),n=h):(s=5,a=new Array(4),i&&(i.indexOf("mp4a.40.29")!==-1||i.indexOf("mp4a.40.5")!==-1)||!i&&h>=6?n=h-3:((i&&i.indexOf("mp4a.40.2")!==-1&&(h>=6&&o===1||/vivaldi/i.test(l))||!i&&o===1)&&(s=2,a=new Array(2)),n=h)),a[0]=s<<3,a[0]|=(h&14)>>1,a[1]|=(h&1)<<7,a[1]|=o<<3,s===5&&(a[1]|=(n&14)>>1,a[2]=(n&1)<<7,a[2]|=8,a[3]=0),{config:a,samplerate:d[h],channelCount:o,codec:"mp4a.40."+s,manifestCodec:c}}function ka(r,e){return r[e]===255&&(r[e+1]&246)===240}function Pa(r,e){return r[e+1]&1?7:9}function _r(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function $h(r,e){return e+5<r.length}function Fs(r,e){return e+1<r.length&&ka(r,e)}function eu(r,e){return $h(r,e)&&ka(r,e)&&_r(r,e)<=r.length-e}function tu(r,e){if(Fs(r,e)){const t=Pa(r,e);if(e+t>=r.length)return!1;const i=_r(r,e);if(i<=t)return!1;const s=e+i;return s===r.length||Fs(r,s)}return!1}function Oa(r,e,t,i,s){if(!r.samplerate){const n=_h(e,t,i,s);if(!n)return;r.config=n.config,r.samplerate=n.samplerate,r.channelCount=n.channelCount,r.codec=n.codec,r.manifestCodec=n.manifestCodec,C.log(`parsed codec:${r.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function Ma(r){return 9216e4/r}function iu(r,e){const t=Pa(r,e);if(e+t<=r.length){const i=_r(r,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function Fa(r,e,t,i,s){const n=Ma(r.samplerate),o=i+s*n,a=iu(e,t);let l;if(a){const{frameLength:h,headerLength:u}=a,f=u+h,g=Math.max(0,t+f-e.length);g?(l=new Uint8Array(f-u),l.set(e.subarray(t+u,e.length),0)):l=e.subarray(t+u,t+f);const p={unit:l,pts:o};return g||r.samples.push(p),{sample:p,length:f,missing:g}}const c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:o},length:c,missing:-1}}class su extends Da{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let i=(Ss(e,0)||[]).length;for(let s=e.length;i<s;i++)if(tu(e,i))return C.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return eu(e,t)}appendFrame(e,t,i){Oa(e,this.observer,t,i,e.manifestCodec);const s=Fa(e,t,i,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}}const ru=/\/emsg[-/]ID3/i;class nu{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,s){const n=this.videoTrack=pt("video",1),o=this.audioTrack=pt("audio",1),a=this.txtTrack=pt("text",1);if(this.id3Track=pt("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=Xo(e);if(l.video){const{id:c,timescale:d,codec:h}=l.video;n.id=c,n.timescale=a.timescale=d,n.codec=h}if(l.audio){const{id:c,timescale:d,codec:h}=l.audio;o.id=c,o.timescale=d,o.codec=h}a.id=Wo.text,n.sampleDuration=0,n.duration=o.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return e=e.length>16384?e.subarray(0,16384):e,re(e,["moof"]).length>0}demux(e,t){this.timeOffset=t;let i=e;const s=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=$t(this.remainderData,e));const a=Xd(i);this.remainderData=a.remainder,s.samples=a.valid||new Uint8Array}else s.samples=i;const o=this.extractID3Track(s,t);return n.samples=Zo(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(t,this.timeOffset);return i.samples=Zo(e,t),{videoTrack:t,audioTrack:pt(),id3Track:s,textTrack:pt()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const s=re(e.samples,["emsg"]);s&&s.forEach(n=>{const o=Jd(n);if(ru.test(o.schemeIdUri)){const a=W(o.presentationTime)?o.presentationTime/o.timeScale:t+o.presentationTimeDelta/o.timeScale;let l=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=o.payload;i.samples.push({data:c,len:c.byteLength,dts:a,pts:a,type:lt.emsg,duration:l})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}let Ns=null;const ou=[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],au=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],lu=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],cu=[0,1,1,4];function Na(r,e,t,i,s){if(t+24>e.length)return;const n=Ba(e,t);if(n&&t+n.frameLength<=e.length){const o=n.samplesPerFrame*9e4/n.sampleRate,a=i+s*o,l={unit:e.subarray(t,t+n.frameLength),pts:a,dts:a};return r.config=[],r.channelCount=n.channelCount,r.samplerate=n.sampleRate,r.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function Ba(r,e){const t=r[e+1]>>3&3,i=r[e+1]>>1&3,s=r[e+2]>>4&15,n=r[e+2]>>2&3;if(t!==1&&s!==0&&s!==15&&n!==3){const o=r[e+2]>>1&1,a=r[e+3]>>6,l=t===3?3-i:i===3?3:4,c=ou[l*14+s-1]*1e3,h=au[(t===3?0:t===2?1:2)*3+n],u=a===3?1:2,f=lu[t][i],g=cu[i],p=f*8*g,m=Math.floor(f*c/h+o)*g;if(Ns===null){const b=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ns=b?parseInt(b[1]):0}return!!Ns&&Ns<=87&&i===2&&c>=224e3&&a===0&&(r[e+3]=r[e+3]|128),{sampleRate:h,channelCount:u,frameLength:m,samplesPerFrame:p}}}function $r(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function Ua(r,e){return e+1<r.length&&$r(r,e)}function du(r,e){return $r(r,e)&&4<=r.length-e}function hu(r,e){if(e+1<r.length&&$r(r,e)){const i=Ba(r,e);let s=4;i!=null&&i.frameLength&&(s=i.frameLength);const n=e+s;return n===r.length||Ua(r,n)}return!1}class Ha{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(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,s=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");s.set(e.subarray(i,i+n)),this.word=new DataView(s.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);const i=this.word>>>32-t;if(e>32&&C.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)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(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const 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)}skipScalingList(e){let t=8,i=8,s;for(let n=0;n<e;n++)i!==0&&(s=this.readEG(),i=(t+s+256)%256),t=i===0?t:i}readSPS(){let e=0,t=0,i=0,s=0,n,o,a;const l=this.readUByte.bind(this),c=this.readBits.bind(this),d=this.readUEG.bind(this),h=this.readBoolean.bind(this),u=this.skipBits.bind(this),f=this.skipEG.bind(this),g=this.skipUEG.bind(this),p=this.skipScalingList.bind(this);l();const m=l();if(c(5),u(3),l(),g(),m===100||m===110||m===122||m===244||m===44||m===83||m===86||m===118||m===128){const E=d();if(E===3&&u(1),g(),g(),u(1),h())for(o=E!==3?8:12,a=0;a<o;a++)h()&&(a<6?p(16):p(64))}g();const A=d();if(A===0)d();else if(A===1)for(u(1),f(),f(),n=d(),a=0;a<n;a++)f();g(),u(1);const x=d(),b=d(),y=c(1);y===0&&u(1),u(1),h()&&(e=d(),t=d(),i=d(),s=d());let T=[1,1];if(h()&&h())switch(l()){case 1:T=[1,1];break;case 2:T=[12,11];break;case 3:T=[10,11];break;case 4:T=[16,11];break;case 5:T=[40,33];break;case 6:T=[24,11];break;case 7:T=[20,11];break;case 8:T=[32,11];break;case 9:T=[80,33];break;case 10:T=[18,11];break;case 11:T=[15,11];break;case 12:T=[64,33];break;case 13:T=[160,99];break;case 14:T=[4,3];break;case 15:T=[3,2];break;case 16:T=[2,1];break;case 255:{T=[l()<<8|l(),l()<<8|l()];break}}return{width:Math.ceil((x+1)*16-e*2-t*2),height:(2-y)*(b+1)*16-(y?2:4)*(i+s),pixelRatio:T}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class uu{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Jr(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,i){const s=e[t].unit;if(s.length<=16)return;const n=s.subarray(16,s.length-s.length%16),o=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(o).then(a=>{const l=new Uint8Array(a);s.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,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){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let s=0;for(let n=32;n<e.length-16;n+=160,s+=16)i.set(e.subarray(n,n+16),s);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let s=0;for(let n=32;n<e.length-16;n+=160,s+=16)e.set(i.subarray(s,s+16),n);return e}decryptAvcSample(e,t,i,s,n){const o=Qo(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,s)})}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){s();return}const n=e[t].units;for(;!(i>=n.length);i++){const o=n[i];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,t,i,s,o),!this.decrypter.isSync()))return}}}}const Ne=188;class Bt{constructor(e,t,i){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=e,this.config=t,this.typeSupported=i}static probe(e){const t=Bt.syncOffset(e);return t>0&&C.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),t!==-1}static syncOffset(e){const t=e.length;let i=Math.min(Ne*5,e.length-Ne)+1,s=0;for(;s<i;){let n=!1,o=-1,a=0;for(let l=s;l<t;l+=Ne)if(e[l]===71){if(a++,o===-1&&(o=l,o!==0&&(i=Math.min(o+Ne*99,e.length-Ne)+1)),n||(n=en(e,l)===0),n&&a>1&&(o===0&&a>2||l+Ne>i))return o}else{if(a)return-1;break}s++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Wo[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,s){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=Bt.createTrack("video"),this._audioTrack=Bt.createTrack("audio",s),this._id3Track=Bt.createTrack("id3"),this._txtTrack=Bt.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,this._duration=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_avcTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}demux(e,t,i=!1,s=!1){i||(this.sampleAes=null);let n;const o=this._avcTrack,a=this._audioTrack,l=this._id3Track,c=this._txtTrack;let d=o.pid,h=o.pesData,u=a.pid,f=l.pid,g=a.pesData,p=l.pesData,m=null,A=this.pmtParsed,x=this._pmtId,b=e.length;if(this.remainderData&&(e=$t(this.remainderData,e),b=e.length,this.remainderData=null),b<Ne&&!s)return this.remainderData=e,{audioTrack:a,videoTrack:o,id3Track:l,textTrack:c};const y=Math.max(0,Bt.syncOffset(e));b-=(b-y)%Ne,b<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,b,e.buffer.byteLength-b));let T=0;for(let S=y;S<b;S+=Ne)if(e[S]===71){const R=!!(e[S+1]&64),w=en(e,S),I=(e[S+3]&48)>>4;let O;if(I>1){if(O=S+5+e[S+4],O===S+Ne)continue}else O=S+4;switch(w){case d:R&&(h&&(n=mi(h))&&this.parseAVCPES(o,c,n,!1),h={data:[],size:0}),h&&(h.data.push(e.subarray(O,S+Ne)),h.size+=S+Ne-O);break;case u:if(R){if(g&&(n=mi(g)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,n);break;case"mp3":this.parseMPEGPES(a,n);break}g={data:[],size:0}}g&&(g.data.push(e.subarray(O,S+Ne)),g.size+=S+Ne-O);break;case f:R&&(p&&(n=mi(p))&&this.parseID3PES(l,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(O,S+Ne)),p.size+=S+Ne-O);break;case 0:R&&(O+=e[O]+1),x=this._pmtId=fu(e,O);break;case x:{R&&(O+=e[O]+1);const P=gu(e,O,this.typeSupported,i);d=P.avc,d>0&&(o.pid=d),u=P.audio,u>0&&(a.pid=u,a.segmentCodec=P.segmentCodec),f=P.id3,f>0&&(l.pid=f),m!==null&&!A&&(C.warn(`MPEG-TS PMT found at ${S} after unknown PID '${m}'. Backtracking to sync byte @${y} to parse all TS packets.`),m=null,S=y-188),A=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=w;break}}else T++;if(T>0){const S=new Error(`Found ${T} TS packet/s that do not start with 0x47`);this.observer.emit(v.ERROR,v.ERROR,{type:q.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:S,reason:S.message})}o.pesData=h,a.pesData=g,l.pesData=p;const E={audioTrack:a,videoTrack:o,id3Track:l,textTrack:c};return s&&this.extractRemainingSamples(E),E}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._avcTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:s,textTrack:n}=e,o=i.pesData,a=t.pesData,l=s.pesData;let c;if(o&&(c=mi(o))?(this.parseAVCPES(i,n,c,!0),i.pesData=null):i.pesData=o,a&&(c=mi(a))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,c);break;case"mp3":this.parseMPEGPES(t,c);break}t.pesData=null}else a!=null&&a.size&&C.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;l&&(c=mi(l))?(this.parseID3PES(s,c),s.pesData=null):s.pesData=l}demuxSampleAes(e,t,i){const s=this.demux(e,i,!0,!this.config.progressive),n=this.sampleAes=new uu(this.observer,this.config,t);return this.decrypt(s,n)}decrypt(e,t){return new Promise(i=>{const{audioTrack:s,videoTrack:n}=e;s.samples&&s.segmentCodec==="aac"?t.decryptAacSamples(s.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._duration=0}parseAVCPES(e,t,i,s){const n=this.parseAVCNALu(e,i.data);let o=this.avcSample,a,l=!1;i.data=null,o&&n.length&&!e.audFound&&(tn(o,e),o=this.avcSample=Bs(!1,i.pts,i.dts,"")),n.forEach(c=>{switch(c.type){case 1:{a=!0,o||(o=this.avcSample=Bs(!0,i.pts,i.dts,"")),o.frame=!0;const d=c.data;if(l&&d.length>4){const h=new Ha(d).readSliceType();(h===2||h===4||h===7||h===9)&&(o.key=!0)}break}case 5:a=!0,o||(o=this.avcSample=Bs(!0,i.pts,i.dts,"")),o.key=!0,o.frame=!0;break;case 6:{a=!0,Jo(c.data,1,i.pts,t.samples);break}case 7:if(a=!0,l=!0,!e.sps){const d=c.data,u=new Ha(d).readSPS();e.width=u.width,e.height=u.height,e.pixelRatio=u.pixelRatio,e.sps=[d],e.duration=this._duration;const f=d.subarray(1,4);let g="avc1.";for(let p=0;p<3;p++){let m=f[p].toString(16);m.length<2&&(m="0"+m),g+=m}e.codec=g}break;case 8:a=!0,e.pps||(e.pps=[c.data]);break;case 9:a=!1,e.audFound=!0,o&&tn(o,e),o=this.avcSample=Bs(!1,i.pts,i.dts,"");break;case 12:a=!0;break;default:a=!1,o&&(o.debug+="unknown NAL "+c.type+" ");break}o&&a&&o.units.push(c)}),s&&o&&(tn(o,e),this.avcSample=null)}getLastNalUnit(e){var t;let i=this.avcSample,s;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const n=i.units;s=n[n.length-1]}return s}parseAVCNALu(e,t){const i=t.byteLength;let s=e.naluState||0;const n=s,o=[];let a=0,l,c,d,h=-1,u=0;for(s===-1&&(h=0,u=t[0]&31,s=0,a=1);a<i;){if(l=t[a++],!s){s=l?0:1;continue}if(s===1){s=l?0:2;continue}if(!l)s=3;else if(l===1){if(h>=0){const f={data:t.subarray(h,a-s-1),type:u};o.push(f)}else{const f=this.getLastNalUnit(e.samples);if(f&&(n&&a<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),c=a-s-1,c>0)){const g=new Uint8Array(f.data.byteLength+c);g.set(f.data,0),g.set(t.subarray(0,c),f.data.byteLength),f.data=g,f.state=0}}a<i?(d=t[a]&31,h=a,u=d,s=0):s=-1}else s=0}if(h>=0&&s>=0){const f={data:t.subarray(h,i),type:u,state:s};o.push(f)}if(o.length===0){const f=this.getLastNalUnit(e.samples);if(f){const g=new Uint8Array(f.data.byteLength+t.byteLength);g.set(f.data,0),g.set(t,f.data.byteLength),f.data=g}}return e.naluState=s,o}parseAACPES(e,t){let i=0;const s=this.aacOverFlow;let n=t.data;if(s){this.aacOverFlow=null;const h=s.missing,u=s.sample.unit.byteLength;if(h===-1){const f=new Uint8Array(u+n.byteLength);f.set(s.sample.unit,0),f.set(n,u),n=f}else{const f=u-h;s.sample.unit.set(n.subarray(0,h),f),e.samples.push(s.sample),i=s.missing}}let o,a;for(o=i,a=n.length;o<a-1&&!Fs(n,o);o++);if(o!==i){let h;const u=o<a-1;u?h=`AAC PES did not start with ADTS header,offset:${o}`:h="No ADTS header found in AAC PES";const f=new Error(h);if(C.warn(`parsing error: ${h}`),this.observer.emit(v.ERROR,v.ERROR,{type:q.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,levelRetry:u,error:f,reason:h}),!u)return}Oa(e,this.observer,n,o,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(s){const h=Ma(e.samplerate);l=s.sample.pts+h}else{C.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,d;for(;o<a;)if(d=Fa(e,n,o,l,c),o+=d.length,d.missing){this.aacOverFlow=d;break}else for(c++;o<a-1&&!Fs(n,o);o++);}parseMPEGPES(e,t){const i=t.data,s=i.length;let n=0,o=0;const a=t.pts;if(a===void 0){C.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;o<s;)if(Ua(i,o)){const l=Na(e,i,o,a,n);if(l)o+=l.length,n++;else break}else o++}parseID3PES(e,t){if(t.pts===void 0){C.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=Ce({},t,{type:this._avcTrack?lt.emsg:lt.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Bs(r,e,t,i){return{key:r,frame:!1,pts:e,dts:t,units:[],debug:i,length:0}}function en(r,e){return((r[e+1]&31)<<8)+r[e+2]}function fu(r,e){return(r[e+10]&31)<<8|r[e+11]}function gu(r,e,t,i){const s={audio:-1,avc:-1,id3:-1,segmentCodec:"aac"},n=(r[e+1]&15)<<8|r[e+2],o=e+3+n-4,a=(r[e+10]&15)<<8|r[e+11];for(e+=12+a;e<o;){const l=en(r,e);switch(r[e]){case 207:if(!i){C.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:s.audio===-1&&(s.audio=l);break;case 21:s.id3===-1&&(s.id3=l);break;case 219:if(!i){C.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:s.avc===-1&&(s.avc=l);break;case 3:case 4:t.mpeg!==!0&&t.mp3!==!0?C.log("MPEG audio found, not supported in this browser"):s.audio===-1&&(s.audio=l,s.segmentCodec="mp3");break;case 36:C.warn("Unsupported HEVC stream type found");break}e+=((r[e+3]&15)<<8|r[e+4])+5}return s}function mi(r){let e=0,t,i,s,n,o;const a=r.data;if(!r||r.size===0)return null;for(;a[0].length<19&&a.length>1;){const c=new Uint8Array(a[0].length+a[1].length);c.set(a[0]),c.set(a[1],a[0].length),a[0]=c,a.splice(1,1)}if(t=a[0],(t[0]<<16)+(t[1]<<8)+t[2]===1){if(i=(t[4]<<8)+t[5],i&&i>r.size-6)return null;const c=t[7];c&192&&(n=(t[9]&14)*536870912+(t[10]&255)*4194304+(t[11]&254)*16384+(t[12]&255)*128+(t[13]&254)/2,c&64?(o=(t[14]&14)*536870912+(t[15]&255)*4194304+(t[16]&254)*16384+(t[17]&255)*128+(t[18]&254)/2,n-o>54e5&&(C.warn(`${Math.round((n-o)/9e4)}s delta between PTS and DTS, align them`),n=o)):o=n),s=t[8];let d=s+9;if(r.size<=d)return null;r.size-=d;const h=new Uint8Array(r.size);for(let u=0,f=a.length;u<f;u++){t=a[u];let g=t.byteLength;if(d)if(d>g){d-=g;continue}else t=t.subarray(d),g-=d,d=0;h.set(t,e),e+=g}return i&&(i-=s+3),{data:h,pts:n,dts:o,len:i}}return null}function tn(r,e){if(r.units.length&&r.frame){if(r.pts===void 0){const t=e.samples,i=t.length;if(i){const s=t[i-1];r.pts=s.pts,r.dts=s.dts}else{e.dropped++;return}}e.samples.push(r)}r.debug.length&&C.log(r.pts+"/"+r.dts+":"+r.debug)}class pu extends Da{resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let i=(Ss(e,0)||[]).length;for(let s=e.length;i<s;i++)if(hu(e,i))return C.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return du(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return Na(e,t,i,this.basePTS,this.frameIndex)}}class Ga{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}}}const Ut=Math.pow(2,32)-1;class L{static init(){L.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in L.types)L.types.hasOwnProperty(e)&&(L.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const 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]);L.HDLR_TYPES={video:t,audio:i};const s=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]);L.STTS=L.STSC=L.STCO=n,L.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),L.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),L.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),L.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const o=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);L.FTYP=L.box(L.types.ftyp,o,l,o,a),L.DINF=L.box(L.types.dinf,L.box(L.types.dref,s))}static box(e,...t){let i=8,s=t.length;const n=s;for(;s--;)i+=t[s].byteLength;const 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),s=0,i=8;s<n;s++)o.set(t[s],i),i+=t[s].byteLength;return o}static hdlr(e){return L.box(L.types.hdlr,L.HDLR_TYPES[e])}static mdat(e){return L.box(L.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(Ut+1)),s=Math.floor(t%(Ut+1));return L.box(L.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,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(e){return L.box(L.types.mdia,L.mdhd(e.timescale,e.duration),L.hdlr(e.type),L.minf(e))}static mfhd(e){return L.box(L.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"?L.box(L.types.minf,L.box(L.types.smhd,L.SMHD),L.DINF,L.stbl(e)):L.box(L.types.minf,L.box(L.types.vmhd,L.VMHD),L.DINF,L.stbl(e))}static moof(e,t,i){return L.box(L.types.moof,L.mfhd(e),L.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=L.trak(e[t]);return L.box.apply(null,[L.types.moov,L.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(L.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=L.trex(e[t]);return L.box.apply(null,[L.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(Ut+1)),s=Math.floor(t%(Ut+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,s>>24,s>>16&255,s>>8&255,s&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 L.box(L.types.mvhd,n)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let s,n;for(s=0;s<t.length;s++)n=t[s].flags,i[s+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return L.box(L.types.sdtp,i)}static stbl(e){return L.box(L.types.stbl,L.stsd(e),L.box(L.types.stts,L.STTS),L.box(L.types.stsc,L.STSC),L.box(L.types.stsz,L.STSZ),L.box(L.types.stco,L.STCO))}static avc1(e){let t=[],i=[],s,n,o;for(s=0;s<e.sps.length;s++)n=e.sps[s],o=n.byteLength,t.push(o>>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(n));for(s=0;s<e.pps.length;s++)n=e.pps[s],o=n.byteLength,i.push(o>>>8&255),i.push(o&255),i=i.concat(Array.prototype.slice.call(n));const a=L.box(L.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,c=e.height,d=e.pixelRatio[0],h=e.pixelRatio[1];return L.box(L.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,c>>8&255,c&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,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static mp4a(e){const t=e.samplerate;return L.box(L.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0]),L.box(L.types.esds,L.esds(e)))}static mp3(e){const t=e.samplerate;return L.box(L.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0]))}static stsd(e){return e.type==="audio"?e.segmentCodec==="mp3"&&e.codec==="mp3"?L.box(L.types.stsd,L.STSD,L.mp3(e)):L.box(L.types.stsd,L.STSD,L.mp4a(e)):L.box(L.types.stsd,L.STSD,L.avc1(e))}static tkhd(e){const t=e.id,i=e.duration*e.timescale,s=e.width,n=e.height,o=Math.floor(i/(Ut+1)),a=Math.floor(i%(Ut+1));return L.box(L.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,s>>8&255,s&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){const i=L.sdtp(e),s=e.id,n=Math.floor(t/(Ut+1)),o=Math.floor(t%(Ut+1));return L.box(L.types.traf,L.box(L.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),L.box(L.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])),L.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,L.box(L.types.trak,L.tkhd(e),L.mdia(e))}static trex(e){const t=e.id;return L.box(L.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){const i=e.samples||[],s=i.length,n=12+16*s,o=new Uint8Array(n);let a,l,c,d,h,u;for(t+=8+n,o.set([e.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),a=0;a<s;a++)l=i[a],c=l.duration,d=l.size,h=l.flags,u=l.cts,o.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,d>>>24&255,d>>>16&255,d>>>8&255,d&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,u>>>24&255,u>>>16&255,u>>>8&255,u&255],12+16*a);return L.box(L.types.trun,o)}static initSegment(e){L.types||L.init();const t=L.moov(e),i=new Uint8Array(L.FTYP.byteLength+t.byteLength);return i.set(L.FTYP),i.set(t,L.FTYP.byteLength),i}}L.types=void 0,L.HDLR_TYPES=void 0,L.STTS=void 0,L.STSC=void 0,L.STCO=void 0,L.STSZ=void 0,L.VMHD=void 0,L.SMHD=void 0,L.STSD=void 0,L.FTYP=void 0,L.DINF=void 0;const Va=9e4;function sn(r,e,t=1,i=!1){const s=r*e*t;return i?Math.round(s):s}function mu(r,e,t=1,i=!1){return sn(r,e,1/t,i)}function _i(r,e=!1){return sn(r,1e3,1/Va,e)}function vu(r,e=1){return sn(r,Va,1/e)}const yu=10*1e3,ja=1024,Au=1152;let Us=null,rn=null;class nn{constructor(e,t,i,s=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,Us===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Us=o?parseInt(o[1]):0}if(rn===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);rn=n?parseInt(n[1]):0}}destroy(){}resetTimeStamp(e){C.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){C.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){C.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1}getVideoStartPts(e){let t=!1;const i=e.reduce((s,n)=>{const o=n.pts-s;return o<-4294967296?(t=!0,$e(s,n.pts)):o>0?s:n.pts},e[0].pts);return t&&C.debug("PTS rollover detected"),i}remux(e,t,i,s,n,o,a,l){let c,d,h,u,f,g,p=n,m=n;const A=e.pid>-1,x=t.pid>-1,b=t.samples.length,y=e.samples.length>0,T=a&&b>0||b>1;if((!A||y)&&(!x||T)||this.ISGenerated||a){this.ISGenerated||(h=this.generateIS(e,t,n,o));const S=this.isVideoContiguous;let R=-1,w;if(T&&(R=bu(t.samples),!S&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,R>0){C.warn(`[mp4-remuxer]: Dropped ${R} out of ${b} video samples due to a missing keyframe`);const I=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(R),t.dropped+=R,m+=(t.samples[0].pts-I)/t.inputTimeScale,w=m}else R===-1&&(C.warn(`[mp4-remuxer]: No keyframe found out of ${b} video samples`),g=!1);if(this.ISGenerated){if(y&&T){const I=this.getVideoStartPts(t.samples),P=($e(e.samples[0].pts,I)-I)/t.inputTimeScale;p+=Math.max(0,P),m+=Math.max(0,-P)}if(y){if(e.samplerate||(C.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),h=this.generateIS(e,t,n,o)),d=this.remuxAudio(e,p,this.isAudioContiguous,o,x||T||l===Z.AUDIO?m:void 0),T){const I=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(C.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),h=this.generateIS(e,t,n,o)),c=this.remuxVideo(t,m,S,I)}}else T&&(c=this.remuxVideo(t,m,S,0));c&&(c.firstKeyFrame=R,c.independent=R!==-1,c.firstKeyFramePTS=w)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=za(i,n,this._initPTS,this._initDTS)),s.samples.length&&(u=Wa(s,n,this._initPTS))),{audio:d,video:c,initSegment:h,independent:g,text:u,id3:f}}generateIS(e,t,i,s){const n=e.samples,o=t.samples,a=this.typeSupported,l={},c=this._initPTS;let d=!c||s,h="audio/mp4",u,f,g;if(d&&(u=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(h="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break}l.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):L.initSegment([e]),metadata:{channelCount:e.channelCount}},d&&(g=e.inputTimeScale,!c||g!==c.timescale?u=f=n[0].pts-Math.round(g*i):d=!1)}if(t.sps&&t.pps&&o.length&&(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:L.initSegment([t]),metadata:{width:t.width,height:t.height}},d))if(g=t.inputTimeScale,!c||g!==c.timescale){const p=this.getVideoStartPts(o),m=Math.round(g*i);f=Math.min(f,$e(o[0].dts,p)-m),u=Math.min(u,p-m)}else d=!1;if(Object.keys(l).length)return this.ISGenerated=!0,d?(this._initPTS={baseTime:u,timescale:g},this._initDTS={baseTime:f,timescale:g}):u=g=void 0,{tracks:l,initPTS:u,timescale:g}}remuxVideo(e,t,i,s){const n=e.inputTimeScale,o=e.samples,a=[],l=o.length,c=this._initPTS;let d=this.nextAvcDts,h=8,u=this.videoSampleDuration,f,g,p=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,A=!1;if(!i||d===null){const F=t*n,U=o[0].pts-$e(o[0].dts,o[0].pts);d=F-U}const x=c.baseTime*n/c.timescale;for(let F=0;F<l;F++){const U=o[F];U.pts=$e(U.pts-x,d),U.dts=$e(U.dts-x,d),U.dts<o[F>0?F-1:F].dts&&(A=!0)}A&&o.sort(function(F,U){const Q=F.dts-U.dts,Y=F.pts-U.pts;return Q||Y}),f=o[0].dts,g=o[o.length-1].dts;const b=g-f,y=b?Math.round(b/(l-1)):u||e.inputTimeScale/30;if(i){const F=f-d,U=F>y,Q=F<-1;if((U||Q)&&(U?C.warn(`AVC: ${_i(F,!0)} ms (${F}dts) hole between fragments detected, filling it`):C.warn(`AVC: ${_i(-F,!0)} ms (${F}dts) overlapping between fragments detected`),!Q||d>=o[0].pts)){f=d;const Y=o[0].pts-F;o[0].dts=f,o[0].pts=Y,C.log(`Video: First PTS/DTS adjusted: ${_i(Y,!0)}/${_i(f,!0)}, delta: ${_i(F,!0)} ms`)}}f=Math.max(0,f);let T=0,E=0;for(let F=0;F<l;F++){const U=o[F],Q=U.units,Y=Q.length;let z=0;for(let K=0;K<Y;K++)z+=Q[K].data.length;E+=z,T+=Y,U.length=z,U.dts=Math.max(U.dts,f),p=Math.min(U.pts,p),m=Math.max(U.pts,m)}g=o[l-1].dts;const S=E+4*T+8;let R;try{R=new Uint8Array(S)}catch(F){this.observer.emit(v.ERROR,v.ERROR,{type:q.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,error:F,bytes:S,reason:`fail allocating video mdat ${S}`});return}const w=new DataView(R.buffer);w.setUint32(0,S),R.set(L.types.mdat,4);let I=!1,O=Number.POSITIVE_INFINITY,P=Number.POSITIVE_INFINITY,B=Number.NEGATIVE_INFINITY,J=Number.NEGATIVE_INFINITY;for(let F=0;F<l;F++){const U=o[F],Q=U.units;let Y=0;for(let X=0,ie=Q.length;X<ie;X++){const ee=Q[X],ne=ee.data,se=ee.data.byteLength;w.setUint32(h,se),h+=4,R.set(ne,h),h+=se,Y+=4+se}let z;if(F<l-1)u=o[F+1].dts-U.dts,z=o[F+1].pts-U.pts;else{const X=this.config,ie=F>0?U.dts-o[F-1].dts:y;if(z=F>0?U.pts-o[F-1].pts:y,X.stretchShortVideoTrack&&this.nextAudioPts!==null){const ee=Math.floor(X.maxBufferHole*n),ne=(s?p+s*n:this.nextAudioPts)-U.pts;ne>ee?(u=ne-ie,u<0?u=ie:I=!0,C.log(`[mp4-remuxer]: It is approximately ${ne/90} ms to the next segment; using duration ${u/90} ms for the last video frame.`)):u=ie}else u=ie}const K=Math.round(U.pts-U.dts);O=Math.min(O,u),B=Math.max(B,u),P=Math.min(P,z),J=Math.max(J,z),a.push(new Ya(U.key,u,Y,K))}if(a.length){if(Us){if(Us<70){const F=a[0].flags;F.dependsOn=2,F.isNonSync=0}}else if(rn&&J-P<B-O&&y/B<.025&&a[0].cts===0){C.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let F=f;for(let U=0,Q=a.length;U<Q;U++){const Y=F+a[U].duration,z=F+a[U].cts;if(U<Q-1){const K=Y+a[U+1].cts;a[U].duration=K-z}else a[U].duration=U?a[U-1].duration:y;a[U].cts=0,F=Y}}}u=I||!u?y:u,this.nextAvcDts=d=g+u,this.videoSampleDuration=u,this.isVideoContiguous=!0;const H=L.moof(e.sequenceNumber++,f,Ce({},e,{samples:a})),V="video",j={data1:H,data2:R,startPTS:p/n,endPTS:(m+u)/n,startDTS:f/n,endDTS:d/n,type:V,hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,j}remuxAudio(e,t,i,s,n){const o=e.inputTimeScale,a=e.samplerate?e.samplerate:o,l=o/a,c=e.segmentCodec==="aac"?ja:Au,d=c*l,h=this._initPTS,u=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=n!==void 0;let p=e.samples,m=u?0:8,A=this.nextAudioPts||-1;const x=t*o,b=h.baseTime*o/h.timescale;if(this.isAudioContiguous=i=i||p.length&&A>0&&(s&&Math.abs(x-A)<9e3||Math.abs($e(p[0].pts-b,x)-A)<20*d),p.forEach(function(V){V.pts=$e(V.pts-b,x)}),!i||A<0){if(p=p.filter(V=>V.pts>=0),!p.length)return;n===0?A=0:s&&!g?A=Math.max(0,x):A=p[0].pts}if(e.segmentCodec==="aac"){const V=this.config.maxAudioFramesDrift;for(let j=0,F=A;j<p.length;j++){const U=p[j],Q=U.pts,Y=Q-F,z=Math.abs(1e3*Y/o);if(Y<=-V*d&&g)j===0&&(C.warn(`Audio frame @ ${(Q/o).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*Y/o)} ms.`),this.nextAudioPts=A=F=Q);else if(Y>=V*d&&z<yu&&g){let K=Math.round(Y/d);F=Q-K*d,F<0&&(K--,F+=d),j===0&&(this.nextAudioPts=A=F),C.warn(`[mp4-remuxer]: Injecting ${K} audio frame @ ${(F/o).toFixed(3)}s due to ${Math.round(1e3*Y/o)} ms gap.`);for(let X=0;X<K;X++){const ie=Math.max(F,0);let ee=Ga.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);ee||(C.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),ee=U.unit.subarray()),p.splice(j,0,{unit:ee,pts:ie}),F+=d,j++}}U.pts=F,F+=d}}let y=null,T=null,E,S=0,R=p.length;for(;R--;)S+=p[R].unit.byteLength;for(let V=0,j=p.length;V<j;V++){const F=p[V],U=F.unit;let Q=F.pts;if(T!==null){const z=f[V-1];z.duration=Math.round((Q-T)/l)}else if(i&&e.segmentCodec==="aac"&&(Q=A),y=Q,S>0){S+=m;try{E=new Uint8Array(S)}catch(z){this.observer.emit(v.ERROR,v.ERROR,{type:q.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,error:z,bytes:S,reason:`fail allocating audio mdat ${S}`});return}u||(new DataView(E.buffer).setUint32(0,S),E.set(L.types.mdat,4))}else return;E.set(U,m);const Y=U.byteLength;m+=Y,f.push(new Ya(!0,c,Y,0)),T=Q}const w=f.length;if(!w)return;const I=f[f.length-1];this.nextAudioPts=A=T+l*I.duration;const O=u?new Uint8Array(0):L.moof(e.sequenceNumber++,y/l,Ce({},e,{samples:f}));e.samples=[];const P=y/o,B=A/o,H={data1:O,data2:E,startPTS:P,endPTS:B,startDTS:P,endDTS:B,type:"audio",hasAudio:!0,hasVideo:!1,nb:w};return this.isAudioContiguous=!0,H}remuxEmptyAudio(e,t,i,s){const n=e.inputTimeScale,o=e.samplerate?e.samplerate:n,a=n/o,l=this.nextAudioPts,c=this._initDTS,d=c.baseTime*9e4/c.timescale,h=(l!==null?l:s.startDTS*n)+d,u=s.endDTS*n+d,f=a*ja,g=Math.ceil((u-h)/f),p=Ga.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(C.warn("[mp4-remuxer]: remux empty Audio"),!p){C.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const m=[];for(let A=0;A<g;A++){const x=h+A*f;m.push({unit:p,pts:x,dts:x})}return e.samples=m,this.remuxAudio(e,t,i,!1)}}function $e(r,e){let t;if(e===null)return r;for(e<r?t=-8589934592:t=8589934592;Math.abs(r-e)>4294967296;)r+=t;return r}function bu(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function za(r,e,t,i){const s=r.samples.length;if(!s)return;const n=r.inputTimeScale;for(let a=0;a<s;a++){const l=r.samples[a];l.pts=$e(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=$e(l.dts-i.baseTime*n/i.timescale,e*n)/n}const o=r.samples;return r.samples=[],{samples:o}}function Wa(r,e,t){const i=r.samples.length;if(!i)return;const s=r.inputTimeScale;for(let o=0;o<i;o++){const a=r.samples[o];a.pts=$e(a.pts-t.baseTime*9e4/t.timescale,e*s)/s}r.samples.sort((o,a)=>o.pts-a.pts);const n=r.samples;return r.samples=[],{samples:n}}class Ya{constructor(e,t,i,s){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=i,this.cts=s,this.flags=new xu(e)}}class xu{constructor(e){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=e?2:1,this.isNonSync=e?0:1}}class Tu{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(jd(e,s)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const s=this.initData=Xo(e);t||(t=Ka(s.audio,de.AUDIO)),i||(i=Ka(s.video,de.VIDEO));const n={};s.audio&&s.video?n.audiovideo={container:"video/mp4",codec:t+","+i,initSegment:e,id:"main"}:s.audio?n.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:s.video?n.video={container:"video/mp4",codec:i,initSegment:e,id:"main"}:C.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(e,t,i,s,n,o){var a,l;let{initPTS:c,lastEndTime:d}=this;const h={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};W(d)||(d=this.lastEndTime=n||0);const u=t.samples;if(!(u!=null&&u.length))return h;const f={initPTS:void 0,timescale:1};let g=this.initData;if((a=g)!=null&&a.length||(this.generateInitSegment(u),g=this.initData),!((l=g)!=null&&l.length))return C.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),h;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const p=Wd(u,g),m=zd(g,u),A=m===null?n:m;(Eu(c,A,n,p)||f.timescale!==c.timescale&&o)&&(f.initPTS=A-n,c&&c.timescale===1&&C.warn(`Adjusting initPTS by ${f.initPTS-c.baseTime}`),this.initPTS=c={baseTime:f.initPTS,timescale:1});const x=e?A-c.baseTime/c.timescale:d,b=x+p;Kd(g,u,c.baseTime/c.timescale),p>0?this.lastEndTime=b:(C.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const y=!!g.audio,T=!!g.video;let E="";y&&(E+="audio"),T&&(E+="video");const S={data1:u,startPTS:x,startDTS:x,endPTS:b,endDTS:b,type:E,hasAudio:y,hasVideo:T,nb:1,dropped:0};return h.audio=S.type==="audio"?S:void 0,h.video=S.type!=="audio"?S:void 0,h.initSegment=f,h.id3=za(i,n,c,c),s.samples.length&&(h.text=Wa(s,n,c)),h}}function Eu(r,e,t,i){if(r===null)return!0;const s=Math.max(i,1),n=e-r.baseTime/r.timescale;return Math.abs(n-t)>s}function Ka(r,e){const t=r==null?void 0:r.codec;return t&&t.length>4?t:t==="hvc1"||t==="hev1"?"hvc1.1.6.L120.90":t==="av01"?"av01.0.04M.08":t==="avc1"||e===de.VIDEO?"avc1.42e01e":"mp4a.40.5"}let Lt;try{Lt=self.performance.now.bind(self.performance)}catch{C.debug("Unable to use Performance API on this environment"),Lt=typeof self<"u"&&self.Date.now}const on=[{demux:nu,remux:Tu},{demux:Bt,remux:nn},{demux:su,remux:nn},{demux:pu,remux:nn}];class Xa{constructor(e,t,i,s,n){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=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.vendor=s,this.id=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){const n=i.transmuxing;n.executeStart=Lt();let o=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:l}=this;s&&(this.currentTransmuxState=s);const{contiguous:c,discontinuity:d,trackSwitch:h,accurateTimeOffset:u,timeOffset:f,initSegmentChange:g}=s||a,{audioCodec:p,videoCodec:m,defaultInitPts:A,duration:x,initSegmentData:b}=l,y=Su(o,t);if(y&&y.method==="AES-128"){const R=this.getDecrypter();if(R.isSync()){let w=R.softwareDecrypt(o,y.key.buffer,y.iv.buffer);if(i.part>-1&&(w=R.flush()),!w)return n.executeEnd=Lt(),an(i);o=new Uint8Array(w)}else return this.decryptionPromise=R.webCryptoDecrypt(o,y.key.buffer,y.iv.buffer).then(w=>{const I=this.push(w,null,i);return this.decryptionPromise=null,I}),this.decryptionPromise}const T=this.needsProbing(d,h);if(T){const R=this.configureTransmuxer(o);if(R)return C.warn(`[transmuxer] ${R.message}`),this.observer.emit(v.ERROR,v.ERROR,{type:q.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message}),n.executeEnd=Lt(),an(i)}(d||h||g||T)&&this.resetInitSegment(b,p,m,x,t),(d||g||T)&&this.resetInitialTimestamp(A),c||this.resetContiguity();const E=this.transmux(o,y,f,u,i),S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,n.executeEnd=Lt(),E}flush(e){const t=e.transmuxing;t.executeStart=Lt();const{decrypter:i,currentTransmuxState:s,decryptionPromise:n}=this;if(n)return n.then(()=>this.flush(e));const o=[],{timeOffset:a}=s;if(i){const h=i.flush();h&&o.push(this.push(h,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c)return t.executeEnd=Lt(),[an(e)];const d=l.flush(a);return Hs(d)?d.then(h=>(this.flushRemux(o,h,e),o)):(this.flushRemux(o,d,e),o)}flushRemux(e,t,i){const{audioTrack:s,videoTrack:n,id3Track:o,textTrack:a}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;C.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const d=this.remuxer.remux(s,n,o,a,c,l,!0,this.id);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=Lt()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,s,n){const{demuxer:o,remuxer:a}=this;!o||!a||(o.resetInitSegment(e,t,i,s),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,s,n){let o;return t&&t.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,t,i,s,n):o=this.transmuxUnencrypted(e,i,s,n),o}transmuxUnencrypted(e,t,i,s){const{audioTrack:n,videoTrack:o,id3Track:a,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,o,a,l,t,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,i,s,n){return this.demuxer.demuxSampleAes(e,t,i).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,i,s,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:s,vendor:n}=this;let o;for(let h=0,u=on.length;h<u;h++)if(on[h].demux.probe(e)){o=on[h];break}if(!o)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,l=this.remuxer,c=o.remux,d=o.demux;(!l||!(l instanceof c))&&(this.remuxer=new c(i,t,s,n)),(!a||!(a instanceof d))&&(this.demuxer=new d(i,t,s),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Jr(this.config)),e}}function Su(r,e){let t=null;return r.byteLength>0&&e!=null&&e.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const an=r=>({remuxResult:{},chunkMeta:r});function Hs(r){return"then"in r&&r.then instanceof Function}class Iu{constructor(e,t,i,s,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=s,this.defaultInitPts=n||null}}class Cu{constructor(e,t,i,s,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=s,this.timeOffset=n,this.initSegmentChange=o}}var qa={exports:{}};(function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(l,c,d){this.fn=l,this.context=c,this.once=d||!1}function n(l,c,d,h,u){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new s(d,h||l,u),g=t?t+c:c;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],d,h;if(this._eventsCount===0)return c;for(h in d=this._events)e.call(d,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},a.prototype.listeners=function(c){var d=t?t+c:c,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var u=0,f=h.length,g=new Array(f);u<f;u++)g[u]=h[u].fn;return g},a.prototype.listenerCount=function(c){var d=t?t+c:c,h=this._events[d];return h?h.fn?1:h.length:0},a.prototype.emit=function(c,d,h,u,f,g){var p=t?t+c:c;if(!this._events[p])return!1;var m=this._events[p],A=arguments.length,x,b;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),A){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,d),!0;case 3:return m.fn.call(m.context,d,h),!0;case 4:return m.fn.call(m.context,d,h,u),!0;case 5:return m.fn.call(m.context,d,h,u,f),!0;case 6:return m.fn.call(m.context,d,h,u,f,g),!0}for(b=1,x=new Array(A-1);b<A;b++)x[b-1]=arguments[b];m.fn.apply(m.context,x)}else{var y=m.length,T;for(b=0;b<y;b++)switch(m[b].once&&this.removeListener(c,m[b].fn,void 0,!0),A){case 1:m[b].fn.call(m[b].context);break;case 2:m[b].fn.call(m[b].context,d);break;case 3:m[b].fn.call(m[b].context,d,h);break;case 4:m[b].fn.call(m[b].context,d,h,u);break;default:if(!x)for(T=1,x=new Array(A-1);T<A;T++)x[T-1]=arguments[T];m[b].fn.apply(m[b].context,x)}}return!0},a.prototype.on=function(c,d,h){return n(this,c,d,h,!1)},a.prototype.once=function(c,d,h){return n(this,c,d,h,!0)},a.prototype.removeListener=function(c,d,h,u){var f=t?t+c:c;if(!this._events[f])return this;if(!d)return o(this,f),this;var g=this._events[f];if(g.fn)g.fn===d&&(!u||g.once)&&(!h||g.context===h)&&o(this,f);else{for(var p=0,m=[],A=g.length;p<A;p++)(g[p].fn!==d||u&&!g[p].once||h&&g[p].context!==h)&&m.push(g[p]);m.length?this._events[f]=m.length===1?m[0]:m:o(this,f)}return this},a.prototype.removeAllListeners=function(c){var d;return c?(d=t?t+c:c,this._events[d]&&o(this,d)):(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,r.exports=a})(qa);var wu=qa.exports,ln=ud(wu);const cn=Ls()||{isTypeSupported:()=>!1};class Za{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const o=(c,d)=>{d=d||{},d.frag=this.frag,d.id=this.id,c===v.ERROR&&(this.error=d.error),this.hls.trigger(c,d)};this.observer=new ln,this.observer.on(v.FRAG_DECRYPTED,o),this.observer.on(v.ERROR,o);const a={mp4:cn.isTypeSupported("video/mp4"),mpeg:cn.isTypeSupported("audio/mpeg"),mp3:cn.isTypeSupported('audio/mp4; codecs="mp3"')},l=navigator.vendor;if(this.useWorker&&typeof Worker<"u"&&(n.workerPath||qh())){try{n.workerPath?(C.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=Jh(n.workerPath)):(C.log(`injecting Web Worker for "${t}"`),this.workerContext=Zh()),this.onwmsg=h=>this.onWorkerMessage(h);const{worker:d}=this.workerContext;d.addEventListener("message",this.onwmsg),d.onerror=h=>{const u=new Error(`${h.message} (${h.filename}:${h.lineno})`);n.enableWorker=!1,C.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(v.ERROR,{type:q.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:u})},d.postMessage({cmd:"init",typeSupported:a,vendor:l,id:t,config:JSON.stringify(n)})}catch(d){C.warn(`Error setting up "${t}" Web Worker, fallback to inline`,d),this.resetWorker(),this.error=null,this.transmuxer=new Xa(this.observer,a,n,l,t)}return}this.transmuxer=new Xa(this.observer,a,n,l,t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,i,s,n,o,a,l,c,d){var h,u;c.transmuxing.start=self.performance.now();const{transmuxer:f}=this,g=o?o.start:n.start,p=n.decryptdata,m=this.frag,A=!(m&&n.cc===m.cc),x=!(m&&c.level===m.level),b=m?c.sn-m.sn:-1,y=this.part?c.part-this.part.index:-1,T=b===0&&c.id>1&&c.id===(m==null?void 0:m.stats.chunkCount),E=!x&&(b===1||b===0&&(y===1||T&&y<=0)),S=self.performance.now();(x||b||n.stats.parsing.start===0)&&(n.stats.parsing.start=S),o&&(y||!E)&&(o.stats.parsing.start=S);const R=!(m&&((h=n.initSegment)==null?void 0:h.url)===((u=m.initSegment)==null?void 0:u.url)),w=new Cu(A,E,l,x,g,R);if(!E||A||R){C.log(`[transmuxer-interface, ${n.type}]: Starting new transmux session for sn: ${c.sn} p: ${c.part} level: ${c.level} id: ${c.id}
67
67
  discontinuity: ${A}
68
- trackSwitch: ${T}
68
+ trackSwitch: ${x}
69
69
  contiguous: ${E}
70
70
  accurateTimeOffset: ${l}
71
71
  timeOffset: ${g}
72
- initSegmentChange: ${R}`);const I=new Iu(i,s,t,a,d);this.configureTransmuxer(I)}if(this.frag=n,this.part=o,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:p,chunkMeta:c,state:w},e instanceof ArrayBuffer?[e]:[]);else if(f){const I=f.push(e,p,c,w);Hs(I)?(f.async=!0,I.then(O=>{this.handleTransmuxComplete(O)}).catch(O=>{this.transmuxerError(O,c,"transmuxer-interface push error")})):(f.async=!1,this.handleTransmuxComplete(I))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let i=t.flush(e);Hs(i)||t.async?(Hs(i)||(i=Promise.resolve(i)),i.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")})):this.handleFlushResult(i,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}onWorkerMessage(e){const t=e.data,i=this.hls;switch(t.event){case"init":{var s;const n=(s=this.workerContext)==null?void 0:s.objectURL;n&&self.URL.revokeObjectURL(n);break}case"transmuxComplete":{this.handleTransmuxComplete(t.data);break}case"flush":{this.onFlush(t.data);break}case"workerLog":C[t.data.logType]&&C[t.data.logType](t.data.message);break;default:{t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,i.trigger(t.event,t.data);break}}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Lu=250,dn=2,Ru=.1,Du=.05;class ku{constructor(e,t,i,s){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=s}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:i,media:s,stalled:n}=this;if(s===null)return;const{currentTime:o,seeking:a}=s,l=this.seeking&&!a,c=!this.seeking&&a;if(this.seeking=a,o!==e){if(this.moved=!0,n!==null){if(this.stallReported){const A=self.performance.now()-n;C.warn(`playback not stuck anymore @${o}, after ${Math.round(A)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(c||l){this.stalled=null;return}if(s.paused&&!a||s.ended||s.playbackRate===0||!fe.getBuffered(s).length)return;const d=fe.bufferInfo(s,o,0),h=d.len>0,u=d.nextStart||0;if(!h&&!u)return;if(a){const A=d.len>dn,T=!u||t&&t.start<=o||u-o>dn&&!this.fragmentTracker.getPartialFragment(o);if(A||T)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var f;const A=Math.max(u,d.start||0)-o,T=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,y=(T==null||(f=T.details)==null?void 0:f.live)?T.details.targetduration*2:dn,x=this.fragmentTracker.getPartialFragment(o);if(A>0&&(A<=y||x)){this._trySkipBufferHole(x);return}}const g=self.performance.now();if(n===null){this.stalled=g;return}const p=g-n;if(!a&&p>=Lu&&(this._reportStall(d),!this.media))return;const m=fe.bufferInfo(s,o,i.maxBufferHole);this._tryFixBufferStall(m,p)}_tryFixBufferStall(e,t){const{config:i,fragmentTracker:s,media:n}=this;if(n===null)return;const o=n.currentTime,a=s.getPartialFragment(o);a&&(this._trySkipBufferHole(a)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-o<i.maxBufferHole)&&t>i.highBufferWatchdogPeriod*1e3&&(C.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:i,stallReported:s}=this;if(!s&&i){this.stallReported=!0;const n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);C.warn(n.message),t.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:i,media:s}=this;if(s===null)return 0;const n=s.currentTime,o=fe.bufferInfo(s,n,0),a=n<o.start?o.start:o.nextStart;if(a){const l=o.len<=t.maxBufferHole,c=o.len>0&&o.len<1&&s.readyState<3,d=a-n;if(d>0&&(l||c)){if(d>t.maxBufferHole){const{fragmentTracker:u}=this;let f=!1;if(n===0){const g=u.getAppendedFrag(0,Z.MAIN);g&&a<g.end&&(f=!0)}if(!f){const g=e||u.getAppendedFrag(n,Z.MAIN);if(g){let p=!1,m=g.end;for(;m<a;){const A=u.getPartialFragment(m);if(A)m+=A.duration;else{p=!0;break}}if(p)return 0}}}const h=Math.max(a+Du,n+Ru);if(C.warn(`skipping hole, adjusting currentTime from ${n} to ${h}`),this.moved=!0,this.stalled=null,s.currentTime=h,e&&!e.gap){const u=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${h}`);i.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:e})}return h}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:i,nudgeRetry:s}=this;if(i===null)return;const n=i.currentTime;if(this.nudgeRetry++,s<e.nudgeMaxRetry){const o=n+(s+1)*e.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${n} to ${o}`);C.warn(a.message),i.currentTime=o,t.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const o=new Error(`Playhead still not moving while enough data buffered @${n} after ${e.nudgeMaxRetry} nudges`);C.error(o.message),t.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,error:o,fatal:!0})}}}const Pu=100;class Ou extends Qr{constructor(e,t,i){super(e,t,i,"[stream-controller]",Z.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{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_LOADED,this.onLevelLoaded,this),e.on(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(v.ERROR,this.onError,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(){const{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_LOADED,this.onLevelLoaded,this),e.off(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(v.ERROR,this.onError,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._unregisterListeners(),this.onMediaDetaching()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:i}=this;if(this.stopLoad(),this.setInterval(Pu),this.level=-1,!this.startFragRequested){let s=i.startLevel;s===-1&&(i.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=i.nextAutoLevel),this.level=i.nextLoadLevel=s,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=M.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=M.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case M.WAITING_LEVEL:{var e;const{levels:i,level:s}=this,n=i==null||(e=i[s])==null?void 0:e.details;if(n&&(!n.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(n))break;this.state=M.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=M.IDLE;break}break}case M.FRAG_LOADING_WAITING_RETRY:{var t;const i=self.performance.now(),s=this.retryDate;(!s||i>=s||(t=this.media)!=null&&t.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=M.IDLE)}break}this.state===M.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:s}=this,{config:n,nextLoadLevel:o}=e;if(t===null||!s&&(this.startFragRequested||!n.startFragPrefetch)||this.altAudio&&this.audioOnly||!(i!=null&&i[o]))return;const a=i[o],l=this.getMainFwdBufferInfo();if(l===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(l,c)){const m={};this.altAudio&&(m.type="video"),this.hls.trigger(v.BUFFER_EOS,m),this.state=M.ENDED;return}e.loadLevel!==o&&e.manualLevel===-1&&this.log(`Adapting to level ${o} from level ${this.level}`),this.level=e.nextLoadLevel=o;const d=a.details;if(!d||this.state===M.WAITING_LEVEL||d.live&&this.levelLastLoaded!==o){this.level=o,this.state=M.WAITING_LEVEL;return}const h=l.len,u=this.getMaxBufferLength(a.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>l.end&&(this.backtrackFragment=null);const f=this.backtrackFragment?this.backtrackFragment.start:l.end;let g=this.getNextFragment(f,d);if(this.couldBacktrack&&!this.fragPrevious&&g&&g.sn!=="initSegment"&&this.fragmentTracker.getState(g)!==ke.OK){var p;const A=((p=this.backtrackFragment)!=null?p:g).sn-d.startSN,T=d.fragments[A-1];T&&g.cc===T.cc&&(g=T,this.fragmentTracker.removeFragment(T))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,f)){if(!g.gap){const A=this.audioOnly&&!this.altAudio?de.AUDIO:de.VIDEO,T=(A===de.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;T&&this.afterBufferFlushed(T,A,Z.MAIN)}g=this.getNextFragmentLoopLoading(g,d,l,Z.MAIN,u)}g&&(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,a,f))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);this.fragCurrent=e,s===ke.NOT_LOADED||s===ke.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):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)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Z.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let i;const s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const n=this.getLevelDetails();if(n!=null&&n.live){const a=this.getMainFwdBufferInfo();if(!a||a.len<n.targetduration*2)return}if(!t.paused&&e){const a=this.hls.nextLoadLevel,l=e[a],c=this.fragLastKbps;c&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:i=0}else i=0;const o=this.getBufferedFrag(t.currentTime+i);if(o){const a=this.followingBufferedFrag(o);if(a){this.abortCurrentFrag();const l=a.maxStartPTS?a.maxStartPTS:a.start,c=a.duration,d=Math.max(o.end,l+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*.5),c*.75));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case M.KEY_LOADING:case M.FRAG_LOADING:case M.FRAG_LOADING_WAITING_RETRY:case M.PARSING:case M.PARSED:this.state=M.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new ku(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;W(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(v.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.levels=this.fragPlaying=this.backtrackFragment=null,this.altAudio=this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1,n;t.levels.forEach(o=>{n=o.audioCodec,n&&(n.indexOf("mp4a.40.2")!==-1&&(i=!0),n.indexOf("mp4a.40.5")!==-1&&(s=!0))}),this.audioCodecSwitch=i&&s&&!Xh(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==M.IDLE)return;const s=i[t.level];(!s.details||s.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(s.details))&&(this.state=M.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:s}=this,n=t.level,o=t.details,a=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${a}`);const l=s[n],c=this.fragCurrent;c&&(this.state===M.FRAG_LOADING||this.state===M.FRAG_LOADING_WAITING_RETRY)&&(c.level!==t.level||c.urlId!==l.urlId)&&c.loader&&this.abortCurrentFrag();let d=0;if(o.live||(i=l.details)!=null&&i.live){if(o.fragments[0]||(o.deltaUpdateFailed=!0),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,l.details)}if(l.details=o,this.levelLastLoaded=n,this.hls.trigger(v.LEVEL_UPDATED,{details:o,level:n}),this.state===M.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=M.IDLE}this.startFragRequested?o.live&&this.synchronizeToLiveEdge(o):this.setStartPosition(o,d),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:s,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}const a=o[i.level],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}const c=a.videoCodec,d=l.PTSKnown||!l.live,h=(t=i.initSegment)==null?void 0:t.data,u=this._getAudioCodec(a),f=this.transmuxer=this.transmuxer||new Za(this.hls,Z.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=s?s.index:-1,p=g!==-1,m=new qr(i.level,i.sn,i.stats.chunkCount,n.byteLength,g,p),A=this.initPTS[i.cc];f.push(n,h,u,c,i,s,l.totalduration,d,m,A)}onAudioTrackSwitching(e,t){const i=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const 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();const n=this.hls;i&&(n.trigger(v.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),n.trigger(v.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=t.id,s=!!this.hls.audioTracks[i].url;if(s){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=s,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,n,o=!1;for(const a in i){const l=i[a];if(l.id==="main"){if(n=a,s=l,a==="video"){const c=i[a];c&&(this.videoBuffer=c.buffer)}}else o=!0}o&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i&&i.type!==Z.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===M.PARSED&&(this.state=M.IDLE);return}const n=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}onError(e,t){var i;if(t.fatal){this.state=M.ERROR;return}switch(t.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Z.MAIN,t);break;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===M.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===ae.LEVEL&&(this.state=M.IDLE);break;case D.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case D.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){const{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!fe.getBuffered(e).length){const i=this.state!==M.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=M.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==de.AUDIO||this.audioOnly&&!this.altAudio){const i=(t===de.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,Z.MAIN)}}onLevelsUpdated(e,t){this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const s=fe.getBuffered(e),o=(s.length?s.start(0):0)-i;o>0&&(o<this.config.maxBufferHole||o<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${t}`),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=!0,this._doFragLoad(e,t).then(i=>{const{hls:s}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=M.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=e.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),s.trigger(v.FRAG_LOADED,i),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const i="main",{hls:s}=this,{remuxResult:n,chunkMeta:o}=e,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:l,part:c,level:d}=a,{video:h,text:u,id3:f,initSegment:g}=n,{details:p}=d,m=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=M.PARSING,g){if(g!=null&&g.tracks){const b=l.initSegment||l;this._bufferInitSegment(d,g.tracks,b,o),s.trigger(v.FRAG_PARSING_INIT_SEGMENT,{frag:b,id:i,tracks:g.tracks})}const A=g.initPTS,T=g.timescale;W(A)&&(this.initPTS[l.cc]={baseTime:A,timescale:T},s.trigger(v.INIT_PTS_FOUND,{frag:l,id:i,initPTS:A,timescale:T}))}if(h&&n.independent!==!1){if(p){const{startPTS:A,endPTS:T,startDTS:b,endDTS:y}=h;if(c)c.elementaryStreams[h.type]={startPTS:A,endPTS:T,startDTS:b,endDTS:y};else if(h.firstKeyFrame&&h.independent&&o.id===1&&(this.couldBacktrack=!0),h.dropped&&h.independent){const x=this.getMainFwdBufferInfo(),E=(x?x.end:this.getLoadPosition())+this.config.maxBufferHole,S=h.firstKeyFramePTS?h.firstKeyFramePTS:A;if(E<S-this.config.maxBufferHole){this.backtrack(l);return}l.setElementaryStreamInfo(h.type,l.start,T,l.start,y,!0)}l.setElementaryStreamInfo(h.type,A,T,b,y),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(h,l,c,o)}}else if(n.independent===!1){this.backtrack(l);return}if(m){const{startPTS:A,endPTS:T,startDTS:b,endDTS:y}=m;c&&(c.elementaryStreams[de.AUDIO]={startPTS:A,endPTS:T,startDTS:b,endDTS:y}),l.setElementaryStreamInfo(de.AUDIO,A,T,b,y),this.bufferFragmentData(m,l,c,o)}if(p&&f!=null&&(t=f.samples)!=null&&t.length){const A={id:i,frag:l,details:p,samples:f.samples};s.trigger(v.FRAG_PARSING_METADATA,A)}if(p&&u){const A={id:i,frag:l,details:p,samples:u.samples};s.trigger(v.FRAG_PARSING_USERDATA,A)}}_bufferInitSegment(e,t,i,s){if(this.state!==M.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:n,video:o,audiovideo:a}=t;if(n){let l=e.audioCodec;const c=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5"),n.metadata.channelCount!==1&&c.indexOf("firefox")===-1&&(l="mp4a.40.5")),c.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),n.levelCodec=l,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${n.codec}]`)}o&&(o.levelCodec=e.videoCodec,o.id="main",this.log(`Init video buffer, container:${o.container}, codecs[level/parsed]=[${e.videoCodec||""}/${o.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.attrs.CODECS||""}/${a.codec}]`),this.hls.trigger(v.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{const d=t[l].initSegment;d!=null&&d.byteLength&&this.hls.trigger(v.BUFFER_APPENDING,{type:l,data:d,frag:i,part:null,chunkMeta:s,parent:i.type})}),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Z.MAIN)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=M.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(fe.isBuffered(e,i)?t=this.getAppendedFrag(i):fe.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const s=this.fragPlaying,n=t.level;(!s||t.sn!==s.sn||s.level!==n||t.urlId!==s.urlId)&&(this.fragPlaying=t,this.hls.trigger(v.FRAG_CHANGED,{frag:t}),(!s||s.level!==n)&&this.hls.trigger(v.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,i=this.currentFrag;if(i&&W(t)&&W(i.programDateTime)){const s=i.programDateTime+(t-i.start)*1e3;return new Date(s)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class mi{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){const 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_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class Mu{constructor(e,t,i,s=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 mi(e),this.fast_=new mi(t),this.defaultTTFB_=s,this.ttfb_=new mi(e)}update(e,t){const{slow_:i,fast_:s,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new mi(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new mi(t,s.getEstimate(),s.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new mi(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,s=e/1e3,n=i/s;this.fast_.sample(s,n),this.slow_.sample(s,n)}sampleTTFB(e){const 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_}destroy(){}}class Fu{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=e;const t=e.config;this.bwEstimator=new Mu(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:e}=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)}unregisterListeners(){const{hls:e}=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)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(e,t){var i;const s=t.frag;this.ignoreFragment(s)||(this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(e,t){this.clearTimer()}getTimeToLoadFrag(e,t,i,s){const n=e+i/t,o=s?this.lastLevelLoadSec:0;return n+o}onLevelLoaded(e,t){const i=this.hls.config,{total:s,bwEstimate:n}=t.stats;W(s)&&W(n)&&(this.lastLevelLoadSec=8*s/n),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}_abandonRulesCheck(){const{fragCurrent:e,partCurrent:t,hls:i}=this,{autoLevelEnabled:s,media:n}=i;if(!e||!n)return;const o=performance.now(),a=t?t.stats:e.stats,l=t?t.duration:e.duration,c=o-a.loading.start;if(a.aborted||a.loaded&&a.loaded===a.total||e.level===0){this.clearTimer(),this._nextAutoLevel=-1;return}if(!s||n.paused||!n.playbackRate||!n.readyState)return;const d=i.mainForwardBufferInfo;if(d===null)return;const h=this.bwEstimator.getEstimateTTFB(),u=Math.abs(n.playbackRate);if(c<=Math.max(h,1e3*(l/(u*2))))return;const f=d.len/u;if(f>=2*l/u)return;const g=a.loading.first?a.loading.first-a.loading.start:-1,p=a.loaded&&g>-1,m=this.bwEstimator.getEstimate(),{levels:A,minAutoLevel:T}=i,b=A[e.level],y=a.total||Math.max(a.loaded,Math.round(l*b.maxBitrate/8));let x=c-g;x<1&&p&&(x=Math.min(c,a.loaded*8/m));const E=p?a.loaded*1e3/x:0,S=E?(y-a.loaded)/E:y*8/m+h/1e3;if(S<=f)return;const R=E?E*8:m;let w=Number.POSITIVE_INFINITY,I;for(I=e.level-1;I>T;I--){const O=A[I].maxBitrate;if(w=this.getTimeToLoadFrag(h/1e3,R,l*O,!A[I].details),w<f)break}w>=S||w>l*10||(i.nextLoadLevel=I,p?this.bwEstimator.sample(c-Math.min(h,g),a.loaded):this.bwEstimator.sampleTTFB(c),this.clearTimer(),C.warn(`[abr] Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} is loading too slowly;
72
+ initSegmentChange: ${R}`);const I=new Iu(i,s,t,a,d);this.configureTransmuxer(I)}if(this.frag=n,this.part=o,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:p,chunkMeta:c,state:w},e instanceof ArrayBuffer?[e]:[]);else if(f){const I=f.push(e,p,c,w);Hs(I)?(f.async=!0,I.then(O=>{this.handleTransmuxComplete(O)}).catch(O=>{this.transmuxerError(O,c,"transmuxer-interface push error")})):(f.async=!1,this.handleTransmuxComplete(I))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let i=t.flush(e);Hs(i)||t.async?(Hs(i)||(i=Promise.resolve(i)),i.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")})):this.handleFlushResult(i,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}onWorkerMessage(e){const t=e.data,i=this.hls;switch(t.event){case"init":{var s;const n=(s=this.workerContext)==null?void 0:s.objectURL;n&&self.URL.revokeObjectURL(n);break}case"transmuxComplete":{this.handleTransmuxComplete(t.data);break}case"flush":{this.onFlush(t.data);break}case"workerLog":C[t.data.logType]&&C[t.data.logType](t.data.message);break;default:{t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,i.trigger(t.event,t.data);break}}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Lu=250,dn=2,Ru=.1,Du=.05;class ku{constructor(e,t,i,s){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=s}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:i,media:s,stalled:n}=this;if(s===null)return;const{currentTime:o,seeking:a}=s,l=this.seeking&&!a,c=!this.seeking&&a;if(this.seeking=a,o!==e){if(this.moved=!0,n!==null){if(this.stallReported){const A=self.performance.now()-n;C.warn(`playback not stuck anymore @${o}, after ${Math.round(A)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(c||l){this.stalled=null;return}if(s.paused&&!a||s.ended||s.playbackRate===0||!fe.getBuffered(s).length)return;const d=fe.bufferInfo(s,o,0),h=d.len>0,u=d.nextStart||0;if(!h&&!u)return;if(a){const A=d.len>dn,x=!u||t&&t.start<=o||u-o>dn&&!this.fragmentTracker.getPartialFragment(o);if(A||x)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var f;const A=Math.max(u,d.start||0)-o,x=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,y=(x==null||(f=x.details)==null?void 0:f.live)?x.details.targetduration*2:dn,T=this.fragmentTracker.getPartialFragment(o);if(A>0&&(A<=y||T)){this._trySkipBufferHole(T);return}}const g=self.performance.now();if(n===null){this.stalled=g;return}const p=g-n;if(!a&&p>=Lu&&(this._reportStall(d),!this.media))return;const m=fe.bufferInfo(s,o,i.maxBufferHole);this._tryFixBufferStall(m,p)}_tryFixBufferStall(e,t){const{config:i,fragmentTracker:s,media:n}=this;if(n===null)return;const o=n.currentTime,a=s.getPartialFragment(o);a&&(this._trySkipBufferHole(a)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-o<i.maxBufferHole)&&t>i.highBufferWatchdogPeriod*1e3&&(C.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:i,stallReported:s}=this;if(!s&&i){this.stallReported=!0;const n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);C.warn(n.message),t.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:i,media:s}=this;if(s===null)return 0;const n=s.currentTime,o=fe.bufferInfo(s,n,0),a=n<o.start?o.start:o.nextStart;if(a){const l=o.len<=t.maxBufferHole,c=o.len>0&&o.len<1&&s.readyState<3,d=a-n;if(d>0&&(l||c)){if(d>t.maxBufferHole){const{fragmentTracker:u}=this;let f=!1;if(n===0){const g=u.getAppendedFrag(0,Z.MAIN);g&&a<g.end&&(f=!0)}if(!f){const g=e||u.getAppendedFrag(n,Z.MAIN);if(g){let p=!1,m=g.end;for(;m<a;){const A=u.getPartialFragment(m);if(A)m+=A.duration;else{p=!0;break}}if(p)return 0}}}const h=Math.max(a+Du,n+Ru);if(C.warn(`skipping hole, adjusting currentTime from ${n} to ${h}`),this.moved=!0,this.stalled=null,s.currentTime=h,e&&!e.gap){const u=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${h}`);i.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:e})}return h}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:i,nudgeRetry:s}=this;if(i===null)return;const n=i.currentTime;if(this.nudgeRetry++,s<e.nudgeMaxRetry){const o=n+(s+1)*e.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${n} to ${o}`);C.warn(a.message),i.currentTime=o,t.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const o=new Error(`Playhead still not moving while enough data buffered @${n} after ${e.nudgeMaxRetry} nudges`);C.error(o.message),t.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,error:o,fatal:!0})}}}const Pu=100;class Ou extends Qr{constructor(e,t,i){super(e,t,i,"[stream-controller]",Z.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{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_LOADED,this.onLevelLoaded,this),e.on(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(v.ERROR,this.onError,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(){const{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_LOADED,this.onLevelLoaded,this),e.off(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(v.ERROR,this.onError,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._unregisterListeners(),this.onMediaDetaching()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:i}=this;if(this.stopLoad(),this.setInterval(Pu),this.level=-1,!this.startFragRequested){let s=i.startLevel;s===-1&&(i.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=i.nextAutoLevel),this.level=i.nextLoadLevel=s,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=M.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=M.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case M.WAITING_LEVEL:{var e;const{levels:i,level:s}=this,n=i==null||(e=i[s])==null?void 0:e.details;if(n&&(!n.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(n))break;this.state=M.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=M.IDLE;break}break}case M.FRAG_LOADING_WAITING_RETRY:{var t;const i=self.performance.now(),s=this.retryDate;(!s||i>=s||(t=this.media)!=null&&t.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=M.IDLE)}break}this.state===M.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:s}=this,{config:n,nextLoadLevel:o}=e;if(t===null||!s&&(this.startFragRequested||!n.startFragPrefetch)||this.altAudio&&this.audioOnly||!(i!=null&&i[o]))return;const a=i[o],l=this.getMainFwdBufferInfo();if(l===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(l,c)){const m={};this.altAudio&&(m.type="video"),this.hls.trigger(v.BUFFER_EOS,m),this.state=M.ENDED;return}e.loadLevel!==o&&e.manualLevel===-1&&this.log(`Adapting to level ${o} from level ${this.level}`),this.level=e.nextLoadLevel=o;const d=a.details;if(!d||this.state===M.WAITING_LEVEL||d.live&&this.levelLastLoaded!==o){this.level=o,this.state=M.WAITING_LEVEL;return}const h=l.len,u=this.getMaxBufferLength(a.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>l.end&&(this.backtrackFragment=null);const f=this.backtrackFragment?this.backtrackFragment.start:l.end;let g=this.getNextFragment(f,d);if(this.couldBacktrack&&!this.fragPrevious&&g&&g.sn!=="initSegment"&&this.fragmentTracker.getState(g)!==ke.OK){var p;const A=((p=this.backtrackFragment)!=null?p:g).sn-d.startSN,x=d.fragments[A-1];x&&g.cc===x.cc&&(g=x,this.fragmentTracker.removeFragment(x))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,f)){if(!g.gap){const A=this.audioOnly&&!this.altAudio?de.AUDIO:de.VIDEO,x=(A===de.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;x&&this.afterBufferFlushed(x,A,Z.MAIN)}g=this.getNextFragmentLoopLoading(g,d,l,Z.MAIN,u)}g&&(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,a,f))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);this.fragCurrent=e,s===ke.NOT_LOADED||s===ke.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):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)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Z.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let i;const s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const n=this.getLevelDetails();if(n!=null&&n.live){const a=this.getMainFwdBufferInfo();if(!a||a.len<n.targetduration*2)return}if(!t.paused&&e){const a=this.hls.nextLoadLevel,l=e[a],c=this.fragLastKbps;c&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:i=0}else i=0;const o=this.getBufferedFrag(t.currentTime+i);if(o){const a=this.followingBufferedFrag(o);if(a){this.abortCurrentFrag();const l=a.maxStartPTS?a.maxStartPTS:a.start,c=a.duration,d=Math.max(o.end,l+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*.5),c*.75));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case M.KEY_LOADING:case M.FRAG_LOADING:case M.FRAG_LOADING_WAITING_RETRY:case M.PARSING:case M.PARSED:this.state=M.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new ku(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;W(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(v.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.levels=this.fragPlaying=this.backtrackFragment=null,this.altAudio=this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1,n;t.levels.forEach(o=>{n=o.audioCodec,n&&(n.indexOf("mp4a.40.2")!==-1&&(i=!0),n.indexOf("mp4a.40.5")!==-1&&(s=!0))}),this.audioCodecSwitch=i&&s&&!Xh(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==M.IDLE)return;const s=i[t.level];(!s.details||s.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(s.details))&&(this.state=M.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:s}=this,n=t.level,o=t.details,a=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${a}`);const l=s[n],c=this.fragCurrent;c&&(this.state===M.FRAG_LOADING||this.state===M.FRAG_LOADING_WAITING_RETRY)&&(c.level!==t.level||c.urlId!==l.urlId)&&c.loader&&this.abortCurrentFrag();let d=0;if(o.live||(i=l.details)!=null&&i.live){if(o.fragments[0]||(o.deltaUpdateFailed=!0),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,l.details)}if(l.details=o,this.levelLastLoaded=n,this.hls.trigger(v.LEVEL_UPDATED,{details:o,level:n}),this.state===M.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=M.IDLE}this.startFragRequested?o.live&&this.synchronizeToLiveEdge(o):this.setStartPosition(o,d),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:s,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}const a=o[i.level],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}const c=a.videoCodec,d=l.PTSKnown||!l.live,h=(t=i.initSegment)==null?void 0:t.data,u=this._getAudioCodec(a),f=this.transmuxer=this.transmuxer||new Za(this.hls,Z.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=s?s.index:-1,p=g!==-1,m=new qr(i.level,i.sn,i.stats.chunkCount,n.byteLength,g,p),A=this.initPTS[i.cc];f.push(n,h,u,c,i,s,l.totalduration,d,m,A)}onAudioTrackSwitching(e,t){const i=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const 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();const n=this.hls;i&&(n.trigger(v.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),n.trigger(v.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=t.id,s=!!this.hls.audioTracks[i].url;if(s){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=s,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,n,o=!1;for(const a in i){const l=i[a];if(l.id==="main"){if(n=a,s=l,a==="video"){const c=i[a];c&&(this.videoBuffer=c.buffer)}}else o=!0}o&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i&&i.type!==Z.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===M.PARSED&&(this.state=M.IDLE);return}const n=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}onError(e,t){var i;if(t.fatal){this.state=M.ERROR;return}switch(t.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Z.MAIN,t);break;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===M.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===ae.LEVEL&&(this.state=M.IDLE);break;case D.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case D.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){const{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!fe.getBuffered(e).length){const i=this.state!==M.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=M.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==de.AUDIO||this.audioOnly&&!this.altAudio){const i=(t===de.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,Z.MAIN)}}onLevelsUpdated(e,t){this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const s=fe.getBuffered(e),o=(s.length?s.start(0):0)-i;o>0&&(o<this.config.maxBufferHole||o<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${t}`),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=!0,this._doFragLoad(e,t).then(i=>{const{hls:s}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=M.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=e.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),s.trigger(v.FRAG_LOADED,i),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const i="main",{hls:s}=this,{remuxResult:n,chunkMeta:o}=e,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:l,part:c,level:d}=a,{video:h,text:u,id3:f,initSegment:g}=n,{details:p}=d,m=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=M.PARSING,g){if(g!=null&&g.tracks){const b=l.initSegment||l;this._bufferInitSegment(d,g.tracks,b,o),s.trigger(v.FRAG_PARSING_INIT_SEGMENT,{frag:b,id:i,tracks:g.tracks})}const A=g.initPTS,x=g.timescale;W(A)&&(this.initPTS[l.cc]={baseTime:A,timescale:x},s.trigger(v.INIT_PTS_FOUND,{frag:l,id:i,initPTS:A,timescale:x}))}if(h&&n.independent!==!1){if(p){const{startPTS:A,endPTS:x,startDTS:b,endDTS:y}=h;if(c)c.elementaryStreams[h.type]={startPTS:A,endPTS:x,startDTS:b,endDTS:y};else if(h.firstKeyFrame&&h.independent&&o.id===1&&(this.couldBacktrack=!0),h.dropped&&h.independent){const T=this.getMainFwdBufferInfo(),E=(T?T.end:this.getLoadPosition())+this.config.maxBufferHole,S=h.firstKeyFramePTS?h.firstKeyFramePTS:A;if(E<S-this.config.maxBufferHole){this.backtrack(l);return}l.setElementaryStreamInfo(h.type,l.start,x,l.start,y,!0)}l.setElementaryStreamInfo(h.type,A,x,b,y),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(h,l,c,o)}}else if(n.independent===!1){this.backtrack(l);return}if(m){const{startPTS:A,endPTS:x,startDTS:b,endDTS:y}=m;c&&(c.elementaryStreams[de.AUDIO]={startPTS:A,endPTS:x,startDTS:b,endDTS:y}),l.setElementaryStreamInfo(de.AUDIO,A,x,b,y),this.bufferFragmentData(m,l,c,o)}if(p&&f!=null&&(t=f.samples)!=null&&t.length){const A={id:i,frag:l,details:p,samples:f.samples};s.trigger(v.FRAG_PARSING_METADATA,A)}if(p&&u){const A={id:i,frag:l,details:p,samples:u.samples};s.trigger(v.FRAG_PARSING_USERDATA,A)}}_bufferInitSegment(e,t,i,s){if(this.state!==M.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:n,video:o,audiovideo:a}=t;if(n){let l=e.audioCodec;const c=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5"),n.metadata.channelCount!==1&&c.indexOf("firefox")===-1&&(l="mp4a.40.5")),c.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),n.levelCodec=l,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${n.codec}]`)}o&&(o.levelCodec=e.videoCodec,o.id="main",this.log(`Init video buffer, container:${o.container}, codecs[level/parsed]=[${e.videoCodec||""}/${o.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.attrs.CODECS||""}/${a.codec}]`),this.hls.trigger(v.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{const d=t[l].initSegment;d!=null&&d.byteLength&&this.hls.trigger(v.BUFFER_APPENDING,{type:l,data:d,frag:i,part:null,chunkMeta:s,parent:i.type})}),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Z.MAIN)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=M.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(fe.isBuffered(e,i)?t=this.getAppendedFrag(i):fe.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const s=this.fragPlaying,n=t.level;(!s||t.sn!==s.sn||s.level!==n||t.urlId!==s.urlId)&&(this.fragPlaying=t,this.hls.trigger(v.FRAG_CHANGED,{frag:t}),(!s||s.level!==n)&&this.hls.trigger(v.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,i=this.currentFrag;if(i&&W(t)&&W(i.programDateTime)){const s=i.programDateTime+(t-i.start)*1e3;return new Date(s)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class vi{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){const 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_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class Mu{constructor(e,t,i,s=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 vi(e),this.fast_=new vi(t),this.defaultTTFB_=s,this.ttfb_=new vi(e)}update(e,t){const{slow_:i,fast_:s,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new vi(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new vi(t,s.getEstimate(),s.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new vi(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,s=e/1e3,n=i/s;this.fast_.sample(s,n),this.slow_.sample(s,n)}sampleTTFB(e){const 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_}destroy(){}}class Fu{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=e;const t=e.config;this.bwEstimator=new Mu(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:e}=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)}unregisterListeners(){const{hls:e}=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)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(e,t){var i;const s=t.frag;this.ignoreFragment(s)||(this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(e,t){this.clearTimer()}getTimeToLoadFrag(e,t,i,s){const n=e+i/t,o=s?this.lastLevelLoadSec:0;return n+o}onLevelLoaded(e,t){const i=this.hls.config,{total:s,bwEstimate:n}=t.stats;W(s)&&W(n)&&(this.lastLevelLoadSec=8*s/n),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}_abandonRulesCheck(){const{fragCurrent:e,partCurrent:t,hls:i}=this,{autoLevelEnabled:s,media:n}=i;if(!e||!n)return;const o=performance.now(),a=t?t.stats:e.stats,l=t?t.duration:e.duration,c=o-a.loading.start;if(a.aborted||a.loaded&&a.loaded===a.total||e.level===0){this.clearTimer(),this._nextAutoLevel=-1;return}if(!s||n.paused||!n.playbackRate||!n.readyState)return;const d=i.mainForwardBufferInfo;if(d===null)return;const h=this.bwEstimator.getEstimateTTFB(),u=Math.abs(n.playbackRate);if(c<=Math.max(h,1e3*(l/(u*2))))return;const f=d.len/u;if(f>=2*l/u)return;const g=a.loading.first?a.loading.first-a.loading.start:-1,p=a.loaded&&g>-1,m=this.bwEstimator.getEstimate(),{levels:A,minAutoLevel:x}=i,b=A[e.level],y=a.total||Math.max(a.loaded,Math.round(l*b.maxBitrate/8));let T=c-g;T<1&&p&&(T=Math.min(c,a.loaded*8/m));const E=p?a.loaded*1e3/T:0,S=E?(y-a.loaded)/E:y*8/m+h/1e3;if(S<=f)return;const R=E?E*8:m;let w=Number.POSITIVE_INFINITY,I;for(I=e.level-1;I>x;I--){const O=A[I].maxBitrate;if(w=this.getTimeToLoadFrag(h/1e3,R,l*O,!A[I].details),w<f)break}w>=S||w>l*10||(i.nextLoadLevel=I,p?this.bwEstimator.sample(c-Math.min(h,g),a.loaded):this.bwEstimator.sampleTTFB(c),this.clearTimer(),C.warn(`[abr] Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} is loading too slowly;
73
73
  Time to underbuffer: ${f.toFixed(3)} s
74
74
  Estimated load time for current fragment: ${S.toFixed(3)} s
75
75
  Estimated load time for down switch fragment: ${w.toFixed(3)} s
76
76
  TTFB estimate: ${g}
77
77
  Current BW estimate: ${W(m)?(m/1024).toFixed(3):"Unknown"} Kb/s
78
78
  New BW estimate: ${(this.bwEstimator.getEstimate()/1024).toFixed(3)} Kb/s
79
- Aborting and switching to level ${I}`),e.loader&&(this.fragCurrent=this.partCurrent=null,e.abortRequests()),i.trigger(v.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:a}))}onFragLoaded(e,{frag:t,part:i}){const s=i?i.stats:t.stats;if(t.type===Z.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),this.lastLoadedFragLevel=t.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){const n=i?i.duration:t.duration,o=this.hls.levels[t.level],a=(o.loaded?o.loaded.bytes:0)+s.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){const n={stats:s,frag:t,part:i,id:t.type};this.onFragBuffered(v.FRAG_BUFFERED,n),t.bitrateTest=!1}}}onFragBuffered(e,t){const{frag:i,part:s}=t,n=s!=null&&s.stats.loaded?s.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;const 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.bwEstimator.getEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Z.MAIN||e.sn==="initSegment"}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){const e=this._nextAutoLevel,t=this.bwEstimator;if(e!==-1&&!t.canEstimate())return e;let i=this.getNextABRAutoLevel();if(e!==-1){const s=this.hls.levels;if(s.length>Math.max(e,i)&&s[e].loadError<=s[i].loadError)return e}return e!==-1&&(i=Math.min(e,i)),i}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this,{maxAutoLevel:s,config:n,minAutoLevel:o,media:a}=i,l=t?t.duration:e?e.duration:0,c=a&&a.playbackRate!==0?Math.abs(a.playbackRate):1,d=this.bwEstimator?this.bwEstimator.getEstimate():n.abrEwmaDefaultEstimate,h=i.mainForwardBufferInfo,u=(h?h.len:0)/c;let f=this.findBestLevel(d,o,s,u,n.abrBandWidthFactor,n.abrBandWidthUpFactor);if(f>=0)return f;C.trace(`[abr] ${u?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let g=l?Math.min(l,n.maxStarvationDelay):n.maxStarvationDelay,p=n.abrBandWidthFactor,m=n.abrBandWidthUpFactor;if(!u){const A=this.bitrateTestDelay;A&&(g=(l?Math.min(l,n.maxLoadingDelay):n.maxLoadingDelay)-A,C.trace(`[abr] bitrate test took ${Math.round(1e3*A)}ms, set first fragment max fetchDuration to ${Math.round(1e3*g)} ms`),p=m=1)}return f=this.findBestLevel(d,o,s,u+g,p,m),Math.max(f,0)}findBestLevel(e,t,i,s,n,o){var a;const{fragCurrent:l,partCurrent:c,lastLoadedFragLevel:d}=this,{levels:h}=this.hls,u=h[d],f=!!(u!=null&&(a=u.details)!=null&&a.live),g=u==null?void 0:u.codecSet,p=c?c.duration:l?l.duration:0,m=this.bwEstimator.getEstimateTTFB()/1e3;let A=t,T=-1;for(let b=i;b>=t;b--){const y=h[b];if(!y||g&&y.codecSet!==g){y&&(A=Math.min(b,A),T=Math.max(b,T));continue}T!==-1&&C.trace(`[abr] Skipped level(s) ${A}-${T} with CODECS:"${h[T].attrs.CODECS}"; not compatible with "${u.attrs.CODECS}"`);const x=y.details,E=(c?x==null?void 0:x.partTarget:x==null?void 0:x.averagetargetduration)||p;let S;b<=d?S=n*e:S=o*e;const R=h[b].maxBitrate,w=this.getTimeToLoadFrag(m,S,R*E,x===void 0);if(C.trace(`[abr] level:${b} adjustedbw-bitrate:${Math.round(S-R)} avgDuration:${E.toFixed(1)} maxFetchDuration:${s.toFixed(1)} fetchDuration:${w.toFixed(1)}`),S>R&&(w===0||!W(w)||f&&!this.bitrateTestDelay||w<s))return b}return-1}set nextAutoLevel(e){this._nextAutoLevel=e}}class Ja{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=Nu(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function Nu(r,e){const t=new Uint8Array(e);let i=0;for(let s=0;s<r.length;s++){const n=r[s];t.set(n,i),i+=n.length}return t}const Qa=100;class Bu extends Qr{constructor(e,t,i){super(e,t,i,"[audio-stream-controller]",Z.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{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.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.ERROR,this.onError,this),e.on(v.BUFFER_RESET,this.onBufferReset,this),e.on(v.BUFFER_CREATED,this.onBufferCreated,this),e.on(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{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.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.ERROR,this.onError,this),e.off(v.BUFFER_RESET,this.onBufferReset,this),e.off(v.BUFFER_CREATED,this.onBufferCreated,this),e.off(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n}){if(i==="main"){const o=t.cc;this.initPTS[t.cc]={baseTime:s,timescale:n},this.log(`InitPTS for cc: ${o} found from main: ${s}`),this.videoTrackCC=o,this.state===M.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=M.STOPPED;return}const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(Qa),t>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=M.IDLE):(this.loadedmetadata=!1,this.state=M.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case M.IDLE:this.doTickIdle();break;case M.WAITING_TRACK:{var e;const{levels:i,trackId:s}=this,n=i==null||(e=i[s])==null?void 0:e.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=M.WAITING_INIT_PTS}break}case M.FRAG_LOADING_WAITING_RETRY:{var t;const i=performance.now(),s=this.retryDate;(!s||i>=s||(t=this.media)!=null&&t.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=M.IDLE);break}case M.WAITING_INIT_PTS:{const i=this.waitingData;if(i){const{frag:s,part:n,cache:o,complete:a}=i;if(this.initPTS[s.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=M.FRAG_LOADING;const l=o.flush(),c={frag:s,part:n,payload:l,networkDetails:null};this._handleFragmentLoadProgress(c),a&&super._handleFragmentLoadComplete(c)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${s.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),c=fe.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);Yr(c.end,this.config.maxFragLookUpTolerance,s)<0&&(this.log(`Waiting fragment cc (${s.cc}) @ ${s.start} cancelled because another fragment at ${c.end} is needed`),this.clearWaitingFragment())}}else this.state=M.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=M.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:i,trackId:s}=this,n=e.config;if(!(t!=null&&t[s])||!i&&(this.startFragRequested||!n.startFragPrefetch))return;const o=t[s],a=o.details;if(!a||a.live&&this.levelLastLoaded!==s||this.waitForCdnTuneIn(a)){this.state=M.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,de.AUDIO,Z.AUDIO));const c=this.getFwdBufferInfo(l,Z.AUDIO);if(c===null)return;const{bufferedTrack:d,switchingTrack:h}=this;if(!h&&this._streamEnded(c,a)){e.trigger(v.BUFFER_EOS,{type:"audio"}),this.state=M.ENDED;return}const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Z.MAIN),f=c.len,g=this.getMaxBufferLength(u==null?void 0:u.len);if(f>=g&&!h)return;const m=a.fragments[0].start;let A=c.end;if(h&&i){const x=this.getLoadPosition();d&&h.attrs!==d.attrs&&(A=x),a.PTSKnown&&x<m&&(c.end>m||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=m+.05)}let T=this.getNextFragment(A,a),b=!1;if(T&&this.isLoopLoading(T,A)&&(b=!!T.gap,T=this.getNextFragmentLoopLoading(T,a,c,Z.MAIN,g)),!T){this.bufferFlushed=!0;return}const y=u&&T.start>u.end+a.targetduration;if(y||!(u!=null&&u.len)&&c.len){const x=this.getAppendedFrag(T.start,Z.MAIN);if(x===null||(b||(b=!!x.gap||!!y&&u.len===0),y&&!b||b&&c.nextStart&&c.nextStart<x.end))return}this.loadFragment(T,o,A)}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new Ji(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?this.setInterval(Qa):this.resetTransmuxer(),i?(this.switchingTrack=t,this.state=M.IDLE):(this.switchingTrack=null,this.bufferedTrack=t,this.state=M.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(v.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var i;if(this.mainDetails==null){this.cachedTrackLoadedData=t;return}const{levels:s}=this,{details:n,id:o}=t;if(!s){this.warn(`Audio tracks were reset while loading level ${o}`);return}this.log(`Track ${o} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const a=s[o];let l=0;if(n.live||(i=a.details)!=null&&i.live){const c=this.mainDetails;if(n.fragments[0]||(n.deltaUpdateFailed=!0),n.deltaUpdateFailed||!c)return;!a.details&&n.hasProgramDateTime&&c.hasProgramDateTime?(La(n,c),l=n.fragments[0].start):l=this.alignPlaylists(n,a.details)}a.details=n,this.levelLastLoaded=o,!this.startFragRequested&&(this.mainDetails||!n.live)&&this.setStartPosition(a.details,l),this.state===M.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=M.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:s,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}const c=l[a];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const d=c.details;if(!d){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const h=o.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Za(this.hls,Z.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[i.cc],g=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){const m=s?s.index:-1,A=m!==-1,T=new qr(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,A);u.push(n,g,h,"",i,s,d.totalduration,!1,T,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:p}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Ja,complete:!1};p.push(new Uint8Array(n)),this.waitingVideoCC=this.videoTrackCC,this.state=M.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i.type!==Z.AUDIO){if(!this.loadedmetadata&&i.type===Z.MAIN){const n=this.videoBuffer||this.media;n&&fe.getBuffered(n).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(i.sn!=="initSegment"){this.fragPrevious=i;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(v.AUDIO_TRACK_SWITCHED,je({},n)))}this.fragBufferedComplete(i,s)}onError(e,t){var i;if(t.fatal){this.state=M.ERROR;return}switch(t.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Z.AUDIO,t);break;case D.AUDIO_TRACK_LOAD_ERROR:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===M.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===ae.AUDIO_TRACK&&(this.state=M.IDLE);break;case D.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case D.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushed(e,{type:t}){t===de.AUDIO&&(this.bufferFlushed=!0,this.state===M.ENDED&&(this.state=M.IDLE))}_handleTransmuxComplete(e){var t;const i="audio",{hls:s}=this,{remuxResult:n,chunkMeta:o}=e,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:l,part:c,level:d}=a,{details:h}=d,{audio:u,text:f,id3:g,initSegment:p}=n;if(this.fragContextChanged(l)||!h){this.fragmentTracker.removeFragment(l);return}if(this.state=M.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const m=l.initSegment||l;this._bufferInitSegment(p.tracks,m,o),s.trigger(v.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:i,tracks:p.tracks})}if(u){const{startPTS:m,endPTS:A,startDTS:T,endDTS:b}=u;c&&(c.elementaryStreams[de.AUDIO]={startPTS:m,endPTS:A,startDTS:T,endDTS:b}),l.setElementaryStreamInfo(de.AUDIO,m,A,T,b),this.bufferFragmentData(u,l,c,o)}if(g!=null&&(t=g.samples)!=null&&t.length){const m=Ce({id:i,frag:l,details:h},g);s.trigger(v.FRAG_PARSING_METADATA,m)}if(f){const m=Ce({id:i,frag:l,details:h},f);s.trigger(v.FRAG_PARSING_USERDATA,m)}}_bufferInitSegment(e,t,i){if(this.state!==M.PARSING)return;e.video&&delete e.video;const s=e.audio;if(!s)return;s.levelCodec=s.codec,s.id="audio",this.log(`Init audio buffer, container:${s.container}, codecs[parsed]=[${s.codec}]`),this.hls.trigger(v.BUFFER_CODECS,e);const n=s.initSegment;if(n!=null&&n.byteLength){const o={type:"audio",frag:t,part:null,chunkMeta:i,parent:t.type,data:n};this.hls.trigger(v.BUFFER_APPENDING,o)}this.tick()}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||s===ke.NOT_LOADED||s===ke.PARTIAL){var n;e.sn==="initSegment"?this._loadInitSegment(e,t):(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=M.WAITING_INIT_PTS):(this.startFragRequested=!0,super.loadFragment(e,t,i))}else this.clearTrackerIfNeeded(e)}completeAudioSwitch(e){const{hls:t,media:i,bufferedTrack:s}=this,n=s==null?void 0:s.attrs,o=e.attrs;i&&n&&(n.CHANNELS!==o.CHANNELS||n.NAME!==o.NAME||n.LANGUAGE!==o.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(v.AUDIO_TRACK_SWITCHED,je({},e))}}class Uu extends Kr{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{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(){const{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.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:s,details:n}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==s){this.warn(`Track with id:${i} and group:${s} not found in active group ${o.groupId}`);return}const a=o.details;o.details=t.details,this.log(`audio-track ${i} "${o.name}" lang:${o.lang} group:${s} 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){const t=this.hls.levels[e];if(!(t!=null&&t.audioGroupIds))return;const i=t.audioGroupIds[t.urlId];if(this.groupId!==i){this.groupId=i||null;const s=this.tracks.filter(o=>!i||o.groupId===i);this.selectDefaultTrack&&!s.some(o=>o.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=s;const n={audioTracks:s};this.log(`Updating audio tracks, ${s.length} track(s) found in group:${i}`),this.hls.trigger(v.AUDIO_TRACKS_UPDATED,n),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(e,t){t.fatal||!t.context||t.context.type===ae.AUDIO_TRACK&&t.context.id===this.trackId&&t.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(t))}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn("Invalid id passed to audio-track controller");return}this.clearTimer();const i=this.currentTrack;t[this.trackId];const s=t[e],{groupId:n,name:o}=s;if(this.log(`Switching to audio-track ${e} "${o}" lang:${s.lang} group:${n}`),this.trackId=e,this.currentTrack=s,this.selectDefaultTrack=!1,this.hls.trigger(v.AUDIO_TRACK_SWITCHING,je({},s)),s.details&&!s.details.live)return;const a=this.switchParams(s.url,i==null?void 0:i.details);this.loadPlaylist(a)}selectInitialTrack(){const e=this.tracksInGroup,t=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(t!==-1)this.setAudioTrack(t);else{const i=new Error(`No track found for running audio group-ID: ${this.groupId} track count: ${e.length}`);this.warn(i.message),this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:i})}}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if((!this.selectDefaultTrack||s.default)&&(!e||e.attrs["STABLE-RENDITION-ID"]!==void 0&&e.attrs["STABLE-RENDITION-ID"]===s.attrs["STABLE-RENDITION-ID"]||e.name===s.name&&e.lang===s.lang))return s.id}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(t)){const i=t.id,s=t.groupId;let n=t.url;if(e)try{n=e.addDirectives(n)}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`)}this.log(`loading audio-track playlist ${i} "${t.name}" lang:${t.lang} group:${s}`),this.clearTimer(),this.hls.trigger(v.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:e||null})}}}function _a(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!Hu(r[t].attrs,e[t].attrs))return!1;return!0}function Hu(r,e){const t=r["STABLE-RENDITION-ID"];return t?t===e["STABLE-RENDITION-ID"]:!["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED"].some(i=>r[i]!==e[i])}const $a=500;class Gu extends Qr{constructor(e,t,i){super(e,t,i,"[subtitle-stream-controller]",Z.SUBTITLE),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){const{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.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.ERROR,this.onError,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),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{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.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.ERROR,this.onError,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),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=M.IDLE,this.setInterval($a),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:s}=t;if(this.fragPrevious=i,this.state=M.IDLE,!s)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let o;const a=i.start;for(let c=0;c<n.length;c++)if(a>=n[c].start&&a<=n[c].end){o=n[c];break}const l=i.start+i.duration;o?o.end=l:(o={start:a,end:l},n.push(o)),this.fragmentTracker.fragBuffered(i)}onBufferFlushing(e,t){const{startOffset:i,endOffset:s}=t;if(i===0&&s!==Number.POSITIVE_INFINITY){const{currentTrackId:n,levels:o}=this;if(!o.length||!o[n]||!o[n].details)return;const l=o[n].details.targetduration,c=s-l;if(c<=0)return;t.endOffsetSubtitles=Math.max(0,c),this.tracksBuffered.forEach(d=>{for(let h=0;h<d.length;){if(d[h].end<=c){d.shift();continue}else if(d[h].start<c)d[h].start=c;else break;h++}}),this.fragmentTracker.removeFragmentsInRange(i,c,Z.SUBTITLE)}}onFragBuffered(e,t){if(!this.loadedmetadata&&t.frag.type===Z.MAIN){var i;(i=this.media)!=null&&i.buffered.length&&(this.loadedmetadata=!0)}}onError(e,t){const i=t.frag;(i==null?void 0:i.type)===Z.SUBTITLE&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==M.STOPPED&&(this.state=M.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(_a(this.levels,t)){this.levels=t.map(i=>new Ji(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const s=new Ji(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Z.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){if(this.currentTrackId=t.id,!this.levels.length||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.setInterval($a)}onSubtitleTrackLoaded(e,t){var i;const{details:s,id:n}=t,{currentTrackId:o,levels:a}=this;if(!a.length)return;const l=a[o];if(n>=a.length||n!==o||!l)return;this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(s.live||(i=l.details)!=null&&i.live){const d=this.mainDetails;if(s.deltaUpdateFailed||!d)return;const h=d.fragments[0];l.details?(c=this.alignPlaylists(s,l.details),c===0&&h&&(c=h.start,zr(s,c))):s.hasProgramDateTime&&d.hasProgramDateTime?(La(s,d),c=s.fragments[0].start):h&&(c=h.start,zr(s,c))}l.details=s,this.levelLastLoaded=n,!this.startFragRequested&&(this.mainDetails||!s.live)&&this.setStartPosition(l.details,c),this.tick(),s.live&&!this.fragCurrent&&this.media&&this.state===M.IDLE&&(Qi(null,s.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,s=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&s&&s.key&&s.iv&&s.method==="AES-128"){const o=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer).catch(a=>{throw n.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t}),a}).then(a=>{const 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=M.IDLE})}}doTick(){if(!this.media){this.state=M.IDLE;return}if(this.state===M.IDLE){const{currentTrackId:e,levels:t}=this,i=t[e];if(!t.length||!i||!i.details)return;const s=i.details,n=s.targetduration,{config:o}=this,a=this.getLoadPosition(),l=fe.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],a-n,o.maxBufferHole),{end:c,len:d}=l,h=this.getFwdBufferInfo(this.media,Z.MAIN),u=this.getMaxBufferLength(h==null?void 0:h.len)+n;if(d>u)return;const f=s.fragments,g=f.length,p=s.edge;let m=null;const A=this.fragPrevious;if(c<p){const{maxFragLookUpTolerance:T}=o;m=Qi(A,f,Math.max(f[0].start,c),T),!m&&A&&A.start<f[0].start&&(m=f[0])}else m=f[g-1];if(!m)return;m=this.mapToInitFragWhenRequired(m),this.fragmentTracker.getState(m)===ke.NOT_LOADED&&this.loadFragment(m,i,c)}}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,i){this.fragCurrent=e,e.sn==="initSegment"?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,i))}get mediaBufferTimeRanges(){return new Vu(this.tracksBuffered[this.currentTrackId]||[])}}class Vu{constructor(e){this.buffered=void 0;const t=(i,s,n)=>{if(s=s>>>0,s>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${n})`);return e[s][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}class ju extends Kr{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.trackChangeListener=()=>this.onTextTracksChanged(),this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes(this.trackId)}registerListeners(){const{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(){const{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.trackChangeListener,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),hn(this.media.textTracks).forEach(t=>{fi(t)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,details:s}=t,{trackId:n}=this,o=this.tracksInGroup[n];if(!o){this.warn(`Invalid subtitle track id ${i}`);return}const a=o.details;o.details=t.details,this.log(`subtitle track ${i} loaded [${s.startSN}-${s.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){const t=this.hls.levels[e];if(!(t!=null&&t.textGroupIds))return;const i=t.textGroupIds[t.urlId],s=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==i){const n=this.tracks.filter(l=>!i||l.groupId===i);this.tracksInGroup=n;const o=this.findTrackId(s==null?void 0:s.name)||this.findTrackId();this.groupId=i||null;const a={subtitleTracks:n};this.log(`Updating subtitle tracks, ${n.length} track(s) found in "${i}" group-id`),this.hls.trigger(v.SUBTITLE_TRACKS_UPDATED,a),o!==-1&&this.setSubtitleTrack(o,s)}else this.shouldReloadPlaylist(s)&&this.setSubtitleTrack(this.trackId,s)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if((!this.selectDefaultTrack||s.default)&&(!e||e===s.name))return s.id}return-1}onError(e,t){t.fatal||!t.context||t.context.type===ae.SUBTITLE_TRACK&&t.context.id===this.trackId&&t.context.groupId===this.groupId&&this.checkRetry(t)}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1;const t=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(e,t)}loadPlaylist(e){super.loadPlaylist();const t=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(t)){const i=t.id,s=t.groupId;let n=t.url;if(e)try{n=e.addDirectives(n)}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(v.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:e||null})}}toggleTrackModes(e){const{media:t,trackId:i}=this;if(!t)return;const s=hn(t.textTracks),n=s.filter(a=>a.groupId===this.groupId);if(e===-1)[].slice.call(s).forEach(a=>{a.mode="disabled"});else{const a=n[i];a&&(a.mode="disabled")}const o=n[e];o&&(o.mode=this.subtitleDisplay?"showing":"hidden")}setSubtitleTrack(e,t){var i;const s=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(this.trackId!==e&&this.toggleTrackModes(e),this.trackId===e&&(e===-1||(i=s[e])!=null&&i.details)||e<-1||e>=s.length)return;this.clearTimer();const n=s[e];if(this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:"")),this.trackId=e,n){const{id:o,groupId:a="",name:l,type:c,url:d}=n;this.hls.trigger(v.SUBTITLE_TRACK_SWITCH,{id:o,groupId:a,name:l,type:c,url:d});const h=this.switchParams(n.url,t==null?void 0:t.details);this.loadPlaylist(h)}else this.hls.trigger(v.SUBTITLE_TRACK_SWITCH,{id:e})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1;const t=hn(this.media.textTracks);for(let i=0;i<t.length;i++)if(t[i].mode==="hidden")e=i;else if(t[i].mode==="showing"){e=i;break}this.subtitleTrack!==e&&(this.subtitleTrack=e)}}function hn(r){const e=[];for(let t=0;t<r.length;t++){const i=r[t];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&e.push(r[t])}return e}class zu{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t){const i=this.queues[t];i.push(e),i.length===1&&this.buffers[t]&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const i=new Promise(n=>{t=n}),s={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(s,e),i}executeNext(e){const{buffers:t,queues:i}=this,s=t[e],n=i[e];if(n.length){const o=n[0];try{o.execute()}catch(a){C.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),o.onError(a),s!=null&&s.updating||(n.shift(),this.executeNext(e))}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const el=Ls(),tl=/([ha]vc.)(?:\.[^.,]+)+/;class Wu{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=()=>{const{media:t,mediaSource:i}=this;C.log("[buffer-controller]: Media source opened"),t&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(v.MEDIA_ATTACHED,{media:t})),i&&i.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{C.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{C.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:t,_objectUrl:i}=this;t&&t.src!==i&&C.error(`Media element src was set while attaching MediaSource (${i} > ${t.src})`)},this.hls=e,this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null}registerListeners(){const{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)}unregisterListeners(){const{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)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new zu(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,C.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const i=this.media=t.media;if(i&&el){const s=this.mediaSource=new el;s.addEventListener("sourceopen",this._onMediaSourceOpen),s.addEventListener("sourceended",this._onMediaSourceEnded),s.addEventListener("sourceclose",this._onMediaSourceClose),i.src=self.URL.createObjectURL(s),this._objectUrl=i.src,i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:i}=this;if(t){if(C.log("[buffer-controller]: media source detaching"),t.readyState==="open")try{t.endOfStream()}catch(s){C.warn(`[buffer-controller]: onMediaDetaching: ${s.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),e&&(e.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),e.src===i?(e.removeAttribute("src"),e.load()):C.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(v.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{const t=this.sourceBuffer[e];try{t&&(this.removeBufferListeners(e),this.mediaSource&&this.mediaSource.removeSourceBuffer(t),this.sourceBuffer[e]=void 0)}catch(i){C.warn(`[buffer-controller]: Failed to reset the ${e} buffer`,i)}}),this._initSourceBuffer()}onBufferCodecs(e,t){const i=this.getSourceBufferTypes().length;Object.keys(t).forEach(s=>{if(i){const n=this.tracks[s];if(n&&typeof n.buffer.changeType=="function"){const{id:o,codec:a,levelCodec:l,container:c,metadata:d}=t[s],h=(n.levelCodec||n.codec).replace(tl,"$1"),u=(l||a).replace(tl,"$1");if(h!==u){const f=`${c};codecs=${l||a}`;this.appendChangeType(s,f),C.log(`[buffer-controller]: switching codec ${h} to ${u}`),this.tracks[s]={buffer:n.buffer,codec:a,container:c,levelCodec:l,metadata:d,id:o}}}}else this.pendingTracks[s]=t[s]}),!i&&(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks())}appendChangeType(e,t){const{operationQueue:i}=this,s={execute:()=>{const n=this.sourceBuffer[e];n&&(C.log(`[buffer-controller]: changing ${e} sourceBuffer type to ${t}`),n.changeType(t)),i.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{C.warn(`[buffer-controller]: Failed to change ${e} SourceBuffer type`,n)}};i.append(s,e)}onBufferAppending(e,t){const{hls:i,operationQueue:s,tracks:n}=this,{data:o,type:a,frag:l,part:c,chunkMeta:d}=t,h=d.buffering[a],u=self.performance.now();h.start=u;const f=l.stats.buffering,g=c?c.stats.buffering:null;f.start===0&&(f.start=u),g&&g.start===0&&(g.start=u);const p=n.audio;let m=!1;a==="audio"&&(p==null?void 0:p.container)==="audio/mpeg"&&(m=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const A=l.start,T={execute:()=>{if(h.executeStart=self.performance.now(),m){const b=this.sourceBuffer[a];if(b){const y=A-b.timestampOffset;Math.abs(y)>=.1&&(C.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${A} (delta: ${y}) sn: ${l.sn})`),b.timestampOffset=A)}}this.appendExecutor(o,a)},onStart:()=>{},onComplete:()=>{const b=self.performance.now();h.executeEnd=h.end=b,f.first===0&&(f.first=b),g&&g.first===0&&(g.first=b);const{sourceBuffer:y}=this,x={};for(const E in y)x[E]=fe.getBuffered(y[E]);this.appendError=0,this.hls.trigger(v.BUFFER_APPENDED,{type:a,frag:l,part:c,chunkMeta:d,parent:l.type,timeRanges:x})},onError:b=>{C.error(`[buffer-controller]: Error encountered while trying to append to the ${a} SourceBuffer`,b);const y={type:q.MEDIA_ERROR,parent:l.type,details:D.BUFFER_APPEND_ERROR,frag:l,part:c,chunkMeta:d,error:b,err:b,fatal:!1};b.code===DOMException.QUOTA_EXCEEDED_ERR?y.details=D.BUFFER_FULL_ERROR:(this.appendError++,y.details=D.BUFFER_APPEND_ERROR,this.appendError>i.config.appendErrorMaxRetry&&(C.error(`[buffer-controller]: Failed ${i.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),y.fatal=!0)),i.trigger(v.ERROR,y)}};s.append(T,a)}onBufferFlushing(e,t){const{operationQueue:i}=this,s=n=>({execute:this.removeExecutor.bind(this,n,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(v.BUFFER_FLUSHED,{type:n})},onError:o=>{C.warn(`[buffer-controller]: Failed to remove from ${n} SourceBuffer`,o)}});t.type?i.append(s(t.type),t.type):this.getSourceBufferTypes().forEach(n=>{i.append(s(n),n)})}onFragParsed(e,t){const{frag:i,part:s}=t,n=[],o=s?s.elementaryStreams:i.elementaryStreams;o[de.AUDIOVIDEO]?n.push("audiovideo"):(o[de.AUDIO]&&n.push("audio"),o[de.VIDEO]&&n.push("video"));const a=()=>{const l=self.performance.now();i.stats.buffering.end=l,s&&(s.stats.buffering.end=l);const c=s?s.stats:i.stats;this.hls.trigger(v.FRAG_BUFFERED,{frag:i,part:s,stats:c,id:i.type})};n.length===0&&C.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(a,n)}onFragChanged(e,t){this.flushBackBuffer()}onBufferEos(e,t){this.getSourceBufferTypes().reduce((s,n)=>{const o=this.sourceBuffer[n];return o&&(!t.type||t.type===n)&&(o.ending=!0,o.ended||(o.ended=!0,C.log(`[buffer-controller]: ${n} sourceBuffer now EOS`))),s&&!!(!o||o.ended)},!0)&&(C.log("[buffer-controller]: Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(n=>{const o=this.sourceBuffer[n];o&&(o.ending=!1)});const{mediaSource:s}=this;if(!s||s.readyState!=="open"){s&&C.info(`[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ${s.readyState}`);return}C.log("[buffer-controller]: Calling mediaSource.endOfStream()"),s.endOfStream()}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}flushBackBuffer(){const{hls:e,details:t,media:i,sourceBuffer:s}=this;if(!i||t===null)return;const n=this.getSourceBufferTypes();if(!n.length)return;const o=t.live&&e.config.liveBackBufferLength!==null?e.config.liveBackBufferLength:e.config.backBufferLength;if(!W(o)||o<0)return;const a=i.currentTime,l=t.levelTargetDuration,c=Math.max(o,l),d=Math.floor(a/l)*l-c;n.forEach(h=>{const u=s[h];if(u){const f=fe.getBuffered(u);if(f.length>0&&d>f.start(0)){if(e.trigger(v.BACK_BUFFER_REACHED,{bufferEnd:d}),t.live)e.trigger(v.LIVE_BACK_BUFFER_REACHED,{bufferEnd:d});else if(u.ended&&f.end(f.length-1)-a<l*2){C.info(`[buffer-controller]: Cannot flush ${h} back buffer while SourceBuffer is in ended state`);return}e.trigger(v.BUFFER_FLUSHING,{startOffset:0,endOffset:d,type:h})}}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:e,hls:t,media:i,mediaSource:s}=this,n=e.fragments[0].start+e.totalduration,o=i.duration,a=W(s.duration)?s.duration:0;e.live&&t.config.liveDurationInfinity?(C.log("[buffer-controller]: Media Source duration is set to Infinity"),s.duration=1/0,this.updateSeekableRange(e)):(n>a&&n>o||!W(o))&&(C.log(`[buffer-controller]: Updating Media Source duration to ${n.toFixed(3)}`),s.duration=n)}updateSeekableRange(e){const t=this.mediaSource,i=e.fragments;if(i.length&&e.live&&t!=null&&t.setLiveSeekableRange){const n=Math.max(0,i[0].start),o=Math.max(n,n+e.totalduration);t.setLiveSeekableRange(n,o)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:i}=this,s=Object.keys(i).length;if(s&&!e||s===2){this.createSourceBuffers(i),this.pendingTracks={};const n=this.getSourceBufferTypes();if(n.length)this.hls.trigger(v.BUFFER_CREATED,{tracks:this.tracks}),n.forEach(o=>{t.executeNext(o)});else{const o=new Error("could not create source buffer for media codec(s)");this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:o,reason:o.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const s in e)if(!t[s]){const n=e[s];if(!n)throw Error(`source buffer exists for track ${s}, however track does not`);const o=n.levelCodec||n.codec,a=`${n.container};codecs=${o}`;C.log(`[buffer-controller]: creating sourceBuffer(${a})`);try{const l=t[s]=i.addSourceBuffer(a),c=s;this.addBufferListener(c,"updatestart",this._onSBUpdateStart),this.addBufferListener(c,"updateend",this._onSBUpdateEnd),this.addBufferListener(c,"error",this._onSBUpdateError),this.tracks[s]={buffer:l,codec:o,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(l){C.error(`[buffer-controller]: error while trying to add sourceBuffer: ${l.message}`),this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:l,mimeType:a})}}}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){const{operationQueue:t}=this;t.current(e).onComplete(),t.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){const i=new Error(`${e} SourceBuffer error`);C.error(`[buffer-controller]: ${i}`,t),this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.BUFFER_APPENDING_ERROR,error:i,fatal:!1});const s=this.operationQueue.current(e);s&&s.onError(t)}removeExecutor(e,t,i){const{media:s,mediaSource:n,operationQueue:o,sourceBuffer:a}=this,l=a[e];if(!s||!n||!l){C.warn(`[buffer-controller]: Attempting to remove from the ${e} SourceBuffer, but it does not exist`),o.shiftAndExecuteNext(e);return}const c=W(s.duration)?s.duration:1/0,d=W(n.duration)?n.duration:1/0,h=Math.max(0,t),u=Math.min(i,c,d);u>h&&!l.ending?(l.ended=!1,C.log(`[buffer-controller]: Removing [${h},${u}] from the ${e} SourceBuffer`),l.remove(h,u)):o.shiftAndExecuteNext(e)}appendExecutor(e,t){const{operationQueue:i,sourceBuffer:s}=this,n=s[t];if(!n){C.warn(`[buffer-controller]: Attempting to append to the ${t} SourceBuffer, but it does not exist`),i.shiftAndExecuteNext(t);return}n.ended=!1,n.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length){C.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}const{operationQueue:i}=this,s=t.map(n=>i.appendBlocker(n));Promise.all(s).then(()=>{e(),t.forEach(n=>{const o=this.sourceBuffer[n];o!=null&&o.updating||i.shiftAndExecuteNext(n)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,i){const s=this.sourceBuffer[e];if(!s)return;const n=i.bind(this,e);this.listeners[e].push({event:t,listener:n}),s.addEventListener(t,n)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach(i=>{t.removeEventListener(i.event,i.listener)})}}const il={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},sl=function(e){let t=e;return il.hasOwnProperty(e)&&(t=il[e]),String.fromCharCode(t)},dt=15,Rt=100,Yu={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Ku={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Xu={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},qu={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Zu=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Ju{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;C.log(`${this.time} [${e}] ${i}`)}}}const ei=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class rl{constructor(e,t,i,s,n){this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=e||"white",this.underline=t||!1,this.italics=i||!1,this.background=s||"black",this.flash=n||!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){const s=t[i];e.hasOwnProperty(s)&&(this[s]=e[s])}}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}}class Qu{constructor(e,t,i,s,n,o){this.uchar=void 0,this.penState=void 0,this.uchar=e||" ",this.penState=new rl(t,i,s,n,o)}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()}}class _u{constructor(e){this.chars=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(let t=0;t<Rt;t++)this.chars.push(new Qu);this.logger=e,this.pos=0,this.currPenState=new rl}equals(e){let t=!0;for(let i=0;i<Rt;i++)if(!this.chars[i].equals(e.chars[i])){t=!1;break}return t}copy(e){for(let t=0;t<Rt;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Rt;t++)if(!this.chars[t].isEmpty()){e=!1;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>Rt&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Rt)}moveCursor(e){const 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();const t=sl(e);if(this.pos>=Rt){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<Rt;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let i=0;i<Rt;i++){const s=this.chars[i].uchar;s!==" "&&(t=!1),e.push(s)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class un{constructor(e){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(let t=0;t<dt;t++)this.rows.push(new _u(e));this.logger=e,this.currRow=dt-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}reset(){for(let e=0;e<dt;e++)this.rows[e].clear();this.currRow=dt-1}equals(e){let t=!0;for(let i=0;i<dt;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<dt;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<dt;t++)if(!this.rows[t].isEmpty()){e=!1;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 = "+JSON.stringify(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<dt;a++)this.rows[a].clear();const n=this.currRow+1-this.nrRollUpRows,o=this.lastOutputScreen;if(o){const a=o.rows[n].cueStartTime,l=this.logger.time;if(a&&l!==null&&a<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(o.rows[n+c])}}this.currRow=t;const i=this.rows[this.currRow];if(e.indent!==null){const n=e.indent,o=Math.max(n-1,0);i.setCursor(e.indent),e.color=i.chars[o].penState.foreground}const s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+JSON.stringify(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());const 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||!1;const t=[];let i="",s=-1;for(let n=0;n<dt;n++){const o=this.rows[n].getTextString();o&&(s=n+1,e?t.push("Row "+s+": '"+o+"'"):t.push(o.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
80
- `)),i}getTextAndFormat(){return this.rows}}class nl{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 un(i),this.nonDisplayedMemory=new un(i),this.lastOutputScreen=new un(i),this.currRollUpRow=this.displayedMemory.rows[dt-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[dt-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]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),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:!0})}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(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}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"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=s[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const 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))}}class ol{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const s=new Ju;this.channels=[null,new nl(e,t,s),new nl(e+1,i,s)],this.cmdHistory=ll(),this.logger=s}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){let i,s,n,o=!1;this.logger.time=e;for(let a=0;a<t.length;a+=2)if(s=t[a]&127,n=t[a+1]&127,!(s===0&&n===0)){if(this.logger.log(3,"["+ei([t[a],t[a+1]])+"] -> ("+ei([s,n])+")"),i=this.parseCmd(s,n),i||(i=this.parseMidrow(s,n)),i||(i=this.parsePAC(s,n)),i||(i=this.parseBackgroundAttributes(s,n)),!i&&(o=this.parseChars(s,n),o)){const l=this.currentChannel;l&&l>0?this.channels[l].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!i&&!o&&this.logger.log(2,"Couldn't parse cleaned data "+ei([s,n])+" orig: "+ei([t[a],t[a+1]]))}}parseCmd(e,t){const{cmdHistory:i}=this,s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(s||n))return!1;if(al(e,t,i))return vi(null,null,i),this.logger.log(3,"Repeated command ("+ei([e,t])+") is dropped"),!0;const o=e===20||e===21||e===23?1:2,a=this.channels[o];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),vi(e,t,i),this.currentChannel=o,!0}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"),!1;const s=this.channels[i];return s?(s.ccMIDROW(t),this.logger.log(3,"MIDROW ("+ei([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const s=this.cmdHistory,n=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,o=(e===16||e===24)&&t>=64&&t<=95;if(!(n||o))return!1;if(al(e,t,s))return vi(null,null,s),!0;const a=e<=23?1:2;t>=64&&t<=95?i=a===1?Yu[e]:Xu[e]:i=a===1?Ku[e]:qu[e];const l=this.channels[a];return l?(l.setPAC(this.interpretPAC(i,t)),vi(e,t,s),this.currentChannel=a,!0):!1}interpretPAC(e,t){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,s.underline=(i&1)===1,i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=Math.floor((i-16)/2)*4,s}parseChars(e,t){let i,s=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 '"+sl(o)+"' in channel "+i),s=[o]}else e>=32&&e<=127&&(s=t===0?[e]:[e,t]);if(s){const o=ei(s);this.logger.log(3,"Char codes = "+o.join(",")),vi(e,t,this.cmdHistory)}return s}parseBackgroundAttributes(e,t){const i=(e===16||e===24)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=45&&t<=47;if(!(i||s))return!1;let n;const o={};e===16||e===24?(n=Math.floor((t-32)/2),o.background=Zu[n],t%2===1&&(o.background=o.background+"_semi")):t===45?o.background="transparent":(o.foreground="black",t===47&&(o.underline=!0));const a=e<=23?1:2;return this.channels[a].setBkgData(o),vi(e,t,this.cmdHistory),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}this.cmdHistory=ll()}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const i=this.channels[t];i&&i.cueSplitAtTime(e)}}}function vi(r,e,t){t.a=r,t.b=e}function al(r,e,t){return t.a===r&&t.b===e}function ll(){return{a:null,b:null}}class Gs{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}}var fn=function(){if(typeof self<"u"&&self.VTTCue)return self.VTTCue;const r=["","lr","rl"],e=["start","middle","end","left","right"];function t(a,l){if(typeof l!="string"||!Array.isArray(a))return!1;const c=l.toLowerCase();return~a.indexOf(c)?c:!1}function i(a){return t(r,a)}function s(a){return t(e,a)}function n(a,...l){let c=1;for(;c<arguments.length;c++){const d=arguments[c];for(const h in d)a[h]=d[h]}return a}function o(a,l,c){const d=this,h={enumerable:!0};d.hasBeenReset=!1;let u="",f=!1,g=a,p=l,m=c,A=null,T="",b=!0,y="auto",x="start",E=50,S="middle",R=50,w="middle";Object.defineProperty(d,"id",n({},h,{get:function(){return u},set:function(I){u=""+I}})),Object.defineProperty(d,"pauseOnExit",n({},h,{get:function(){return f},set:function(I){f=!!I}})),Object.defineProperty(d,"startTime",n({},h,{get:function(){return g},set:function(I){if(typeof I!="number")throw new TypeError("Start time must be set to a number.");g=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"endTime",n({},h,{get:function(){return p},set:function(I){if(typeof I!="number")throw new TypeError("End time must be set to a number.");p=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"text",n({},h,{get:function(){return m},set:function(I){m=""+I,this.hasBeenReset=!0}})),Object.defineProperty(d,"region",n({},h,{get:function(){return A},set:function(I){A=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"vertical",n({},h,{get:function(){return T},set:function(I){const O=i(I);if(O===!1)throw new SyntaxError("An invalid or illegal string was specified.");T=O,this.hasBeenReset=!0}})),Object.defineProperty(d,"snapToLines",n({},h,{get:function(){return b},set:function(I){b=!!I,this.hasBeenReset=!0}})),Object.defineProperty(d,"line",n({},h,{get:function(){return y},set:function(I){if(typeof I!="number"&&I!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");y=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"lineAlign",n({},h,{get:function(){return x},set:function(I){const O=s(I);if(!O)throw new SyntaxError("An invalid or illegal string was specified.");x=O,this.hasBeenReset=!0}})),Object.defineProperty(d,"position",n({},h,{get:function(){return E},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");E=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"positionAlign",n({},h,{get:function(){return S},set:function(I){const O=s(I);if(!O)throw new SyntaxError("An invalid or illegal string was specified.");S=O,this.hasBeenReset=!0}})),Object.defineProperty(d,"size",n({},h,{get:function(){return R},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");R=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"align",n({},h,{get:function(){return w},set:function(I){const O=s(I);if(!O)throw new SyntaxError("An invalid or illegal string was specified.");w=O,this.hasBeenReset=!0}})),d.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o}();class $u{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function cl(r){function e(i,s,n,o){return(i|0)*3600+(s|0)*60+(n|0)+parseFloat(o||0)}const t=r.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}class ef{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 s=0;s<i.length;++s)if(t===i[s]){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)){const i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}function dl(r,e,t,i){const s=i?r.split(i):[r];for(const n in s){if(typeof s[n]!="string")continue;const o=s[n].split(t);if(o.length!==2)continue;const a=o[0],l=o[1];e(a,l)}}const gn=new fn(0,0,""),Vs=gn.align==="middle"?"middle":"center";function tf(r,e,t){const i=r;function s(){const a=cl(r);if(a===null)throw new Error("Malformed timestamp: "+i);return r=r.replace(/^[^\sa-zA-Z-]+/,""),a}function n(a,l){const c=new ef;dl(a,function(u,f){let g;switch(u){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){c.set(u,t[p].region);break}break;case"vertical":c.alt(u,f,["rl","lr"]);break;case"line":g=f.split(","),c.integer(u,g[0]),c.percent(u,g[0])&&c.set("snapToLines",!1),c.alt(u,g[0],["auto"]),g.length===2&&c.alt("lineAlign",g[1],["start",Vs,"end"]);break;case"position":g=f.split(","),c.percent(u,g[0]),g.length===2&&c.alt("positionAlign",g[1],["start",Vs,"end","line-left","line-right","auto"]);break;case"size":c.percent(u,f);break;case"align":c.alt(u,f,["start",Vs,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let d=c.get("line","auto");d==="auto"&&gn.line===-1&&(d=-1),l.line=d,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",Vs);let h=c.get("position","auto");h==="auto"&&gn.position===50&&(h=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=h}function o(){r=r.replace(/^\s+/,"")}if(o(),e.startTime=s(),o(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);r=r.slice(3),o(),e.endTime=s(),o(),n(r,e)}function hl(r){return r.replace(/<br(?: \/)?>/gi,`
79
+ Aborting and switching to level ${I}`),e.loader&&(this.fragCurrent=this.partCurrent=null,e.abortRequests()),i.trigger(v.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:a}))}onFragLoaded(e,{frag:t,part:i}){const s=i?i.stats:t.stats;if(t.type===Z.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),this.lastLoadedFragLevel=t.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){const n=i?i.duration:t.duration,o=this.hls.levels[t.level],a=(o.loaded?o.loaded.bytes:0)+s.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){const n={stats:s,frag:t,part:i,id:t.type};this.onFragBuffered(v.FRAG_BUFFERED,n),t.bitrateTest=!1}}}onFragBuffered(e,t){const{frag:i,part:s}=t,n=s!=null&&s.stats.loaded?s.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;const 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.bwEstimator.getEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Z.MAIN||e.sn==="initSegment"}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){const e=this._nextAutoLevel,t=this.bwEstimator;if(e!==-1&&!t.canEstimate())return e;let i=this.getNextABRAutoLevel();if(e!==-1){const s=this.hls.levels;if(s.length>Math.max(e,i)&&s[e].loadError<=s[i].loadError)return e}return e!==-1&&(i=Math.min(e,i)),i}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this,{maxAutoLevel:s,config:n,minAutoLevel:o,media:a}=i,l=t?t.duration:e?e.duration:0,c=a&&a.playbackRate!==0?Math.abs(a.playbackRate):1,d=this.bwEstimator?this.bwEstimator.getEstimate():n.abrEwmaDefaultEstimate,h=i.mainForwardBufferInfo,u=(h?h.len:0)/c;let f=this.findBestLevel(d,o,s,u,n.abrBandWidthFactor,n.abrBandWidthUpFactor);if(f>=0)return f;C.trace(`[abr] ${u?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let g=l?Math.min(l,n.maxStarvationDelay):n.maxStarvationDelay,p=n.abrBandWidthFactor,m=n.abrBandWidthUpFactor;if(!u){const A=this.bitrateTestDelay;A&&(g=(l?Math.min(l,n.maxLoadingDelay):n.maxLoadingDelay)-A,C.trace(`[abr] bitrate test took ${Math.round(1e3*A)}ms, set first fragment max fetchDuration to ${Math.round(1e3*g)} ms`),p=m=1)}return f=this.findBestLevel(d,o,s,u+g,p,m),Math.max(f,0)}findBestLevel(e,t,i,s,n,o){var a;const{fragCurrent:l,partCurrent:c,lastLoadedFragLevel:d}=this,{levels:h}=this.hls,u=h[d],f=!!(u!=null&&(a=u.details)!=null&&a.live),g=u==null?void 0:u.codecSet,p=c?c.duration:l?l.duration:0,m=this.bwEstimator.getEstimateTTFB()/1e3;let A=t,x=-1;for(let b=i;b>=t;b--){const y=h[b];if(!y||g&&y.codecSet!==g){y&&(A=Math.min(b,A),x=Math.max(b,x));continue}x!==-1&&C.trace(`[abr] Skipped level(s) ${A}-${x} with CODECS:"${h[x].attrs.CODECS}"; not compatible with "${u.attrs.CODECS}"`);const T=y.details,E=(c?T==null?void 0:T.partTarget:T==null?void 0:T.averagetargetduration)||p;let S;b<=d?S=n*e:S=o*e;const R=h[b].maxBitrate,w=this.getTimeToLoadFrag(m,S,R*E,T===void 0);if(C.trace(`[abr] level:${b} adjustedbw-bitrate:${Math.round(S-R)} avgDuration:${E.toFixed(1)} maxFetchDuration:${s.toFixed(1)} fetchDuration:${w.toFixed(1)}`),S>R&&(w===0||!W(w)||f&&!this.bitrateTestDelay||w<s))return b}return-1}set nextAutoLevel(e){this._nextAutoLevel=e}}class Ja{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=Nu(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function Nu(r,e){const t=new Uint8Array(e);let i=0;for(let s=0;s<r.length;s++){const n=r[s];t.set(n,i),i+=n.length}return t}const Qa=100;class Bu extends Qr{constructor(e,t,i){super(e,t,i,"[audio-stream-controller]",Z.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{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.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.ERROR,this.onError,this),e.on(v.BUFFER_RESET,this.onBufferReset,this),e.on(v.BUFFER_CREATED,this.onBufferCreated,this),e.on(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{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.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.ERROR,this.onError,this),e.off(v.BUFFER_RESET,this.onBufferReset,this),e.off(v.BUFFER_CREATED,this.onBufferCreated,this),e.off(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n}){if(i==="main"){const o=t.cc;this.initPTS[t.cc]={baseTime:s,timescale:n},this.log(`InitPTS for cc: ${o} found from main: ${s}`),this.videoTrackCC=o,this.state===M.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=M.STOPPED;return}const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(Qa),t>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=M.IDLE):(this.loadedmetadata=!1,this.state=M.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case M.IDLE:this.doTickIdle();break;case M.WAITING_TRACK:{var e;const{levels:i,trackId:s}=this,n=i==null||(e=i[s])==null?void 0:e.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=M.WAITING_INIT_PTS}break}case M.FRAG_LOADING_WAITING_RETRY:{var t;const i=performance.now(),s=this.retryDate;(!s||i>=s||(t=this.media)!=null&&t.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=M.IDLE);break}case M.WAITING_INIT_PTS:{const i=this.waitingData;if(i){const{frag:s,part:n,cache:o,complete:a}=i;if(this.initPTS[s.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=M.FRAG_LOADING;const l=o.flush(),c={frag:s,part:n,payload:l,networkDetails:null};this._handleFragmentLoadProgress(c),a&&super._handleFragmentLoadComplete(c)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${s.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),c=fe.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);Yr(c.end,this.config.maxFragLookUpTolerance,s)<0&&(this.log(`Waiting fragment cc (${s.cc}) @ ${s.start} cancelled because another fragment at ${c.end} is needed`),this.clearWaitingFragment())}}else this.state=M.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=M.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:i,trackId:s}=this,n=e.config;if(!(t!=null&&t[s])||!i&&(this.startFragRequested||!n.startFragPrefetch))return;const o=t[s],a=o.details;if(!a||a.live&&this.levelLastLoaded!==s||this.waitForCdnTuneIn(a)){this.state=M.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,de.AUDIO,Z.AUDIO));const c=this.getFwdBufferInfo(l,Z.AUDIO);if(c===null)return;const{bufferedTrack:d,switchingTrack:h}=this;if(!h&&this._streamEnded(c,a)){e.trigger(v.BUFFER_EOS,{type:"audio"}),this.state=M.ENDED;return}const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Z.MAIN),f=c.len,g=this.getMaxBufferLength(u==null?void 0:u.len);if(f>=g&&!h)return;const m=a.fragments[0].start;let A=c.end;if(h&&i){const T=this.getLoadPosition();d&&h.attrs!==d.attrs&&(A=T),a.PTSKnown&&T<m&&(c.end>m||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=m+.05)}let x=this.getNextFragment(A,a),b=!1;if(x&&this.isLoopLoading(x,A)&&(b=!!x.gap,x=this.getNextFragmentLoopLoading(x,a,c,Z.MAIN,g)),!x){this.bufferFlushed=!0;return}const y=u&&x.start>u.end+a.targetduration;if(y||!(u!=null&&u.len)&&c.len){const T=this.getAppendedFrag(x.start,Z.MAIN);if(T===null||(b||(b=!!T.gap||!!y&&u.len===0),y&&!b||b&&c.nextStart&&c.nextStart<T.end))return}this.loadFragment(x,o,A)}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new Ji(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?this.setInterval(Qa):this.resetTransmuxer(),i?(this.switchingTrack=t,this.state=M.IDLE):(this.switchingTrack=null,this.bufferedTrack=t,this.state=M.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(v.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var i;if(this.mainDetails==null){this.cachedTrackLoadedData=t;return}const{levels:s}=this,{details:n,id:o}=t;if(!s){this.warn(`Audio tracks were reset while loading level ${o}`);return}this.log(`Track ${o} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const a=s[o];let l=0;if(n.live||(i=a.details)!=null&&i.live){const c=this.mainDetails;if(n.fragments[0]||(n.deltaUpdateFailed=!0),n.deltaUpdateFailed||!c)return;!a.details&&n.hasProgramDateTime&&c.hasProgramDateTime?(La(n,c),l=n.fragments[0].start):l=this.alignPlaylists(n,a.details)}a.details=n,this.levelLastLoaded=o,!this.startFragRequested&&(this.mainDetails||!n.live)&&this.setStartPosition(a.details,l),this.state===M.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=M.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:s,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}const c=l[a];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const d=c.details;if(!d){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const h=o.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Za(this.hls,Z.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[i.cc],g=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){const m=s?s.index:-1,A=m!==-1,x=new qr(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,A);u.push(n,g,h,"",i,s,d.totalduration,!1,x,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:p}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Ja,complete:!1};p.push(new Uint8Array(n)),this.waitingVideoCC=this.videoTrackCC,this.state=M.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i.type!==Z.AUDIO){if(!this.loadedmetadata&&i.type===Z.MAIN){const n=this.videoBuffer||this.media;n&&fe.getBuffered(n).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(i.sn!=="initSegment"){this.fragPrevious=i;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(v.AUDIO_TRACK_SWITCHED,je({},n)))}this.fragBufferedComplete(i,s)}onError(e,t){var i;if(t.fatal){this.state=M.ERROR;return}switch(t.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Z.AUDIO,t);break;case D.AUDIO_TRACK_LOAD_ERROR:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===M.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===ae.AUDIO_TRACK&&(this.state=M.IDLE);break;case D.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case D.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushed(e,{type:t}){t===de.AUDIO&&(this.bufferFlushed=!0,this.state===M.ENDED&&(this.state=M.IDLE))}_handleTransmuxComplete(e){var t;const i="audio",{hls:s}=this,{remuxResult:n,chunkMeta:o}=e,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:l,part:c,level:d}=a,{details:h}=d,{audio:u,text:f,id3:g,initSegment:p}=n;if(this.fragContextChanged(l)||!h){this.fragmentTracker.removeFragment(l);return}if(this.state=M.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const m=l.initSegment||l;this._bufferInitSegment(p.tracks,m,o),s.trigger(v.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:i,tracks:p.tracks})}if(u){const{startPTS:m,endPTS:A,startDTS:x,endDTS:b}=u;c&&(c.elementaryStreams[de.AUDIO]={startPTS:m,endPTS:A,startDTS:x,endDTS:b}),l.setElementaryStreamInfo(de.AUDIO,m,A,x,b),this.bufferFragmentData(u,l,c,o)}if(g!=null&&(t=g.samples)!=null&&t.length){const m=Ce({id:i,frag:l,details:h},g);s.trigger(v.FRAG_PARSING_METADATA,m)}if(f){const m=Ce({id:i,frag:l,details:h},f);s.trigger(v.FRAG_PARSING_USERDATA,m)}}_bufferInitSegment(e,t,i){if(this.state!==M.PARSING)return;e.video&&delete e.video;const s=e.audio;if(!s)return;s.levelCodec=s.codec,s.id="audio",this.log(`Init audio buffer, container:${s.container}, codecs[parsed]=[${s.codec}]`),this.hls.trigger(v.BUFFER_CODECS,e);const n=s.initSegment;if(n!=null&&n.byteLength){const o={type:"audio",frag:t,part:null,chunkMeta:i,parent:t.type,data:n};this.hls.trigger(v.BUFFER_APPENDING,o)}this.tick()}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||s===ke.NOT_LOADED||s===ke.PARTIAL){var n;e.sn==="initSegment"?this._loadInitSegment(e,t):(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=M.WAITING_INIT_PTS):(this.startFragRequested=!0,super.loadFragment(e,t,i))}else this.clearTrackerIfNeeded(e)}completeAudioSwitch(e){const{hls:t,media:i,bufferedTrack:s}=this,n=s==null?void 0:s.attrs,o=e.attrs;i&&n&&(n.CHANNELS!==o.CHANNELS||n.NAME!==o.NAME||n.LANGUAGE!==o.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(v.AUDIO_TRACK_SWITCHED,je({},e))}}class Uu extends Kr{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{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(){const{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.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:s,details:n}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==s){this.warn(`Track with id:${i} and group:${s} not found in active group ${o.groupId}`);return}const a=o.details;o.details=t.details,this.log(`audio-track ${i} "${o.name}" lang:${o.lang} group:${s} 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){const t=this.hls.levels[e];if(!(t!=null&&t.audioGroupIds))return;const i=t.audioGroupIds[t.urlId];if(this.groupId!==i){this.groupId=i||null;const s=this.tracks.filter(o=>!i||o.groupId===i);this.selectDefaultTrack&&!s.some(o=>o.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=s;const n={audioTracks:s};this.log(`Updating audio tracks, ${s.length} track(s) found in group:${i}`),this.hls.trigger(v.AUDIO_TRACKS_UPDATED,n),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(e,t){t.fatal||!t.context||t.context.type===ae.AUDIO_TRACK&&t.context.id===this.trackId&&t.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(t))}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn("Invalid id passed to audio-track controller");return}this.clearTimer();const i=this.currentTrack;t[this.trackId];const s=t[e],{groupId:n,name:o}=s;if(this.log(`Switching to audio-track ${e} "${o}" lang:${s.lang} group:${n}`),this.trackId=e,this.currentTrack=s,this.selectDefaultTrack=!1,this.hls.trigger(v.AUDIO_TRACK_SWITCHING,je({},s)),s.details&&!s.details.live)return;const a=this.switchParams(s.url,i==null?void 0:i.details);this.loadPlaylist(a)}selectInitialTrack(){const e=this.tracksInGroup,t=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(t!==-1)this.setAudioTrack(t);else{const i=new Error(`No track found for running audio group-ID: ${this.groupId} track count: ${e.length}`);this.warn(i.message),this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:i})}}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if((!this.selectDefaultTrack||s.default)&&(!e||e.attrs["STABLE-RENDITION-ID"]!==void 0&&e.attrs["STABLE-RENDITION-ID"]===s.attrs["STABLE-RENDITION-ID"]||e.name===s.name&&e.lang===s.lang))return s.id}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(t)){const i=t.id,s=t.groupId;let n=t.url;if(e)try{n=e.addDirectives(n)}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`)}this.log(`loading audio-track playlist ${i} "${t.name}" lang:${t.lang} group:${s}`),this.clearTimer(),this.hls.trigger(v.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:e||null})}}}function _a(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!Hu(r[t].attrs,e[t].attrs))return!1;return!0}function Hu(r,e){const t=r["STABLE-RENDITION-ID"];return t?t===e["STABLE-RENDITION-ID"]:!["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED"].some(i=>r[i]!==e[i])}const $a=500;class Gu extends Qr{constructor(e,t,i){super(e,t,i,"[subtitle-stream-controller]",Z.SUBTITLE),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){const{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.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.ERROR,this.onError,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),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{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.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.ERROR,this.onError,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),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=M.IDLE,this.setInterval($a),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:s}=t;if(this.fragPrevious=i,this.state=M.IDLE,!s)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let o;const a=i.start;for(let c=0;c<n.length;c++)if(a>=n[c].start&&a<=n[c].end){o=n[c];break}const l=i.start+i.duration;o?o.end=l:(o={start:a,end:l},n.push(o)),this.fragmentTracker.fragBuffered(i)}onBufferFlushing(e,t){const{startOffset:i,endOffset:s}=t;if(i===0&&s!==Number.POSITIVE_INFINITY){const{currentTrackId:n,levels:o}=this;if(!o.length||!o[n]||!o[n].details)return;const l=o[n].details.targetduration,c=s-l;if(c<=0)return;t.endOffsetSubtitles=Math.max(0,c),this.tracksBuffered.forEach(d=>{for(let h=0;h<d.length;){if(d[h].end<=c){d.shift();continue}else if(d[h].start<c)d[h].start=c;else break;h++}}),this.fragmentTracker.removeFragmentsInRange(i,c,Z.SUBTITLE)}}onFragBuffered(e,t){if(!this.loadedmetadata&&t.frag.type===Z.MAIN){var i;(i=this.media)!=null&&i.buffered.length&&(this.loadedmetadata=!0)}}onError(e,t){const i=t.frag;(i==null?void 0:i.type)===Z.SUBTITLE&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==M.STOPPED&&(this.state=M.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(_a(this.levels,t)){this.levels=t.map(i=>new Ji(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const s=new Ji(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Z.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){if(this.currentTrackId=t.id,!this.levels.length||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.setInterval($a)}onSubtitleTrackLoaded(e,t){var i;const{details:s,id:n}=t,{currentTrackId:o,levels:a}=this;if(!a.length)return;const l=a[o];if(n>=a.length||n!==o||!l)return;this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(s.live||(i=l.details)!=null&&i.live){const d=this.mainDetails;if(s.deltaUpdateFailed||!d)return;const h=d.fragments[0];l.details?(c=this.alignPlaylists(s,l.details),c===0&&h&&(c=h.start,zr(s,c))):s.hasProgramDateTime&&d.hasProgramDateTime?(La(s,d),c=s.fragments[0].start):h&&(c=h.start,zr(s,c))}l.details=s,this.levelLastLoaded=n,!this.startFragRequested&&(this.mainDetails||!s.live)&&this.setStartPosition(l.details,c),this.tick(),s.live&&!this.fragCurrent&&this.media&&this.state===M.IDLE&&(Qi(null,s.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,s=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&s&&s.key&&s.iv&&s.method==="AES-128"){const o=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer).catch(a=>{throw n.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t}),a}).then(a=>{const 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=M.IDLE})}}doTick(){if(!this.media){this.state=M.IDLE;return}if(this.state===M.IDLE){const{currentTrackId:e,levels:t}=this,i=t[e];if(!t.length||!i||!i.details)return;const s=i.details,n=s.targetduration,{config:o}=this,a=this.getLoadPosition(),l=fe.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],a-n,o.maxBufferHole),{end:c,len:d}=l,h=this.getFwdBufferInfo(this.media,Z.MAIN),u=this.getMaxBufferLength(h==null?void 0:h.len)+n;if(d>u)return;const f=s.fragments,g=f.length,p=s.edge;let m=null;const A=this.fragPrevious;if(c<p){const{maxFragLookUpTolerance:x}=o;m=Qi(A,f,Math.max(f[0].start,c),x),!m&&A&&A.start<f[0].start&&(m=f[0])}else m=f[g-1];if(!m)return;m=this.mapToInitFragWhenRequired(m),this.fragmentTracker.getState(m)===ke.NOT_LOADED&&this.loadFragment(m,i,c)}}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,i){this.fragCurrent=e,e.sn==="initSegment"?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,i))}get mediaBufferTimeRanges(){return new Vu(this.tracksBuffered[this.currentTrackId]||[])}}class Vu{constructor(e){this.buffered=void 0;const t=(i,s,n)=>{if(s=s>>>0,s>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${n})`);return e[s][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}class ju extends Kr{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.trackChangeListener=()=>this.onTextTracksChanged(),this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes(this.trackId)}registerListeners(){const{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(){const{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.trackChangeListener,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),hn(this.media.textTracks).forEach(t=>{gi(t)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,details:s}=t,{trackId:n}=this,o=this.tracksInGroup[n];if(!o){this.warn(`Invalid subtitle track id ${i}`);return}const a=o.details;o.details=t.details,this.log(`subtitle track ${i} loaded [${s.startSN}-${s.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){const t=this.hls.levels[e];if(!(t!=null&&t.textGroupIds))return;const i=t.textGroupIds[t.urlId],s=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==i){const n=this.tracks.filter(l=>!i||l.groupId===i);this.tracksInGroup=n;const o=this.findTrackId(s==null?void 0:s.name)||this.findTrackId();this.groupId=i||null;const a={subtitleTracks:n};this.log(`Updating subtitle tracks, ${n.length} track(s) found in "${i}" group-id`),this.hls.trigger(v.SUBTITLE_TRACKS_UPDATED,a),o!==-1&&this.setSubtitleTrack(o,s)}else this.shouldReloadPlaylist(s)&&this.setSubtitleTrack(this.trackId,s)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if((!this.selectDefaultTrack||s.default)&&(!e||e===s.name))return s.id}return-1}onError(e,t){t.fatal||!t.context||t.context.type===ae.SUBTITLE_TRACK&&t.context.id===this.trackId&&t.context.groupId===this.groupId&&this.checkRetry(t)}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1;const t=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(e,t)}loadPlaylist(e){super.loadPlaylist();const t=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(t)){const i=t.id,s=t.groupId;let n=t.url;if(e)try{n=e.addDirectives(n)}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(v.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:e||null})}}toggleTrackModes(e){const{media:t,trackId:i}=this;if(!t)return;const s=hn(t.textTracks),n=s.filter(a=>a.groupId===this.groupId);if(e===-1)[].slice.call(s).forEach(a=>{a.mode="disabled"});else{const a=n[i];a&&(a.mode="disabled")}const o=n[e];o&&(o.mode=this.subtitleDisplay?"showing":"hidden")}setSubtitleTrack(e,t){var i;const s=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(this.trackId!==e&&this.toggleTrackModes(e),this.trackId===e&&(e===-1||(i=s[e])!=null&&i.details)||e<-1||e>=s.length)return;this.clearTimer();const n=s[e];if(this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:"")),this.trackId=e,n){const{id:o,groupId:a="",name:l,type:c,url:d}=n;this.hls.trigger(v.SUBTITLE_TRACK_SWITCH,{id:o,groupId:a,name:l,type:c,url:d});const h=this.switchParams(n.url,t==null?void 0:t.details);this.loadPlaylist(h)}else this.hls.trigger(v.SUBTITLE_TRACK_SWITCH,{id:e})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1;const t=hn(this.media.textTracks);for(let i=0;i<t.length;i++)if(t[i].mode==="hidden")e=i;else if(t[i].mode==="showing"){e=i;break}this.subtitleTrack!==e&&(this.subtitleTrack=e)}}function hn(r){const e=[];for(let t=0;t<r.length;t++){const i=r[t];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&e.push(r[t])}return e}class zu{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t){const i=this.queues[t];i.push(e),i.length===1&&this.buffers[t]&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const i=new Promise(n=>{t=n}),s={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(s,e),i}executeNext(e){const{buffers:t,queues:i}=this,s=t[e],n=i[e];if(n.length){const o=n[0];try{o.execute()}catch(a){C.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),o.onError(a),s!=null&&s.updating||(n.shift(),this.executeNext(e))}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const el=Ls(),tl=/([ha]vc.)(?:\.[^.,]+)+/;class Wu{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=()=>{const{media:t,mediaSource:i}=this;C.log("[buffer-controller]: Media source opened"),t&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(v.MEDIA_ATTACHED,{media:t})),i&&i.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{C.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{C.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:t,_objectUrl:i}=this;t&&t.src!==i&&C.error(`Media element src was set while attaching MediaSource (${i} > ${t.src})`)},this.hls=e,this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null}registerListeners(){const{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)}unregisterListeners(){const{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)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new zu(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,C.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const i=this.media=t.media;if(i&&el){const s=this.mediaSource=new el;s.addEventListener("sourceopen",this._onMediaSourceOpen),s.addEventListener("sourceended",this._onMediaSourceEnded),s.addEventListener("sourceclose",this._onMediaSourceClose),i.src=self.URL.createObjectURL(s),this._objectUrl=i.src,i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:i}=this;if(t){if(C.log("[buffer-controller]: media source detaching"),t.readyState==="open")try{t.endOfStream()}catch(s){C.warn(`[buffer-controller]: onMediaDetaching: ${s.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),e&&(e.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),e.src===i?(e.removeAttribute("src"),e.load()):C.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(v.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{const t=this.sourceBuffer[e];try{t&&(this.removeBufferListeners(e),this.mediaSource&&this.mediaSource.removeSourceBuffer(t),this.sourceBuffer[e]=void 0)}catch(i){C.warn(`[buffer-controller]: Failed to reset the ${e} buffer`,i)}}),this._initSourceBuffer()}onBufferCodecs(e,t){const i=this.getSourceBufferTypes().length;Object.keys(t).forEach(s=>{if(i){const n=this.tracks[s];if(n&&typeof n.buffer.changeType=="function"){const{id:o,codec:a,levelCodec:l,container:c,metadata:d}=t[s],h=(n.levelCodec||n.codec).replace(tl,"$1"),u=(l||a).replace(tl,"$1");if(h!==u){const f=`${c};codecs=${l||a}`;this.appendChangeType(s,f),C.log(`[buffer-controller]: switching codec ${h} to ${u}`),this.tracks[s]={buffer:n.buffer,codec:a,container:c,levelCodec:l,metadata:d,id:o}}}}else this.pendingTracks[s]=t[s]}),!i&&(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks())}appendChangeType(e,t){const{operationQueue:i}=this,s={execute:()=>{const n=this.sourceBuffer[e];n&&(C.log(`[buffer-controller]: changing ${e} sourceBuffer type to ${t}`),n.changeType(t)),i.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{C.warn(`[buffer-controller]: Failed to change ${e} SourceBuffer type`,n)}};i.append(s,e)}onBufferAppending(e,t){const{hls:i,operationQueue:s,tracks:n}=this,{data:o,type:a,frag:l,part:c,chunkMeta:d}=t,h=d.buffering[a],u=self.performance.now();h.start=u;const f=l.stats.buffering,g=c?c.stats.buffering:null;f.start===0&&(f.start=u),g&&g.start===0&&(g.start=u);const p=n.audio;let m=!1;a==="audio"&&(p==null?void 0:p.container)==="audio/mpeg"&&(m=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const A=l.start,x={execute:()=>{if(h.executeStart=self.performance.now(),m){const b=this.sourceBuffer[a];if(b){const y=A-b.timestampOffset;Math.abs(y)>=.1&&(C.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${A} (delta: ${y}) sn: ${l.sn})`),b.timestampOffset=A)}}this.appendExecutor(o,a)},onStart:()=>{},onComplete:()=>{const b=self.performance.now();h.executeEnd=h.end=b,f.first===0&&(f.first=b),g&&g.first===0&&(g.first=b);const{sourceBuffer:y}=this,T={};for(const E in y)T[E]=fe.getBuffered(y[E]);this.appendError=0,this.hls.trigger(v.BUFFER_APPENDED,{type:a,frag:l,part:c,chunkMeta:d,parent:l.type,timeRanges:T})},onError:b=>{C.error(`[buffer-controller]: Error encountered while trying to append to the ${a} SourceBuffer`,b);const y={type:q.MEDIA_ERROR,parent:l.type,details:D.BUFFER_APPEND_ERROR,frag:l,part:c,chunkMeta:d,error:b,err:b,fatal:!1};b.code===DOMException.QUOTA_EXCEEDED_ERR?y.details=D.BUFFER_FULL_ERROR:(this.appendError++,y.details=D.BUFFER_APPEND_ERROR,this.appendError>i.config.appendErrorMaxRetry&&(C.error(`[buffer-controller]: Failed ${i.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),y.fatal=!0)),i.trigger(v.ERROR,y)}};s.append(x,a)}onBufferFlushing(e,t){const{operationQueue:i}=this,s=n=>({execute:this.removeExecutor.bind(this,n,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(v.BUFFER_FLUSHED,{type:n})},onError:o=>{C.warn(`[buffer-controller]: Failed to remove from ${n} SourceBuffer`,o)}});t.type?i.append(s(t.type),t.type):this.getSourceBufferTypes().forEach(n=>{i.append(s(n),n)})}onFragParsed(e,t){const{frag:i,part:s}=t,n=[],o=s?s.elementaryStreams:i.elementaryStreams;o[de.AUDIOVIDEO]?n.push("audiovideo"):(o[de.AUDIO]&&n.push("audio"),o[de.VIDEO]&&n.push("video"));const a=()=>{const l=self.performance.now();i.stats.buffering.end=l,s&&(s.stats.buffering.end=l);const c=s?s.stats:i.stats;this.hls.trigger(v.FRAG_BUFFERED,{frag:i,part:s,stats:c,id:i.type})};n.length===0&&C.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(a,n)}onFragChanged(e,t){this.flushBackBuffer()}onBufferEos(e,t){this.getSourceBufferTypes().reduce((s,n)=>{const o=this.sourceBuffer[n];return o&&(!t.type||t.type===n)&&(o.ending=!0,o.ended||(o.ended=!0,C.log(`[buffer-controller]: ${n} sourceBuffer now EOS`))),s&&!!(!o||o.ended)},!0)&&(C.log("[buffer-controller]: Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(n=>{const o=this.sourceBuffer[n];o&&(o.ending=!1)});const{mediaSource:s}=this;if(!s||s.readyState!=="open"){s&&C.info(`[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ${s.readyState}`);return}C.log("[buffer-controller]: Calling mediaSource.endOfStream()"),s.endOfStream()}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}flushBackBuffer(){const{hls:e,details:t,media:i,sourceBuffer:s}=this;if(!i||t===null)return;const n=this.getSourceBufferTypes();if(!n.length)return;const o=t.live&&e.config.liveBackBufferLength!==null?e.config.liveBackBufferLength:e.config.backBufferLength;if(!W(o)||o<0)return;const a=i.currentTime,l=t.levelTargetDuration,c=Math.max(o,l),d=Math.floor(a/l)*l-c;n.forEach(h=>{const u=s[h];if(u){const f=fe.getBuffered(u);if(f.length>0&&d>f.start(0)){if(e.trigger(v.BACK_BUFFER_REACHED,{bufferEnd:d}),t.live)e.trigger(v.LIVE_BACK_BUFFER_REACHED,{bufferEnd:d});else if(u.ended&&f.end(f.length-1)-a<l*2){C.info(`[buffer-controller]: Cannot flush ${h} back buffer while SourceBuffer is in ended state`);return}e.trigger(v.BUFFER_FLUSHING,{startOffset:0,endOffset:d,type:h})}}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:e,hls:t,media:i,mediaSource:s}=this,n=e.fragments[0].start+e.totalduration,o=i.duration,a=W(s.duration)?s.duration:0;e.live&&t.config.liveDurationInfinity?(C.log("[buffer-controller]: Media Source duration is set to Infinity"),s.duration=1/0,this.updateSeekableRange(e)):(n>a&&n>o||!W(o))&&(C.log(`[buffer-controller]: Updating Media Source duration to ${n.toFixed(3)}`),s.duration=n)}updateSeekableRange(e){const t=this.mediaSource,i=e.fragments;if(i.length&&e.live&&t!=null&&t.setLiveSeekableRange){const n=Math.max(0,i[0].start),o=Math.max(n,n+e.totalduration);t.setLiveSeekableRange(n,o)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:i}=this,s=Object.keys(i).length;if(s&&!e||s===2){this.createSourceBuffers(i),this.pendingTracks={};const n=this.getSourceBufferTypes();if(n.length)this.hls.trigger(v.BUFFER_CREATED,{tracks:this.tracks}),n.forEach(o=>{t.executeNext(o)});else{const o=new Error("could not create source buffer for media codec(s)");this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:o,reason:o.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const s in e)if(!t[s]){const n=e[s];if(!n)throw Error(`source buffer exists for track ${s}, however track does not`);const o=n.levelCodec||n.codec,a=`${n.container};codecs=${o}`;C.log(`[buffer-controller]: creating sourceBuffer(${a})`);try{const l=t[s]=i.addSourceBuffer(a),c=s;this.addBufferListener(c,"updatestart",this._onSBUpdateStart),this.addBufferListener(c,"updateend",this._onSBUpdateEnd),this.addBufferListener(c,"error",this._onSBUpdateError),this.tracks[s]={buffer:l,codec:o,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(l){C.error(`[buffer-controller]: error while trying to add sourceBuffer: ${l.message}`),this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:l,mimeType:a})}}}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){const{operationQueue:t}=this;t.current(e).onComplete(),t.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){const i=new Error(`${e} SourceBuffer error`);C.error(`[buffer-controller]: ${i}`,t),this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:D.BUFFER_APPENDING_ERROR,error:i,fatal:!1});const s=this.operationQueue.current(e);s&&s.onError(t)}removeExecutor(e,t,i){const{media:s,mediaSource:n,operationQueue:o,sourceBuffer:a}=this,l=a[e];if(!s||!n||!l){C.warn(`[buffer-controller]: Attempting to remove from the ${e} SourceBuffer, but it does not exist`),o.shiftAndExecuteNext(e);return}const c=W(s.duration)?s.duration:1/0,d=W(n.duration)?n.duration:1/0,h=Math.max(0,t),u=Math.min(i,c,d);u>h&&!l.ending?(l.ended=!1,C.log(`[buffer-controller]: Removing [${h},${u}] from the ${e} SourceBuffer`),l.remove(h,u)):o.shiftAndExecuteNext(e)}appendExecutor(e,t){const{operationQueue:i,sourceBuffer:s}=this,n=s[t];if(!n){C.warn(`[buffer-controller]: Attempting to append to the ${t} SourceBuffer, but it does not exist`),i.shiftAndExecuteNext(t);return}n.ended=!1,n.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length){C.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}const{operationQueue:i}=this,s=t.map(n=>i.appendBlocker(n));Promise.all(s).then(()=>{e(),t.forEach(n=>{const o=this.sourceBuffer[n];o!=null&&o.updating||i.shiftAndExecuteNext(n)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,i){const s=this.sourceBuffer[e];if(!s)return;const n=i.bind(this,e);this.listeners[e].push({event:t,listener:n}),s.addEventListener(t,n)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach(i=>{t.removeEventListener(i.event,i.listener)})}}const il={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},sl=function(e){let t=e;return il.hasOwnProperty(e)&&(t=il[e]),String.fromCharCode(t)},dt=15,Rt=100,Yu={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Ku={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Xu={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},qu={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Zu=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Ju{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;C.log(`${this.time} [${e}] ${i}`)}}}const ei=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class rl{constructor(e,t,i,s,n){this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=e||"white",this.underline=t||!1,this.italics=i||!1,this.background=s||"black",this.flash=n||!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){const s=t[i];e.hasOwnProperty(s)&&(this[s]=e[s])}}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}}class Qu{constructor(e,t,i,s,n,o){this.uchar=void 0,this.penState=void 0,this.uchar=e||" ",this.penState=new rl(t,i,s,n,o)}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()}}class _u{constructor(e){this.chars=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(let t=0;t<Rt;t++)this.chars.push(new Qu);this.logger=e,this.pos=0,this.currPenState=new rl}equals(e){let t=!0;for(let i=0;i<Rt;i++)if(!this.chars[i].equals(e.chars[i])){t=!1;break}return t}copy(e){for(let t=0;t<Rt;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Rt;t++)if(!this.chars[t].isEmpty()){e=!1;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>Rt&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Rt)}moveCursor(e){const 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();const t=sl(e);if(this.pos>=Rt){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<Rt;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let i=0;i<Rt;i++){const s=this.chars[i].uchar;s!==" "&&(t=!1),e.push(s)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class un{constructor(e){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(let t=0;t<dt;t++)this.rows.push(new _u(e));this.logger=e,this.currRow=dt-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}reset(){for(let e=0;e<dt;e++)this.rows[e].clear();this.currRow=dt-1}equals(e){let t=!0;for(let i=0;i<dt;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<dt;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<dt;t++)if(!this.rows[t].isEmpty()){e=!1;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 = "+JSON.stringify(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<dt;a++)this.rows[a].clear();const n=this.currRow+1-this.nrRollUpRows,o=this.lastOutputScreen;if(o){const a=o.rows[n].cueStartTime,l=this.logger.time;if(a&&l!==null&&a<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(o.rows[n+c])}}this.currRow=t;const i=this.rows[this.currRow];if(e.indent!==null){const n=e.indent,o=Math.max(n-1,0);i.setCursor(e.indent),e.color=i.chars[o].penState.foreground}const s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+JSON.stringify(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());const 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||!1;const t=[];let i="",s=-1;for(let n=0;n<dt;n++){const o=this.rows[n].getTextString();o&&(s=n+1,e?t.push("Row "+s+": '"+o+"'"):t.push(o.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
80
+ `)),i}getTextAndFormat(){return this.rows}}class nl{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 un(i),this.nonDisplayedMemory=new un(i),this.lastOutputScreen=new un(i),this.currRollUpRow=this.displayedMemory.rows[dt-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[dt-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]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),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:!0})}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(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}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"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=s[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const 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))}}class ol{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const s=new Ju;this.channels=[null,new nl(e,t,s),new nl(e+1,i,s)],this.cmdHistory=ll(),this.logger=s}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){let i,s,n,o=!1;this.logger.time=e;for(let a=0;a<t.length;a+=2)if(s=t[a]&127,n=t[a+1]&127,!(s===0&&n===0)){if(this.logger.log(3,"["+ei([t[a],t[a+1]])+"] -> ("+ei([s,n])+")"),i=this.parseCmd(s,n),i||(i=this.parseMidrow(s,n)),i||(i=this.parsePAC(s,n)),i||(i=this.parseBackgroundAttributes(s,n)),!i&&(o=this.parseChars(s,n),o)){const l=this.currentChannel;l&&l>0?this.channels[l].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!i&&!o&&this.logger.log(2,"Couldn't parse cleaned data "+ei([s,n])+" orig: "+ei([t[a],t[a+1]]))}}parseCmd(e,t){const{cmdHistory:i}=this,s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(s||n))return!1;if(al(e,t,i))return yi(null,null,i),this.logger.log(3,"Repeated command ("+ei([e,t])+") is dropped"),!0;const o=e===20||e===21||e===23?1:2,a=this.channels[o];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),yi(e,t,i),this.currentChannel=o,!0}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"),!1;const s=this.channels[i];return s?(s.ccMIDROW(t),this.logger.log(3,"MIDROW ("+ei([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const s=this.cmdHistory,n=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,o=(e===16||e===24)&&t>=64&&t<=95;if(!(n||o))return!1;if(al(e,t,s))return yi(null,null,s),!0;const a=e<=23?1:2;t>=64&&t<=95?i=a===1?Yu[e]:Xu[e]:i=a===1?Ku[e]:qu[e];const l=this.channels[a];return l?(l.setPAC(this.interpretPAC(i,t)),yi(e,t,s),this.currentChannel=a,!0):!1}interpretPAC(e,t){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,s.underline=(i&1)===1,i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=Math.floor((i-16)/2)*4,s}parseChars(e,t){let i,s=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 '"+sl(o)+"' in channel "+i),s=[o]}else e>=32&&e<=127&&(s=t===0?[e]:[e,t]);if(s){const o=ei(s);this.logger.log(3,"Char codes = "+o.join(",")),yi(e,t,this.cmdHistory)}return s}parseBackgroundAttributes(e,t){const i=(e===16||e===24)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=45&&t<=47;if(!(i||s))return!1;let n;const o={};e===16||e===24?(n=Math.floor((t-32)/2),o.background=Zu[n],t%2===1&&(o.background=o.background+"_semi")):t===45?o.background="transparent":(o.foreground="black",t===47&&(o.underline=!0));const a=e<=23?1:2;return this.channels[a].setBkgData(o),yi(e,t,this.cmdHistory),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}this.cmdHistory=ll()}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const i=this.channels[t];i&&i.cueSplitAtTime(e)}}}function yi(r,e,t){t.a=r,t.b=e}function al(r,e,t){return t.a===r&&t.b===e}function ll(){return{a:null,b:null}}class Gs{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}}var fn=function(){if(typeof self<"u"&&self.VTTCue)return self.VTTCue;const r=["","lr","rl"],e=["start","middle","end","left","right"];function t(a,l){if(typeof l!="string"||!Array.isArray(a))return!1;const c=l.toLowerCase();return~a.indexOf(c)?c:!1}function i(a){return t(r,a)}function s(a){return t(e,a)}function n(a,...l){let c=1;for(;c<arguments.length;c++){const d=arguments[c];for(const h in d)a[h]=d[h]}return a}function o(a,l,c){const d=this,h={enumerable:!0};d.hasBeenReset=!1;let u="",f=!1,g=a,p=l,m=c,A=null,x="",b=!0,y="auto",T="start",E=50,S="middle",R=50,w="middle";Object.defineProperty(d,"id",n({},h,{get:function(){return u},set:function(I){u=""+I}})),Object.defineProperty(d,"pauseOnExit",n({},h,{get:function(){return f},set:function(I){f=!!I}})),Object.defineProperty(d,"startTime",n({},h,{get:function(){return g},set:function(I){if(typeof I!="number")throw new TypeError("Start time must be set to a number.");g=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"endTime",n({},h,{get:function(){return p},set:function(I){if(typeof I!="number")throw new TypeError("End time must be set to a number.");p=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"text",n({},h,{get:function(){return m},set:function(I){m=""+I,this.hasBeenReset=!0}})),Object.defineProperty(d,"region",n({},h,{get:function(){return A},set:function(I){A=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"vertical",n({},h,{get:function(){return x},set:function(I){const O=i(I);if(O===!1)throw new SyntaxError("An invalid or illegal string was specified.");x=O,this.hasBeenReset=!0}})),Object.defineProperty(d,"snapToLines",n({},h,{get:function(){return b},set:function(I){b=!!I,this.hasBeenReset=!0}})),Object.defineProperty(d,"line",n({},h,{get:function(){return y},set:function(I){if(typeof I!="number"&&I!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");y=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"lineAlign",n({},h,{get:function(){return T},set:function(I){const O=s(I);if(!O)throw new SyntaxError("An invalid or illegal string was specified.");T=O,this.hasBeenReset=!0}})),Object.defineProperty(d,"position",n({},h,{get:function(){return E},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");E=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"positionAlign",n({},h,{get:function(){return S},set:function(I){const O=s(I);if(!O)throw new SyntaxError("An invalid or illegal string was specified.");S=O,this.hasBeenReset=!0}})),Object.defineProperty(d,"size",n({},h,{get:function(){return R},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");R=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"align",n({},h,{get:function(){return w},set:function(I){const O=s(I);if(!O)throw new SyntaxError("An invalid or illegal string was specified.");w=O,this.hasBeenReset=!0}})),d.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o}();class $u{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function cl(r){function e(i,s,n,o){return(i|0)*3600+(s|0)*60+(n|0)+parseFloat(o||0)}const t=r.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}class ef{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 s=0;s<i.length;++s)if(t===i[s]){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)){const i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}function dl(r,e,t,i){const s=i?r.split(i):[r];for(const n in s){if(typeof s[n]!="string")continue;const o=s[n].split(t);if(o.length!==2)continue;const a=o[0],l=o[1];e(a,l)}}const gn=new fn(0,0,""),Vs=gn.align==="middle"?"middle":"center";function tf(r,e,t){const i=r;function s(){const a=cl(r);if(a===null)throw new Error("Malformed timestamp: "+i);return r=r.replace(/^[^\sa-zA-Z-]+/,""),a}function n(a,l){const c=new ef;dl(a,function(u,f){let g;switch(u){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){c.set(u,t[p].region);break}break;case"vertical":c.alt(u,f,["rl","lr"]);break;case"line":g=f.split(","),c.integer(u,g[0]),c.percent(u,g[0])&&c.set("snapToLines",!1),c.alt(u,g[0],["auto"]),g.length===2&&c.alt("lineAlign",g[1],["start",Vs,"end"]);break;case"position":g=f.split(","),c.percent(u,g[0]),g.length===2&&c.alt("positionAlign",g[1],["start",Vs,"end","line-left","line-right","auto"]);break;case"size":c.percent(u,f);break;case"align":c.alt(u,f,["start",Vs,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let d=c.get("line","auto");d==="auto"&&gn.line===-1&&(d=-1),l.line=d,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",Vs);let h=c.get("position","auto");h==="auto"&&gn.position===50&&(h=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=h}function o(){r=r.replace(/^\s+/,"")}if(o(),e.startTime=s(),o(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);r=r.slice(3),o(),e.endTime=s(),o(),n(r,e)}function hl(r){return r.replace(/<br(?: \/)?>/gi,`
81
81
  `)}class sf{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new $u,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let n=t.buffer,o=0;for(n=hl(n);o<n.length&&n[o]!=="\r"&&n[o]!==`
82
82
  `;)++o;const a=n.slice(0,o);return n[o]==="\r"&&++o,n[o]===`
83
83
  `&&++o,t.buffer=n.slice(o),a}function s(n){dl(n,function(o,a){},/:/)}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=i();const 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)?s(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 fn(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{tf(n,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const 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+=`
@@ -85,18 +85,18 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
85
85
 
86
86
  `,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}}const rf=/\r\n|\n\r|\n|\r/g,pn=function(e,t,i=0){return e.slice(i,i+t.length)===t},nf=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!W(t)||!W(i)||!W(s)||!W(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*s,t+=60*60*1e3*n,t},mn=function(e){let t=5381,i=e.length;for(;i;)t=t*33^e.charCodeAt(--i);return(t>>>0).toString()};function vn(r,e,t){return mn(r.toString())+mn(e.toString())+mn(t)}const of=function(e,t,i){let s=e[t],n=e[s.prevCC];if(!n||!n.new&&s.new){e.ccOffset=e.presentationOffset=s.start,s.new=!1;return}for(;(o=n)!=null&&o.new;){var o;e.ccOffset+=s.start-n.start,s.new=!1,s=n,n=e[s.prevCC]}e.presentationOffset=i};function af(r,e,t,i,s,n,o){const a=new sf,l=ft(new Uint8Array(r)).trim().replace(rf,`
87
87
  `).split(`
88
- `),c=[],d=vu(e.baseTime,e.timescale);let h="00:00.000",u=0,f=0,g,p=!0;a.oncue=function(m){const A=t[i];let T=t.ccOffset;const b=(u-d)/9e4;A!=null&&A.new&&(f!==void 0?T=t.ccOffset=A.start:of(t,i,b)),b&&(T=b-t.presentationOffset);const y=m.endTime-m.startTime,x=$e((m.startTime+T-f)*9e4,s*9e4)/9e4;m.startTime=Math.max(x,0),m.endTime=Math.max(x+y,0);const E=m.text.trim();m.text=decodeURIComponent(encodeURIComponent(E)),m.id||(m.id=vn(m.startTime,m.endTime,E)),m.endTime>0&&c.push(m)},a.onparsingerror=function(m){g=m},a.onflush=function(){if(g){o(g);return}n(c)},l.forEach(m=>{if(p)if(pn(m,"X-TIMESTAMP-MAP=")){p=!1,m.slice(16).split(",").forEach(A=>{pn(A,"LOCAL:")?h=A.slice(6):pn(A,"MPEGTS:")&&(u=parseInt(A.slice(7)))});try{f=nf(h)/1e3}catch(A){g=A}return}else m===""&&(p=!1);a.parse(m+`
89
- `)}),a.flush()}const yn="stpp.ttml.im1t",ul=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,fl=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,lf={left:"start",center:"center",right:"end",start:"start",end:"end"};function gl(r,e,t,i){const s=re(new Uint8Array(r),["mdat"]);if(s.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const n=s.map(a=>ft(a)),o=mu(e.baseTime,1,e.timescale);try{n.forEach(a=>t(cf(a,o)))}catch(a){i(a)}}function cf(r,e){const s=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},o=Object.keys(n).reduce((h,u)=>(h[u]=s.getAttribute(`ttp:${u}`)||n[u],h),{}),a=s.getAttribute("xml:space")!=="preserve",l=pl(An(s,"styling","style")),c=pl(An(s,"layout","region")),d=An(s,"body","[begin]");return[].map.call(d,h=>{const u=ml(h,a);if(!u||!h.hasAttribute("begin"))return null;const f=xn(h.getAttribute("begin"),o),g=xn(h.getAttribute("dur"),o);let p=xn(h.getAttribute("end"),o);if(f===null)throw vl(h);if(p===null){if(g===null)throw vl(h);p=f+g}const m=new fn(f-e,p-e,u);m.id=vn(m.startTime,m.endTime,m.text);const A=c[h.getAttribute("region")],T=l[h.getAttribute("style")],b=df(A,T,l),{textAlign:y}=b;if(y){const x=lf[y];x&&(m.lineAlign=x),m.align=y}return Ce(m,b),m}).filter(h=>h!==null)}function An(r,e,t){const i=r.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function pl(r){return r.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function ml(r,e){return[].slice.call(r.childNodes).reduce((t,i,s)=>{var n;return i.nodeName==="br"&&s?t+`
90
- `:(n=i.childNodes)!=null&&n.length?ml(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function df(r,e,t){const i="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return o&&t.hasOwnProperty(o)&&(s=t[o]),n.reduce((a,l)=>{const c=bn(e,i,l)||bn(r,i,l)||bn(s,i,l);return c&&(a[l]=c),a},{})}function bn(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function vl(r){return new Error(`Could not parse ttml timestamp ${r}`)}function xn(r,e){if(!r)return null;let t=cl(r);return t===null&&(ul.test(r)?t=hf(r,e):fl.test(r)&&(t=uf(r,e))),t}function hf(r,e){const t=ul.exec(r),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 uf(r,e){const t=fl.exec(r),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}class ff{constructor(e){if(this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,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.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=yl(),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}},this.config.enableCEA708Captions){const t=new Gs(this,"textTrack1"),i=new Gs(this,"textTrack2"),s=new Gs(this,"textTrack3"),n=new Gs(this,"textTrack4");this.cea608Parser1=new ol(1,t,i),this.cea608Parser2=new ol(3,s,n)}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(){const{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.cea608Parser1=this.cea608Parser2=null}addCues(e,t,i,s,n){let o=!1;for(let a=n.length;a--;){const l=n[a],c=pf(l[0],l[1],t,i);if(c>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),o=!0,c/(i-t)>.5))return}if(o||n.push([t,i]),this.config.renderTextTracksNatively){const a=this.captionsTracks[e];this.Cues.newCue(a,t,i,s)}else{const a=this.Cues.newCue(null,t,i,s);this.hls.trigger(v.CUES_PARSED,{type:"captions",cues:a,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n}){const{unparsedVttFrags:o}=this;i==="main"&&(this.initPTS[t.cc]={baseTime:s,timescale:n}),o.length&&(this.unparsedVttFrags=[],o.forEach(a=>{this.onFragLoaded(v.FRAG_LOADED,a)}))}getExistingTrack(e){const{media:t}=this;if(t)for(let i=0;i<t.textTracks.length;i++){const s=t.textTracks[i];if(s[e])return s}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:s}=this,{label:n,languageCode:o}=t[e],a=this.getExistingTrack(e);if(a)i[e]=a,fi(i[e]),ua(i[e],s);else{const l=this.createTextTrack("captions",n,o);l&&(l[e]=!0,i[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i=t.label,s={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(v.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,t,i){const s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach(t=>{fi(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=yl(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=this.unparsedVttFrags||[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let i=0;i<t.length;i++)fi(t[i])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],s=i.some(n=>n.textCodec===yn);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(_a(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const o=this.media?this.media.textTracks:null;this.tracks.forEach((a,l)=>{let c;if(o&&l<o.length){let d=null;for(let h=0;h<o.length;h++)if(gf(o[h],a)){d=o[h];break}d&&(c=d)}if(c)fi(c);else{const d=this._captionsOrSubtitlesFromCharacteristics(a);c=this.createTextTrack(d,a.name,a.lang),c&&(c.mode="disabled")}c&&(c.groupId=a.groupId,this.textTracks.push(c))})}else if(this.tracks.length){const 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})}}}_captionsOrSubtitlesFromCharacteristics(e){if(e.attrs.CHARACTERISTICS){const t=/transcribes-spoken-dialog/gi.test(e.attrs.CHARACTERISTICS),i=/describes-music-and-sound/gi.test(e.attrs.CHARACTERISTICS);if(t&&i)return"captions"}return"subtitles"}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;const n=`textTrack${s[1]}`,o=this.captionsProperties[n];o&&(o.label=i.name,i.lang&&(o.languageCode=i.lang),o.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){const{cea608Parser1:i,cea608Parser2:s,lastSn:n,lastPartIndex:o}=this;if(!(!this.enabled||!(i&&s))&&t.frag.type===Z.MAIN){var a,l;const c=t.frag.sn,d=(a=t==null||(l=t.part)==null?void 0:l.index)!=null?a:-1;c===n+1||c===n&&d===o+1||(i.reset(),s.reset()),this.lastSn=c,this.lastPartIndex=d}}onFragLoaded(e,t){const{frag:i,payload:s}=t,{initPTS:n,unparsedVttFrags:o}=this;if(i.type===Z.SUBTITLE)if(s.byteLength){if(!n[i.cc]){o.push(t),n.length&&this.hls.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Missing initial subtitle PTS")});return}const a=i.decryptdata,l="stats"in t;if(a==null||!a.encrypted||l){const c=this.tracks[i.level],d=this.vttCCs;d[i.cc]||(d[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),c&&c.textCodec===yn?this._parseIMSC1(i,s):this._parseVTTs(i,s,d)}}else this.hls.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;gl(t,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),i.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{C.log(`Failed to parse IMSC1: ${s}`),i.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:s})})}_parseVTTs(e,t,i){var s;const n=this.hls,o=(s=e.initSegment)!=null&&s.data?$t(e.initSegment.data,new Uint8Array(t)):t;af(o,this.initPTS[e.cc],i,e.cc,e.start,a=>{this._appendCues(a,e.level),n.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},a=>{this._fallbackToIMSC1(e,t),C.log(`Failed to parse VTT cue: ${a}`),n.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:a})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||gl(t,this.initPTS[e.cc],()=>{i.textCodec=yn,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[t];if(!s||s.mode==="disabled")return;e.forEach(n=>fa(s,n))}else{const s=this.tracks[t];if(!s)return;const n=s.default?"default":"subtitles"+t;i.trigger(v.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){const{frag:i}=t;if(i.type===Z.SUBTITLE){if(!this.initPTS[i.cc]){this.unparsedVttFrags.push(t);return}this.onFragLoaded(v.FRAG_LOADED,t)}}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){const{cea608Parser1:i,cea608Parser2:s}=this;if(!this.enabled||!(i&&s))return;const{frag:n,samples:o}=t;if(!(n.type===Z.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let a=0;a<o.length;a++){const l=o[a].bytes;if(l){const c=this.extractCea608Data(l);i.addData(o[a].pts,c[0]),s.addData(o[a].pts,c[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:s,type:n}){const{media:o}=this;if(!(!o||o.currentTime<i)){if(!n||n==="video"){const{captionsTracks:a}=this;Object.keys(a).forEach(l=>Ur(a[l],t,i))}if(this.config.renderTextTracksNatively&&t===0&&s!==void 0){const{textTracks:a}=this;Object.keys(a).forEach(l=>Ur(a[l],t,s))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let s=2;for(let n=0;n<i;n++){const o=e[s++],a=127&e[s++],l=127&e[s++];if(a===0&&l===0)continue;if((4&o)!==0){const d=3&o;(d===0||d===1)&&(t[d].push(a),t[d].push(l))}}return t}}function gf(r,e){return!!r&&r.label===e.name&&!(r.textTrack1||r.textTrack2)}function pf(r,e,t,i){return Math.min(e,i)-Math.max(r,t)}function yl(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class Tn{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.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{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.BUFFER_CODECS,this.onBufferCodecs,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{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.BUFFER_CODECS,this.onBufferCodecs,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const 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}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){const e=this.hls.levels;if(e.length){const t=this.hls;t.autoLevelCapping=this.getMaxLevel(e.length-1),t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((s,n)=>this.isLevelAllowed(s)&&n<=e);return this.clientRect=null,Tn.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),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;const e=this.media,t={width:0,height:0};if(e){const 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 e}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;const s=(o,a)=>a?o.width!==a.width||o.height!==a.height:!0;let n=e.length-1;for(let o=0;o<e.length;o+=1){const a=e[o];if((a.width>=t||a.height>=i)&&s(a,e[o+1])){n=o;break}}return n}}class mf{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,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)}unregisterListeners(){this.hls.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const s=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){const s=performance.now();if(t){if(this.lastTime){const n=s-this.lastTime,o=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,l=1e3*o/n,c=this.hls;if(c.trigger(v.FPS_DROP,{currentDropped:o,currentDecoded:a,totalDroppedFrames:i}),l>0&&o>c.config.fpsDroppedMonitoringThreshold*a){let d=c.currentLevel;C.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=d)&&(d=d-1,c.trigger(v.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:c.currentLevel}),c.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}const js="[eme]";class yi{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=yi.CDMCleanupPromise?[yi.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=C.debug.bind(C,js),this.log=C.log.bind(C,js),this.warn=C.warn.bind(C,js),this.error=C.error.bind(C,js),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=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)}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)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,s=t[e];if(s)return s.licenseUrl;if(e===ve.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(o,a,l)=>!!o&&l.indexOf(o)===a,s=t.map(o=>o.audioCodec).filter(i),n=t.map(o=>o.videoCodec).filter(i);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((o,a)=>{const l=c=>{const d=c.shift();this.getMediaKeysPromise(d,s,n).then(h=>o({keySystem:d,mediaKeys:h})).catch(h=>{c.length?l(c):h instanceof et?a(h):a(new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Go===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return i(e,t)}getMediaKeysPromise(e,t,i){const s=Rd(e,t,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[e];let o=n==null?void 0:n.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(s)}`),o=this.requestMediaKeySystemAccess(e,s);const a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const c=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),a.mediaKeys=l.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),c.then(h=>h?this.setMediaKeysServerCertificate(d,e,h):d))),a.mediaKeys.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),a.mediaKeys})}return o.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${gt.hexDump(e.keyId||[])}`);const s=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),s=this.getKeyIdString(t),n="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,n,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return gt.hexDump(e.keyId)}updateKeySession(e,t){var i;const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyID ${gt.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])}
91
- } (data length: ${t&&t.byteLength})`),s.update(t)}selectKeySystemFormat(e){const 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){return new Promise((t,i)=>{const s=kr(this.config),n=e.map(Bo).filter(o=>!!o&&s.indexOf(o)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:o})=>{const a=Ho(o);a?t(a):i(new Error(`Unable to find format for key-system "${o}"`))}).catch(i)})}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),s=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${s}`);let n=this.keyIdToKeySessionPromise[i];return n||(n=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:o,mediaKeys:a})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${s}`),this.attemptSetMediaKeys(o,a).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:o,mediaKeys:a,decryptdata:t}),c="cenc";return this.generateRequestWithPreferredKeySession(l,c,t.pssh,"playlist-key")}))),n.catch(o=>this.handleError(o))),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof et?this.hls.trigger(v.ERROR,e.data):this.hls.trigger(v.ERROR,{type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const s=Bo(e.keyFormat),n=s?[s]:kr(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=kr(this.config)),e.length===0)throw new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:i}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),i===null)return;let s,n;if(t==="sinf"&&this.config.drmSystems[ve.FAIRPLAY]){const d=De(new Uint8Array(i));try{const h=Dr(JSON.parse(d).sinf),u=qo(new Uint8Array(h));if(!u)return;s=u.subarray(8,24),n=ve.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{const d=$d(i);if(d===null)return;d.version===0&&d.systemId===Uo.WIDEVINE&&d.data&&(s=d.data.subarray(8,24)),n=Ld(d.systemId)}if(!n||!s)return;const o=gt.hexDump(s),{keyIdToKeySessionPromise:a,mediaKeySessions:l}=this;let c=a[o];for(let d=0;d<l.length;d++){const h=l[d],u=h.decryptdata;if(u.pssh||!u.keyId)continue;const f=gt.hexDump(u.keyId);if(o===f||u.uri.replace(/-/g,"").indexOf(o)!==-1){c=a[f],delete a[f],u.pssh=new Uint8Array(i),u.keyId=s,c=a[o]=c.then(()=>this.generateRequestWithPreferredKeySession(h,t,i,"encrypted-event-key-match"));break}}c||(c=a[o]=this.getKeySystemSelectionPromise([n]).then(({keySystem:d,mediaKeys:h})=>{var u;this.throwIfDestroyed();const f=new qi("ISO-23001-7",o,(u=Ho(d))!=null?u:"");return f.pssh=new Uint8Array(i),f.keyId=s,this.attemptSetMediaKeys(d,h).then(()=>{this.throwIfDestroyed();const g=this.createMediaKeySessionContext({decryptdata:f,keySystem:d,mediaKeys:h});return this.generateRequestWithPreferredKeySession(g,t,i,"encrypted-event-no-match")})})),c.catch(d=>this.handleError(d))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const s=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,i,s){var n,o;const a=(n=this.config.drmSystems)==null||(o=n[e.keySystem])==null?void 0:o.generateRequest;if(a)try{const u=a.call(this.hls,t,i,e);if(!u)throw new Error("Invalid response from configured generateRequest filter");t=u.initDataType,i=e.decryptdata.pssh=u.initData?new Uint8Array(u.initData):null}catch(u){var l;if(this.warn(u.message),(l=this.hls)!=null&&l.config.debug)throw u}if(i===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);const c=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${s}": ${c} (init data type: ${t} length: ${i?i.byteLength:null})`);const d=new ln;e.mediaKeysSession.onmessage=u=>{const f=e.mediaKeysSession;if(!f){d.emit("error",new Error("invalid state"));return}const{messageType:g,message:p}=u;this.log(`"${g}" message event for session "${f.sessionId}" message size: ${p.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,p).catch(m=>{this.handleError(m),d.emit("error",m)}):g==="license-release"?e.keySystem===ve.FAIRPLAY&&(this.updateKeySession(e,No("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${g}"`)},e.mediaKeysSession.onkeystatuseschange=u=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const g=e.keyStatus;d.emit("keyStatus",g),g==="expired"&&(this.warn(`${e.keySystem} expired for key ${c}`),this.renewKeySession(e))};const h=new Promise((u,f)=>{d.on("error",f),d.on("keyStatus",g=>{g.startsWith("usable")?u():g==="output-restricted"?f(new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):g==="internal-error"?f(new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${g}"`)):g==="expired"?f(new Error("key expired while generating request")):this.warn(`unhandled key status change "${g}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var u;this.log(`Request generated for key-session "${(u=e.mediaKeysSession)==null?void 0:u.sessionId}" keyId: ${c}`)}).catch(u=>{throw new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_SESSION,error:u,fatal:!1},`Error generating key-session request: ${u}`)}).then(()=>h).catch(u=>{throw d.removeAllListeners(),this.removeSession(e),u}).then(()=>(d.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${gt.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${gt.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,i=t.loader,s=new i(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching serverCertificate for "${e}"`),new Promise((o,a)=>{const l={responseType:"arraybuffer",url:n},c=t.certLoadPolicy.default,d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,f,g,p)=>{o(u.data)},onError:(u,f,g,p)=>{a(new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:je({url:l.url,data:void 0},u)},`"${e}" certificate request failed (${n}). Status: ${u.code} (${u.text})`))},onTimeout:(u,f,g)=>{a(new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(u,f,g)=>{a(new Error("aborted"))}};s.load(l,d,h)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((s,n)=>{e.setServerCertificate(i).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),s(e)}).catch(o=>{n(new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:o,fatal:!0},o.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(s=>{throw new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:s,fatal:!0},s.message)}))}setupLicenseXHR(e,t,i,s){const 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,s)}).catch(o=>{if(!i.decryptdata)throw o;return e.open("POST",t,!0),n.call(this.hls,e,t,i,s)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||s})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((s,n)=>{const o=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${o}`);const 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}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,a,o,e)}catch(d){this.error(d)}s(l)}else{const l=i.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||a.status>=400&&a.status<500)n(new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,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{const d=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${d} attempts left`),this.requestLicense(e,t).then(s,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,o,e,t).then(({xhr:l,licenseChallenge:c})=>{l.send(c)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},qi.clearKeyUriToKeyIdMap();const i=t.length;yi.CDMCleanupPromise=Promise.all(t.map(s=>this.removeSession(s)).concat(e==null?void 0:e.setMediaKeys(null).catch(s=>{this.log(`Could not clear media keys: ${s}. media.src: ${e==null?void 0:e.src}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(s=>{this.log(`Could not close sessions and clear media keys: ${s}. media.src: ${e==null?void 0:e.src}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((s,n)=>(s.indexOf(n.keyFormat)===-1&&s.push(n.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),t.onmessage=null,t.onkeystatuseschange=null,i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const s=this.mediaKeySessions.indexOf(e);return s>-1&&this.mediaKeySessions.splice(s,1),t.remove().catch(n=>{this.log(`Could not remove session: ${n}`)}).then(()=>t.close()).catch(n=>{this.log(`Could not close session: ${n}`)})}}}yi.CDMCleanupPromise=void 0;class et 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}}const vf=1;var Ke={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"};const yf="h";class Ht{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=s=>{try{this.apply(s,{ot:Ke.MANIFEST,su:!this.initialized})}catch(n){C.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=s=>{try{const n=s.frag,o=this.hls.levels[n.level],a=this.getObjectType(n),l={d:n.duration*1e3,ot:a};(a===Ke.VIDEO||a===Ke.AUDIO||a==Ke.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(a)/1e3,l.bl=this.getBufferLength(a)),this.apply(s,l)}catch(n){C.warn("Could not generate segment CMCD data.",n)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||Ht.uuid(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.registerListeners())}registerListeners(){const 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(){const 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}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,s;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(s=t.tracks.video)==null?void 0:s.buffer}createData(){var e;return{v:vf,sf:yf,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Ce(t,this.createData());const i=t.ot===Ke.INIT||t.ot===Ke.VIDEO||t.ot===Ke.MUXED;if(this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering),this.useHeaders){const s=Ht.toHeaders(t);if(!Object.keys(s).length)return;e.headers||(e.headers={}),Ce(e.headers,s)}else{const s=Ht.toQuery(t);if(!s)return;e.url=Ht.appendQueryToUri(e.url,s)}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Ke.TIMED_TEXT;if(e.sn==="initSegment")return Ke.INIT;if(t==="audio")return Ke.AUDIO;if(t==="main")return this.hls.audioTracks.length?Ke.VIDEO:Ke.MUXED}getTopBandwidth(e){let t=0,i;const s=this.hls;if(e===Ke.AUDIO)i=s.audioTracks;else{const n=s.maxAutoLevel,o=n>-1?n+1:s.levels.length;i=s.levels.slice(0,o)}for(const n of i)n.bitrate>t&&(t=n.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.hls.media,i=e===Ke.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:fe.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{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(){const{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)}}}static uuid(){const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}static serialize(e){const t=[],i=c=>!Number.isNaN(c)&&c!=null&&c!==""&&c!==!1,s=c=>Math.round(c),n=c=>s(c/100)*100,a={br:s,d:s,bl:n,dl:n,mtp:n,nor:c=>encodeURIComponent(c),rtp:n,tb:s},l=Object.keys(e||{}).sort();for(const c of l){let d=e[c];if(!i(d)||c==="v"&&d===1||c=="pr"&&d===1)continue;const h=a[c];h&&(d=h(d));const u=typeof d;let f;c==="ot"||c==="sf"||c==="st"?f=`${c}=${d}`:u==="boolean"?f=c:u==="number"?f=`${c}=${d}`:f=`${c}=${JSON.stringify(d)}`,t.push(f)}return t.join(",")}static toHeaders(e){const t=Object.keys(e),i={},s=["Object","Request","Session","Status"],n=[{},{},{},{}],o={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const a of t){const l=o[a]!=null?o[a]:1;n[l][a]=e[a]}for(let a=0;a<n.length;a++){const l=Ht.serialize(n[a]);l&&(i[`CMCD-${s[a]}`]=l)}return i}static toQuery(e){return`CMCD=${encodeURIComponent(Ht.serialize(e))}`}static appendQueryToUri(e,t){if(!t)return e;const i=e.includes("?")?"&":"?";return`${e}${i}${t}`}}const Af=3e5;class bf{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=C.log.bind(C,"[content-steering]:"),this.registerListeners()}registerListeners(){const 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(){const 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))}startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){const e=Math.max(this.timeToLoad*1e3-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,e)}else this.loadSteeringManifest(this.uri)}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),self.clearTimeout(this.reloadTimer)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{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){const{errorAction:i}=t;if((i==null?void 0:i.action)===Ye.SendAlternateToPenaltyBox&&i.flags===ct.MoveAllAlternatesMatchingHost){let s=this.pathwayPriority;const n=this.pathwayId;this.penalizedPathways[n]||(this.penalizedPathways[n]=performance.now()),!s&&this.levels&&(s=this.levels.reduce((o,a)=>(o.indexOf(a.pathwayId)===-1&&o.push(a.pathwayId),o),[])),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==n)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const 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):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(n=>{s-i[n]>Af&&delete i[n]});for(let n=0;n<e.length;n++){const o=e[n];if(i[o])continue;if(o===this.pathwayId)return;const 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,this.hls.trigger(v.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[a];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=a);break}}}clonePathways(e){const t=this.levels;if(!t)return;const i={},s={};e.forEach(n=>{const{ID:o,"BASE-ID":a,"URI-REPLACEMENT":l}=n;if(t.some(d=>d.pathwayId===o))return;const c=this.getLevelsForPathway(a).map(d=>{const h=Ce({},d);h.details=void 0,h.url=bl(d.uri,d.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l);const u=new me(d.attrs);u["PATHWAY-ID"]=o;const f=u.AUDIO&&`${u.AUDIO}_clone_${o}`,g=u.SUBTITLES&&`${u.SUBTITLES}_clone_${o}`;f&&(i[u.AUDIO]=f,u.AUDIO=f),g&&(s[u.SUBTITLES]=g,u.SUBTITLES=g),h.attrs=u;const p=new Ji(h);return Ps(p,"audio",f),Ps(p,"text",g),p});t.push(...c),Al(this.audioTracks,i,l,o),Al(this.subtitleTracks,s,l,o)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let s;try{s=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){const d=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+d)}const n={responseType:"json",url:s.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},c={onSuccess:(d,h,u,f)=>{this.log(`Loaded steering manifest: "${s}"`);const g=d.data;if(g.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":m,"PATHWAY-PRIORITY":A}=g;if(p)try{this.uri=new self.URL(p,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||u.url),m&&this.clonePathways(m),A&&this.updatePathwayPriority(A)},onError:(d,h,u,f)=>{if(this.log(`Error loading steering manifest: ${d.code} ${d.text} (${h.url})`),this.stopLoad(),d.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let g=this.timeToLoad*1e3;if(d.code===429){const p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){const m=p.getResponseHeader("Retry-After");m&&(g=parseFloat(m)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},onTimeout:(d,h,u)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout(()=>{this.loadSteeringManifest(e)},t)}}function Al(r,e,t,i){r&&Object.keys(e).forEach(s=>{const n=r.filter(o=>o.groupId===s).map(o=>{const a=Ce({},o);return a.details=void 0,a.attrs=new me(a.attrs),a.url=a.attrs.URI=bl(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),a.groupId=a.attrs["GROUP-ID"]=e[s],a.attrs["PATHWAY-ID"]=i,a});r.push(...n)})}function bl(r,e,t,i){const{HOST:s,PARAMS:n,[t]:o}=i;let a;e&&(a=o==null?void 0:o[e],a&&(r=a));const l=new self.URL(r);return s&&!a&&(l.host=s),n&&Object.keys(n).sort().forEach(c=>{c&&l.searchParams.set(c,n[c])}),l.href}const xf=/^age:\s*[\d.]+\s*$/im;class xl{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=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Es,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,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(){const{config:e,context:t}=this;if(!e)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0;const n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!this.stats.aborted)return n(i,t.url)}).catch(o=>(i.open("GET",t.url,!0),n(i,t.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(o=>{this.callbacks.onError({code:i.status,text:o.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const s=this.context.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:o}=i.loadPolicy;if(s)for(const a in s)e.setRequestHeader(a,s[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&&W(n)?n:o,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const s=t.readyState,n=this.config;if(!i.aborted&&s>=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)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const o=t.status,a=t.responseType!=="text";if(o>=200&&o<300&&(a&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=a?t.response:t.responseText,c=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=c,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;const d=this.callbacks.onProgress;if(d&&d(i,e,l,t),!this.callbacks)return;const h={url:t.responseURL,data:l,code:o};this.callbacks.onSuccess(h,i,e,t)}else{const l=n.loadPolicy.errorRetry,c=i.retry;ks(l,c,!1,o)?this.retry(l):(C.error(`${o} while loading ${e.url}`),this.callbacks.onError({code:o,text:t.statusText},e,t,i))}}}loadtimeout(){var e;const t=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,i=this.stats.retry;if(ks(t,i,!0))this.retry(t);else{C.warn(`timeout while loading ${this.context.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Wr(e,i.retry),i.retry++,C.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){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&xf.test(this.loader.getAllResponseHeaders())){const 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}}function Tf(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Ef=/(\d+)-(\d+)\/(\d+)/;class Tl{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||wf,this.controller=new self.AbortController,this.stats=new Es}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const e=this.response;e!=null&&e.ok||(this.stats.aborted=!0,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){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const n=Sf(e,this.controller.signal),o=i.onProgress,a=e.responseType==="arraybuffer",l=a?"byteLength":"length",{maxTimeToFirstByteMs:c,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=c&&W(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,e,this.response)},t.timeout),self.fetch(this.request).then(h=>{this.response=this.loader=h;const u=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,e,this.response)},d-(u-s.loading.start)),!h.ok){const{status:f,statusText:g}=h;throw new Lf(g||"fetch, bad network response",f,h)}return s.loading.first=u,s.total=Cf(h.headers)||s.total,o&&W(t.highWaterMark)?this.loadProgressively(h,s,e,t.highWaterMark,o):a?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{const{response:u}=this;self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const f=h[l];f&&(s.loaded=s.total=f);const g={url:u.url,data:h,code:u.status};o&&!W(t.highWaterMark)&&o(s,e,h,u),i.onSuccess(g,s,e,u)}).catch(h=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const u=h&&h.code||0,f=h?h.message:null;i.onError({code:u,text:f},e,h?h.details:null,s)})}getCacheAge(){let e=null;if(this.response){const 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,s=0,n){const o=new Ja,a=e.body.getReader(),l=()=>a.read().then(c=>{if(c.done)return o.dataLength&&n(t,i,o.flush(),e),Promise.resolve(new ArrayBuffer(0));const d=c.value,h=d.length;return t.loaded+=h,h<s||o.dataLength?(o.push(d),o.dataLength>=s&&n(t,i,o.flush(),e)):n(t,i,d,e),l()}).catch(()=>Promise.reject());return l()}}function Sf(r,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Ce({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function If(r){const e=Ef.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Cf(r){const e=r.get("Content-Range");if(e){const i=If(e);if(W(i))return i}const t=r.get("Content-Length");if(t)return parseInt(t)}function wf(r,e){return new self.Request(r.url,e)}class Lf extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const Rf=/\s/,Df={newCue(r,e,t,i){const s=[];let n,o,a,l,c;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],a=!0,l=0,c="",!n.isEmpty()){var h;for(let p=0;p<n.chars.length;p++)Rf.test(n.chars[p].uchar)&&a?l++:(c+=n.chars[p].uchar,a=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=hl(c.trim()),g=vn(e,t,f);r!=null&&(h=r.cues)!=null&&h.getCueById(g)||(o=new d(e,t,f),o.id=g,o.line=u+1,o.align="left",o.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(o))}return r&&s.length&&(s.sort((u,f)=>u.line==="auto"||f.line==="auto"?0:u.line>8&&f.line>8?f.line-u.line:u.line-f.line),s.forEach(u=>fa(r,u))),s}},kf={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Pf=je(je({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:xl,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Fu,bufferController:Wu,capLevelController:Tn,errorController:wh,fpsController:mf,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Go,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,certLoadPolicy:{default:kf},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}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},Of()),{},{subtitleStreamController:Gu,subtitleTrackController:ju,timelineController:ff,audioStreamController:Bu,audioTrackController:Uu,emeController:yi,cmcdController:Ht,contentSteeringController:bf});function Of(){return{cueHandler:Df,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Mf(r,e){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"');const t=En(r),i=["manifest","level","frag"],s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{const o=`${n==="level"?"playlist":n}LoadPolicy`,a=e[o]===void 0,l=[];s.forEach(c=>{const d=`${n}Loading${c}`,h=e[d];if(h!==void 0&&a){l.push(d);const u=t[o].default;switch(e[o]={default:u},c){case"TimeOut":u.maxLoadTimeMs=h,u.maxTimeToFirstByteMs=h;break;case"MaxRetry":u.errorRetry.maxNumRetry=h,u.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":u.errorRetry.retryDelayMs=h,u.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=h,u.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&C.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${JSON.stringify(e[o])}`)}),je(je({},t),e)}function En(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(En):Object.keys(r).reduce((e,t)=>(e[t]=En(r[t]),e),{}):r}function Ff(r){const e=r.loader;e!==Tl&&e!==xl?(C.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):Tf()&&(r.loader=Tl,r.progressive=!0,r.enableSoftwareAES=!0,C.log("[config]: Progressive streaming enabled, using FetchLoader"))}class Dt{static get version(){return"1.4.6"}static isSupported(){return Kh()}static get Events(){return v}static get ErrorTypes(){return q}static get ErrorDetails(){return D}static get DefaultConfig(){return Dt.defaultConfig?Dt.defaultConfig:Pf}static set DefaultConfig(e){Dt.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new ln,this._autoLevelCapping=void 0,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.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,yd(e.debug||!1,"Hls instance");const t=this.config=Mf(Dt.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,t.progressive&&Ff(t);const{abrController:i,bufferController:s,capLevelController:n,errorController:o,fpsController:a}=t,l=new o(this),c=this.abrController=new i(this),d=this.bufferController=new s(this),h=this.capLevelController=new n(this),u=new a(this),f=new lh(this),g=new fh(this),p=t.contentSteeringController,m=p?new p(this):null,A=this.levelController=new Rh(this,m),T=new Dh(this),b=new Ph(this.config),y=this.streamController=new Ou(this,T,b);h.setStreamController(y),u.setStreamController(y);const x=[f,A,y];m&&x.splice(1,0,m),this.networkControllers=x;const E=[c,d,h,u,g,T];this.audioTrackController=this.createController(t.audioTrackController,x);const S=t.audioStreamController;S&&x.push(new S(this,T,b)),this.subtitleTrackController=this.createController(t.subtitleTrackController,x);const R=t.subtitleStreamController;R&&x.push(new R(this,T,b)),this.createController(t.timelineController,E),b.emeController=this.emeController=this.createController(t.emeController,E),this.cmcdController=this.createController(t.cmcdController,E),this.latencyController=this.createController(gh,E),this.coreComponents=E,x.push(l);const w=l.onErrorOut;typeof w=="function"&&this.on(v.ERROR,w,l)}createController(e,t){if(e){const 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,s){this._emitter.off(e,t,i,s)}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){C.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),this.trigger(v.ERROR,{type:q.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:!1,event:e,error:i})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){C.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;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){C.log("attachMedia"),this._media=e,this.trigger(v.MEDIA_ATTACHING,{media:e})}detachMedia(){C.log("detachMedia"),this.trigger(v.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,i=this.url,s=this.url=wr.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});C.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(v.MANIFEST_LOADING,{url:e})}startLoad(e=-1){C.log(`startLoad(${e})`),this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){C.log("stopLoad"),this.networkControllers.forEach(e=>{e.stopLoad()})}swapAudioCodec(){C.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){C.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e,t=0){this.levelController.removeLevel(e,t)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){C.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){C.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){C.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){C.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){C.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){const 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(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(C.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Vr.indexOf(e)>-1&&(this._maxHdcpLevel=e)}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let s=0;s<i;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let s;if(t===-1&&e&&e.length?s=e.length-1:s=t,i)for(let n=s;n--;){const o=e[n].attrs["HDCP-LEVEL"];if(o&&o<=i)return n}return s}get nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const 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}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}Dt.defaultConfig=void 0;var Nf=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function El(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Bf=$i;$i.flatten=$i,$i.unflatten=Cl;function Sl(r){return r&&r.constructor&&typeof r.constructor.isBuffer=="function"&&r.constructor.isBuffer(r)}function Il(r){return r}function $i(r,e){e=e||{};const t=e.delimiter||".",i=e.maxDepth,s=e.transformKey||Il,n={};function o(a,l,c){c=c||1,Object.keys(a).forEach(function(d){const h=a[d],u=e.safe&&Array.isArray(h),f=Object.prototype.toString.call(h),g=Sl(h),p=f==="[object Object]"||f==="[object Array]",m=l?l+t+s(d):s(d);if(!u&&!g&&p&&Object.keys(h).length&&(!e.maxDepth||c<i))return o(h,m,c+1);n[m]=h})}return o(r),n}function Cl(r,e){e=e||{};const t=e.delimiter||".",i=e.overwrite||!1,s=e.transformKey||Il,n={};if(Sl(r)||Object.prototype.toString.call(r)!=="[object Object]")return r;function a(d){const h=Number(d);return isNaN(h)||d.indexOf(".")!==-1||e.object?d:h}function l(d,h,u){return Object.keys(u).reduce(function(f,g){return f[d+t+g]=u[g],f},h)}function c(d){const h=Object.prototype.toString.call(d),u=h==="[object Array]",f=h==="[object Object]";if(d){if(u)return!d.length;if(f)return!Object.keys(d).length}else return!0}return r=Object.keys(r).reduce(function(d,h){const u=Object.prototype.toString.call(r[h]);return!(u==="[object Object]"||u==="[object Array]")||c(r[h])?(d[h]=r[h],d):l(h,d,$i(r[h],e))},{}),Object.keys(r).forEach(function(d){const h=d.split(t).map(s);let u=a(h.shift()),f=a(h[0]),g=n;for(;f!==void 0;){if(u==="__proto__")return;const p=Object.prototype.toString.call(g[u]),m=p==="[object Object]"||p==="[object Array]";if(!i&&!m&&typeof g[u]<"u")return;(i&&!m||!i&&g[u]==null)&&(g[u]=typeof f=="number"&&!e.object?[]:{}),g=g[u],h.length>0&&(u=a(h.shift()),f=a(h[0]))}g[u]=Cl(r[d],e)}),n}const Uf=El(Bf);/**
88
+ `),c=[],d=vu(e.baseTime,e.timescale);let h="00:00.000",u=0,f=0,g,p=!0;a.oncue=function(m){const A=t[i];let x=t.ccOffset;const b=(u-d)/9e4;A!=null&&A.new&&(f!==void 0?x=t.ccOffset=A.start:of(t,i,b)),b&&(x=b-t.presentationOffset);const y=m.endTime-m.startTime,T=$e((m.startTime+x-f)*9e4,s*9e4)/9e4;m.startTime=Math.max(T,0),m.endTime=Math.max(T+y,0);const E=m.text.trim();m.text=decodeURIComponent(encodeURIComponent(E)),m.id||(m.id=vn(m.startTime,m.endTime,E)),m.endTime>0&&c.push(m)},a.onparsingerror=function(m){g=m},a.onflush=function(){if(g){o(g);return}n(c)},l.forEach(m=>{if(p)if(pn(m,"X-TIMESTAMP-MAP=")){p=!1,m.slice(16).split(",").forEach(A=>{pn(A,"LOCAL:")?h=A.slice(6):pn(A,"MPEGTS:")&&(u=parseInt(A.slice(7)))});try{f=nf(h)/1e3}catch(A){g=A}return}else m===""&&(p=!1);a.parse(m+`
89
+ `)}),a.flush()}const yn="stpp.ttml.im1t",ul=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,fl=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,lf={left:"start",center:"center",right:"end",start:"start",end:"end"};function gl(r,e,t,i){const s=re(new Uint8Array(r),["mdat"]);if(s.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const n=s.map(a=>ft(a)),o=mu(e.baseTime,1,e.timescale);try{n.forEach(a=>t(cf(a,o)))}catch(a){i(a)}}function cf(r,e){const s=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},o=Object.keys(n).reduce((h,u)=>(h[u]=s.getAttribute(`ttp:${u}`)||n[u],h),{}),a=s.getAttribute("xml:space")!=="preserve",l=pl(An(s,"styling","style")),c=pl(An(s,"layout","region")),d=An(s,"body","[begin]");return[].map.call(d,h=>{const u=ml(h,a);if(!u||!h.hasAttribute("begin"))return null;const f=xn(h.getAttribute("begin"),o),g=xn(h.getAttribute("dur"),o);let p=xn(h.getAttribute("end"),o);if(f===null)throw vl(h);if(p===null){if(g===null)throw vl(h);p=f+g}const m=new fn(f-e,p-e,u);m.id=vn(m.startTime,m.endTime,m.text);const A=c[h.getAttribute("region")],x=l[h.getAttribute("style")],b=df(A,x,l),{textAlign:y}=b;if(y){const T=lf[y];T&&(m.lineAlign=T),m.align=y}return Ce(m,b),m}).filter(h=>h!==null)}function An(r,e,t){const i=r.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function pl(r){return r.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function ml(r,e){return[].slice.call(r.childNodes).reduce((t,i,s)=>{var n;return i.nodeName==="br"&&s?t+`
90
+ `:(n=i.childNodes)!=null&&n.length?ml(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function df(r,e,t){const i="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return o&&t.hasOwnProperty(o)&&(s=t[o]),n.reduce((a,l)=>{const c=bn(e,i,l)||bn(r,i,l)||bn(s,i,l);return c&&(a[l]=c),a},{})}function bn(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function vl(r){return new Error(`Could not parse ttml timestamp ${r}`)}function xn(r,e){if(!r)return null;let t=cl(r);return t===null&&(ul.test(r)?t=hf(r,e):fl.test(r)&&(t=uf(r,e))),t}function hf(r,e){const t=ul.exec(r),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 uf(r,e){const t=fl.exec(r),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}class ff{constructor(e){if(this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,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.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=yl(),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}},this.config.enableCEA708Captions){const t=new Gs(this,"textTrack1"),i=new Gs(this,"textTrack2"),s=new Gs(this,"textTrack3"),n=new Gs(this,"textTrack4");this.cea608Parser1=new ol(1,t,i),this.cea608Parser2=new ol(3,s,n)}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(){const{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.cea608Parser1=this.cea608Parser2=null}addCues(e,t,i,s,n){let o=!1;for(let a=n.length;a--;){const l=n[a],c=pf(l[0],l[1],t,i);if(c>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),o=!0,c/(i-t)>.5))return}if(o||n.push([t,i]),this.config.renderTextTracksNatively){const a=this.captionsTracks[e];this.Cues.newCue(a,t,i,s)}else{const a=this.Cues.newCue(null,t,i,s);this.hls.trigger(v.CUES_PARSED,{type:"captions",cues:a,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n}){const{unparsedVttFrags:o}=this;i==="main"&&(this.initPTS[t.cc]={baseTime:s,timescale:n}),o.length&&(this.unparsedVttFrags=[],o.forEach(a=>{this.onFragLoaded(v.FRAG_LOADED,a)}))}getExistingTrack(e){const{media:t}=this;if(t)for(let i=0;i<t.textTracks.length;i++){const s=t.textTracks[i];if(s[e])return s}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:s}=this,{label:n,languageCode:o}=t[e],a=this.getExistingTrack(e);if(a)i[e]=a,gi(i[e]),ua(i[e],s);else{const l=this.createTextTrack("captions",n,o);l&&(l[e]=!0,i[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i=t.label,s={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(v.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,t,i){const s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach(t=>{gi(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=yl(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=this.unparsedVttFrags||[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let i=0;i<t.length;i++)gi(t[i])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],s=i.some(n=>n.textCodec===yn);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(_a(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const o=this.media?this.media.textTracks:null;this.tracks.forEach((a,l)=>{let c;if(o&&l<o.length){let d=null;for(let h=0;h<o.length;h++)if(gf(o[h],a)){d=o[h];break}d&&(c=d)}if(c)gi(c);else{const d=this._captionsOrSubtitlesFromCharacteristics(a);c=this.createTextTrack(d,a.name,a.lang),c&&(c.mode="disabled")}c&&(c.groupId=a.groupId,this.textTracks.push(c))})}else if(this.tracks.length){const 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})}}}_captionsOrSubtitlesFromCharacteristics(e){if(e.attrs.CHARACTERISTICS){const t=/transcribes-spoken-dialog/gi.test(e.attrs.CHARACTERISTICS),i=/describes-music-and-sound/gi.test(e.attrs.CHARACTERISTICS);if(t&&i)return"captions"}return"subtitles"}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;const n=`textTrack${s[1]}`,o=this.captionsProperties[n];o&&(o.label=i.name,i.lang&&(o.languageCode=i.lang),o.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){const{cea608Parser1:i,cea608Parser2:s,lastSn:n,lastPartIndex:o}=this;if(!(!this.enabled||!(i&&s))&&t.frag.type===Z.MAIN){var a,l;const c=t.frag.sn,d=(a=t==null||(l=t.part)==null?void 0:l.index)!=null?a:-1;c===n+1||c===n&&d===o+1||(i.reset(),s.reset()),this.lastSn=c,this.lastPartIndex=d}}onFragLoaded(e,t){const{frag:i,payload:s}=t,{initPTS:n,unparsedVttFrags:o}=this;if(i.type===Z.SUBTITLE)if(s.byteLength){if(!n[i.cc]){o.push(t),n.length&&this.hls.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Missing initial subtitle PTS")});return}const a=i.decryptdata,l="stats"in t;if(a==null||!a.encrypted||l){const c=this.tracks[i.level],d=this.vttCCs;d[i.cc]||(d[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),c&&c.textCodec===yn?this._parseIMSC1(i,s):this._parseVTTs(i,s,d)}}else this.hls.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;gl(t,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),i.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{C.log(`Failed to parse IMSC1: ${s}`),i.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:s})})}_parseVTTs(e,t,i){var s;const n=this.hls,o=(s=e.initSegment)!=null&&s.data?$t(e.initSegment.data,new Uint8Array(t)):t;af(o,this.initPTS[e.cc],i,e.cc,e.start,a=>{this._appendCues(a,e.level),n.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},a=>{this._fallbackToIMSC1(e,t),C.log(`Failed to parse VTT cue: ${a}`),n.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:a})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||gl(t,this.initPTS[e.cc],()=>{i.textCodec=yn,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[t];if(!s||s.mode==="disabled")return;e.forEach(n=>fa(s,n))}else{const s=this.tracks[t];if(!s)return;const n=s.default?"default":"subtitles"+t;i.trigger(v.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){const{frag:i}=t;if(i.type===Z.SUBTITLE){if(!this.initPTS[i.cc]){this.unparsedVttFrags.push(t);return}this.onFragLoaded(v.FRAG_LOADED,t)}}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){const{cea608Parser1:i,cea608Parser2:s}=this;if(!this.enabled||!(i&&s))return;const{frag:n,samples:o}=t;if(!(n.type===Z.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let a=0;a<o.length;a++){const l=o[a].bytes;if(l){const c=this.extractCea608Data(l);i.addData(o[a].pts,c[0]),s.addData(o[a].pts,c[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:s,type:n}){const{media:o}=this;if(!(!o||o.currentTime<i)){if(!n||n==="video"){const{captionsTracks:a}=this;Object.keys(a).forEach(l=>Ur(a[l],t,i))}if(this.config.renderTextTracksNatively&&t===0&&s!==void 0){const{textTracks:a}=this;Object.keys(a).forEach(l=>Ur(a[l],t,s))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let s=2;for(let n=0;n<i;n++){const o=e[s++],a=127&e[s++],l=127&e[s++];if(a===0&&l===0)continue;if((4&o)!==0){const d=3&o;(d===0||d===1)&&(t[d].push(a),t[d].push(l))}}return t}}function gf(r,e){return!!r&&r.label===e.name&&!(r.textTrack1||r.textTrack2)}function pf(r,e,t,i){return Math.min(e,i)-Math.max(r,t)}function yl(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class Tn{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.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{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.BUFFER_CODECS,this.onBufferCodecs,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{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.BUFFER_CODECS,this.onBufferCodecs,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const 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}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){const e=this.hls.levels;if(e.length){const t=this.hls;t.autoLevelCapping=this.getMaxLevel(e.length-1),t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((s,n)=>this.isLevelAllowed(s)&&n<=e);return this.clientRect=null,Tn.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),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;const e=this.media,t={width:0,height:0};if(e){const 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 e}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;const s=(o,a)=>a?o.width!==a.width||o.height!==a.height:!0;let n=e.length-1;for(let o=0;o<e.length;o+=1){const a=e[o];if((a.width>=t||a.height>=i)&&s(a,e[o+1])){n=o;break}}return n}}class mf{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,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)}unregisterListeners(){this.hls.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const s=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){const s=performance.now();if(t){if(this.lastTime){const n=s-this.lastTime,o=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,l=1e3*o/n,c=this.hls;if(c.trigger(v.FPS_DROP,{currentDropped:o,currentDecoded:a,totalDroppedFrames:i}),l>0&&o>c.config.fpsDroppedMonitoringThreshold*a){let d=c.currentLevel;C.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=d)&&(d=d-1,c.trigger(v.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:c.currentLevel}),c.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}const js="[eme]";class Ai{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=Ai.CDMCleanupPromise?[Ai.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=C.debug.bind(C,js),this.log=C.log.bind(C,js),this.warn=C.warn.bind(C,js),this.error=C.error.bind(C,js),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=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)}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)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,s=t[e];if(s)return s.licenseUrl;if(e===ve.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(o,a,l)=>!!o&&l.indexOf(o)===a,s=t.map(o=>o.audioCodec).filter(i),n=t.map(o=>o.videoCodec).filter(i);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((o,a)=>{const l=c=>{const d=c.shift();this.getMediaKeysPromise(d,s,n).then(h=>o({keySystem:d,mediaKeys:h})).catch(h=>{c.length?l(c):h instanceof et?a(h):a(new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Go===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return i(e,t)}getMediaKeysPromise(e,t,i){const s=Rd(e,t,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[e];let o=n==null?void 0:n.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(s)}`),o=this.requestMediaKeySystemAccess(e,s);const a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const c=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),a.mediaKeys=l.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),c.then(h=>h?this.setMediaKeysServerCertificate(d,e,h):d))),a.mediaKeys.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),a.mediaKeys})}return o.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${gt.hexDump(e.keyId||[])}`);const s=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),s=this.getKeyIdString(t),n="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,n,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return gt.hexDump(e.keyId)}updateKeySession(e,t){var i;const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyID ${gt.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])}
91
+ } (data length: ${t&&t.byteLength})`),s.update(t)}selectKeySystemFormat(e){const 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){return new Promise((t,i)=>{const s=kr(this.config),n=e.map(Bo).filter(o=>!!o&&s.indexOf(o)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:o})=>{const a=Ho(o);a?t(a):i(new Error(`Unable to find format for key-system "${o}"`))}).catch(i)})}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),s=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${s}`);let n=this.keyIdToKeySessionPromise[i];return n||(n=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:o,mediaKeys:a})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${s}`),this.attemptSetMediaKeys(o,a).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:o,mediaKeys:a,decryptdata:t}),c="cenc";return this.generateRequestWithPreferredKeySession(l,c,t.pssh,"playlist-key")}))),n.catch(o=>this.handleError(o))),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof et?this.hls.trigger(v.ERROR,e.data):this.hls.trigger(v.ERROR,{type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const s=Bo(e.keyFormat),n=s?[s]:kr(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=kr(this.config)),e.length===0)throw new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:i}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),i===null)return;let s,n;if(t==="sinf"&&this.config.drmSystems[ve.FAIRPLAY]){const d=De(new Uint8Array(i));try{const h=Dr(JSON.parse(d).sinf),u=qo(new Uint8Array(h));if(!u)return;s=u.subarray(8,24),n=ve.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{const d=$d(i);if(d===null)return;d.version===0&&d.systemId===Uo.WIDEVINE&&d.data&&(s=d.data.subarray(8,24)),n=Ld(d.systemId)}if(!n||!s)return;const o=gt.hexDump(s),{keyIdToKeySessionPromise:a,mediaKeySessions:l}=this;let c=a[o];for(let d=0;d<l.length;d++){const h=l[d],u=h.decryptdata;if(u.pssh||!u.keyId)continue;const f=gt.hexDump(u.keyId);if(o===f||u.uri.replace(/-/g,"").indexOf(o)!==-1){c=a[f],delete a[f],u.pssh=new Uint8Array(i),u.keyId=s,c=a[o]=c.then(()=>this.generateRequestWithPreferredKeySession(h,t,i,"encrypted-event-key-match"));break}}c||(c=a[o]=this.getKeySystemSelectionPromise([n]).then(({keySystem:d,mediaKeys:h})=>{var u;this.throwIfDestroyed();const f=new qi("ISO-23001-7",o,(u=Ho(d))!=null?u:"");return f.pssh=new Uint8Array(i),f.keyId=s,this.attemptSetMediaKeys(d,h).then(()=>{this.throwIfDestroyed();const g=this.createMediaKeySessionContext({decryptdata:f,keySystem:d,mediaKeys:h});return this.generateRequestWithPreferredKeySession(g,t,i,"encrypted-event-no-match")})})),c.catch(d=>this.handleError(d))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const s=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,i,s){var n,o;const a=(n=this.config.drmSystems)==null||(o=n[e.keySystem])==null?void 0:o.generateRequest;if(a)try{const u=a.call(this.hls,t,i,e);if(!u)throw new Error("Invalid response from configured generateRequest filter");t=u.initDataType,i=e.decryptdata.pssh=u.initData?new Uint8Array(u.initData):null}catch(u){var l;if(this.warn(u.message),(l=this.hls)!=null&&l.config.debug)throw u}if(i===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);const c=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${s}": ${c} (init data type: ${t} length: ${i?i.byteLength:null})`);const d=new ln;e.mediaKeysSession.onmessage=u=>{const f=e.mediaKeysSession;if(!f){d.emit("error",new Error("invalid state"));return}const{messageType:g,message:p}=u;this.log(`"${g}" message event for session "${f.sessionId}" message size: ${p.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,p).catch(m=>{this.handleError(m),d.emit("error",m)}):g==="license-release"?e.keySystem===ve.FAIRPLAY&&(this.updateKeySession(e,No("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${g}"`)},e.mediaKeysSession.onkeystatuseschange=u=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const g=e.keyStatus;d.emit("keyStatus",g),g==="expired"&&(this.warn(`${e.keySystem} expired for key ${c}`),this.renewKeySession(e))};const h=new Promise((u,f)=>{d.on("error",f),d.on("keyStatus",g=>{g.startsWith("usable")?u():g==="output-restricted"?f(new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):g==="internal-error"?f(new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${g}"`)):g==="expired"?f(new Error("key expired while generating request")):this.warn(`unhandled key status change "${g}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var u;this.log(`Request generated for key-session "${(u=e.mediaKeysSession)==null?void 0:u.sessionId}" keyId: ${c}`)}).catch(u=>{throw new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_SESSION,error:u,fatal:!1},`Error generating key-session request: ${u}`)}).then(()=>h).catch(u=>{throw d.removeAllListeners(),this.removeSession(e),u}).then(()=>(d.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${gt.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${gt.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,i=t.loader,s=new i(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching serverCertificate for "${e}"`),new Promise((o,a)=>{const l={responseType:"arraybuffer",url:n},c=t.certLoadPolicy.default,d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,f,g,p)=>{o(u.data)},onError:(u,f,g,p)=>{a(new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:je({url:l.url,data:void 0},u)},`"${e}" certificate request failed (${n}). Status: ${u.code} (${u.text})`))},onTimeout:(u,f,g)=>{a(new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(u,f,g)=>{a(new Error("aborted"))}};s.load(l,d,h)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((s,n)=>{e.setServerCertificate(i).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),s(e)}).catch(o=>{n(new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:o,fatal:!0},o.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(s=>{throw new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:s,fatal:!0},s.message)}))}setupLicenseXHR(e,t,i,s){const 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,s)}).catch(o=>{if(!i.decryptdata)throw o;return e.open("POST",t,!0),n.call(this.hls,e,t,i,s)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||s})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((s,n)=>{const o=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${o}`);const 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}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,a,o,e)}catch(d){this.error(d)}s(l)}else{const l=i.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||a.status>=400&&a.status<500)n(new et({type:q.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,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{const d=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${d} attempts left`),this.requestLicense(e,t).then(s,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,o,e,t).then(({xhr:l,licenseChallenge:c})=>{l.send(c)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},qi.clearKeyUriToKeyIdMap();const i=t.length;Ai.CDMCleanupPromise=Promise.all(t.map(s=>this.removeSession(s)).concat(e==null?void 0:e.setMediaKeys(null).catch(s=>{this.log(`Could not clear media keys: ${s}. media.src: ${e==null?void 0:e.src}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(s=>{this.log(`Could not close sessions and clear media keys: ${s}. media.src: ${e==null?void 0:e.src}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((s,n)=>(s.indexOf(n.keyFormat)===-1&&s.push(n.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),t.onmessage=null,t.onkeystatuseschange=null,i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const s=this.mediaKeySessions.indexOf(e);return s>-1&&this.mediaKeySessions.splice(s,1),t.remove().catch(n=>{this.log(`Could not remove session: ${n}`)}).then(()=>t.close()).catch(n=>{this.log(`Could not close session: ${n}`)})}}}Ai.CDMCleanupPromise=void 0;class et 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}}const vf=1;var Ke={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"};const yf="h";class Ht{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=s=>{try{this.apply(s,{ot:Ke.MANIFEST,su:!this.initialized})}catch(n){C.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=s=>{try{const n=s.frag,o=this.hls.levels[n.level],a=this.getObjectType(n),l={d:n.duration*1e3,ot:a};(a===Ke.VIDEO||a===Ke.AUDIO||a==Ke.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(a)/1e3,l.bl=this.getBufferLength(a)),this.apply(s,l)}catch(n){C.warn("Could not generate segment CMCD data.",n)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||Ht.uuid(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.registerListeners())}registerListeners(){const 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(){const 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}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,s;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(s=t.tracks.video)==null?void 0:s.buffer}createData(){var e;return{v:vf,sf:yf,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Ce(t,this.createData());const i=t.ot===Ke.INIT||t.ot===Ke.VIDEO||t.ot===Ke.MUXED;if(this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering),this.useHeaders){const s=Ht.toHeaders(t);if(!Object.keys(s).length)return;e.headers||(e.headers={}),Ce(e.headers,s)}else{const s=Ht.toQuery(t);if(!s)return;e.url=Ht.appendQueryToUri(e.url,s)}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Ke.TIMED_TEXT;if(e.sn==="initSegment")return Ke.INIT;if(t==="audio")return Ke.AUDIO;if(t==="main")return this.hls.audioTracks.length?Ke.VIDEO:Ke.MUXED}getTopBandwidth(e){let t=0,i;const s=this.hls;if(e===Ke.AUDIO)i=s.audioTracks;else{const n=s.maxAutoLevel,o=n>-1?n+1:s.levels.length;i=s.levels.slice(0,o)}for(const n of i)n.bitrate>t&&(t=n.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.hls.media,i=e===Ke.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:fe.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{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(){const{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)}}}static uuid(){const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}static serialize(e){const t=[],i=c=>!Number.isNaN(c)&&c!=null&&c!==""&&c!==!1,s=c=>Math.round(c),n=c=>s(c/100)*100,a={br:s,d:s,bl:n,dl:n,mtp:n,nor:c=>encodeURIComponent(c),rtp:n,tb:s},l=Object.keys(e||{}).sort();for(const c of l){let d=e[c];if(!i(d)||c==="v"&&d===1||c=="pr"&&d===1)continue;const h=a[c];h&&(d=h(d));const u=typeof d;let f;c==="ot"||c==="sf"||c==="st"?f=`${c}=${d}`:u==="boolean"?f=c:u==="number"?f=`${c}=${d}`:f=`${c}=${JSON.stringify(d)}`,t.push(f)}return t.join(",")}static toHeaders(e){const t=Object.keys(e),i={},s=["Object","Request","Session","Status"],n=[{},{},{},{}],o={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const a of t){const l=o[a]!=null?o[a]:1;n[l][a]=e[a]}for(let a=0;a<n.length;a++){const l=Ht.serialize(n[a]);l&&(i[`CMCD-${s[a]}`]=l)}return i}static toQuery(e){return`CMCD=${encodeURIComponent(Ht.serialize(e))}`}static appendQueryToUri(e,t){if(!t)return e;const i=e.includes("?")?"&":"?";return`${e}${i}${t}`}}const Af=3e5;class bf{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=C.log.bind(C,"[content-steering]:"),this.registerListeners()}registerListeners(){const 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(){const 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))}startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){const e=Math.max(this.timeToLoad*1e3-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,e)}else this.loadSteeringManifest(this.uri)}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),self.clearTimeout(this.reloadTimer)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{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){const{errorAction:i}=t;if((i==null?void 0:i.action)===Ye.SendAlternateToPenaltyBox&&i.flags===ct.MoveAllAlternatesMatchingHost){let s=this.pathwayPriority;const n=this.pathwayId;this.penalizedPathways[n]||(this.penalizedPathways[n]=performance.now()),!s&&this.levels&&(s=this.levels.reduce((o,a)=>(o.indexOf(a.pathwayId)===-1&&o.push(a.pathwayId),o),[])),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==n)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const 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):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(n=>{s-i[n]>Af&&delete i[n]});for(let n=0;n<e.length;n++){const o=e[n];if(i[o])continue;if(o===this.pathwayId)return;const 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,this.hls.trigger(v.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[a];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=a);break}}}clonePathways(e){const t=this.levels;if(!t)return;const i={},s={};e.forEach(n=>{const{ID:o,"BASE-ID":a,"URI-REPLACEMENT":l}=n;if(t.some(d=>d.pathwayId===o))return;const c=this.getLevelsForPathway(a).map(d=>{const h=Ce({},d);h.details=void 0,h.url=bl(d.uri,d.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l);const u=new me(d.attrs);u["PATHWAY-ID"]=o;const f=u.AUDIO&&`${u.AUDIO}_clone_${o}`,g=u.SUBTITLES&&`${u.SUBTITLES}_clone_${o}`;f&&(i[u.AUDIO]=f,u.AUDIO=f),g&&(s[u.SUBTITLES]=g,u.SUBTITLES=g),h.attrs=u;const p=new Ji(h);return Ps(p,"audio",f),Ps(p,"text",g),p});t.push(...c),Al(this.audioTracks,i,l,o),Al(this.subtitleTracks,s,l,o)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let s;try{s=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){const d=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+d)}const n={responseType:"json",url:s.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},c={onSuccess:(d,h,u,f)=>{this.log(`Loaded steering manifest: "${s}"`);const g=d.data;if(g.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":m,"PATHWAY-PRIORITY":A}=g;if(p)try{this.uri=new self.URL(p,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||u.url),m&&this.clonePathways(m),A&&this.updatePathwayPriority(A)},onError:(d,h,u,f)=>{if(this.log(`Error loading steering manifest: ${d.code} ${d.text} (${h.url})`),this.stopLoad(),d.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let g=this.timeToLoad*1e3;if(d.code===429){const p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){const m=p.getResponseHeader("Retry-After");m&&(g=parseFloat(m)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},onTimeout:(d,h,u)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout(()=>{this.loadSteeringManifest(e)},t)}}function Al(r,e,t,i){r&&Object.keys(e).forEach(s=>{const n=r.filter(o=>o.groupId===s).map(o=>{const a=Ce({},o);return a.details=void 0,a.attrs=new me(a.attrs),a.url=a.attrs.URI=bl(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),a.groupId=a.attrs["GROUP-ID"]=e[s],a.attrs["PATHWAY-ID"]=i,a});r.push(...n)})}function bl(r,e,t,i){const{HOST:s,PARAMS:n,[t]:o}=i;let a;e&&(a=o==null?void 0:o[e],a&&(r=a));const l=new self.URL(r);return s&&!a&&(l.host=s),n&&Object.keys(n).sort().forEach(c=>{c&&l.searchParams.set(c,n[c])}),l.href}const xf=/^age:\s*[\d.]+\s*$/im;class xl{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=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Es,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,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(){const{config:e,context:t}=this;if(!e)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0;const n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!this.stats.aborted)return n(i,t.url)}).catch(o=>(i.open("GET",t.url,!0),n(i,t.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(o=>{this.callbacks.onError({code:i.status,text:o.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const s=this.context.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:o}=i.loadPolicy;if(s)for(const a in s)e.setRequestHeader(a,s[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&&W(n)?n:o,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const s=t.readyState,n=this.config;if(!i.aborted&&s>=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)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const o=t.status,a=t.responseType!=="text";if(o>=200&&o<300&&(a&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=a?t.response:t.responseText,c=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=c,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;const d=this.callbacks.onProgress;if(d&&d(i,e,l,t),!this.callbacks)return;const h={url:t.responseURL,data:l,code:o};this.callbacks.onSuccess(h,i,e,t)}else{const l=n.loadPolicy.errorRetry,c=i.retry;ks(l,c,!1,o)?this.retry(l):(C.error(`${o} while loading ${e.url}`),this.callbacks.onError({code:o,text:t.statusText},e,t,i))}}}loadtimeout(){var e;const t=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,i=this.stats.retry;if(ks(t,i,!0))this.retry(t);else{C.warn(`timeout while loading ${this.context.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Wr(e,i.retry),i.retry++,C.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){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&xf.test(this.loader.getAllResponseHeaders())){const 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}}function Tf(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Ef=/(\d+)-(\d+)\/(\d+)/;class Tl{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||wf,this.controller=new self.AbortController,this.stats=new Es}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const e=this.response;e!=null&&e.ok||(this.stats.aborted=!0,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){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const n=Sf(e,this.controller.signal),o=i.onProgress,a=e.responseType==="arraybuffer",l=a?"byteLength":"length",{maxTimeToFirstByteMs:c,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=c&&W(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,e,this.response)},t.timeout),self.fetch(this.request).then(h=>{this.response=this.loader=h;const u=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,e,this.response)},d-(u-s.loading.start)),!h.ok){const{status:f,statusText:g}=h;throw new Lf(g||"fetch, bad network response",f,h)}return s.loading.first=u,s.total=Cf(h.headers)||s.total,o&&W(t.highWaterMark)?this.loadProgressively(h,s,e,t.highWaterMark,o):a?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{const{response:u}=this;self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const f=h[l];f&&(s.loaded=s.total=f);const g={url:u.url,data:h,code:u.status};o&&!W(t.highWaterMark)&&o(s,e,h,u),i.onSuccess(g,s,e,u)}).catch(h=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const u=h&&h.code||0,f=h?h.message:null;i.onError({code:u,text:f},e,h?h.details:null,s)})}getCacheAge(){let e=null;if(this.response){const 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,s=0,n){const o=new Ja,a=e.body.getReader(),l=()=>a.read().then(c=>{if(c.done)return o.dataLength&&n(t,i,o.flush(),e),Promise.resolve(new ArrayBuffer(0));const d=c.value,h=d.length;return t.loaded+=h,h<s||o.dataLength?(o.push(d),o.dataLength>=s&&n(t,i,o.flush(),e)):n(t,i,d,e),l()}).catch(()=>Promise.reject());return l()}}function Sf(r,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Ce({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function If(r){const e=Ef.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Cf(r){const e=r.get("Content-Range");if(e){const i=If(e);if(W(i))return i}const t=r.get("Content-Length");if(t)return parseInt(t)}function wf(r,e){return new self.Request(r.url,e)}class Lf extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const Rf=/\s/,Df={newCue(r,e,t,i){const s=[];let n,o,a,l,c;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],a=!0,l=0,c="",!n.isEmpty()){var h;for(let p=0;p<n.chars.length;p++)Rf.test(n.chars[p].uchar)&&a?l++:(c+=n.chars[p].uchar,a=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=hl(c.trim()),g=vn(e,t,f);r!=null&&(h=r.cues)!=null&&h.getCueById(g)||(o=new d(e,t,f),o.id=g,o.line=u+1,o.align="left",o.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(o))}return r&&s.length&&(s.sort((u,f)=>u.line==="auto"||f.line==="auto"?0:u.line>8&&f.line>8?f.line-u.line:u.line-f.line),s.forEach(u=>fa(r,u))),s}},kf={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Pf=je(je({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:xl,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Fu,bufferController:Wu,capLevelController:Tn,errorController:wh,fpsController:mf,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Go,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,certLoadPolicy:{default:kf},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}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},Of()),{},{subtitleStreamController:Gu,subtitleTrackController:ju,timelineController:ff,audioStreamController:Bu,audioTrackController:Uu,emeController:Ai,cmcdController:Ht,contentSteeringController:bf});function Of(){return{cueHandler:Df,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Mf(r,e){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"');const t=En(r),i=["manifest","level","frag"],s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{const o=`${n==="level"?"playlist":n}LoadPolicy`,a=e[o]===void 0,l=[];s.forEach(c=>{const d=`${n}Loading${c}`,h=e[d];if(h!==void 0&&a){l.push(d);const u=t[o].default;switch(e[o]={default:u},c){case"TimeOut":u.maxLoadTimeMs=h,u.maxTimeToFirstByteMs=h;break;case"MaxRetry":u.errorRetry.maxNumRetry=h,u.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":u.errorRetry.retryDelayMs=h,u.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=h,u.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&C.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${JSON.stringify(e[o])}`)}),je(je({},t),e)}function En(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(En):Object.keys(r).reduce((e,t)=>(e[t]=En(r[t]),e),{}):r}function Ff(r){const e=r.loader;e!==Tl&&e!==xl?(C.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):Tf()&&(r.loader=Tl,r.progressive=!0,r.enableSoftwareAES=!0,C.log("[config]: Progressive streaming enabled, using FetchLoader"))}class Dt{static get version(){return"1.4.6"}static isSupported(){return Kh()}static get Events(){return v}static get ErrorTypes(){return q}static get ErrorDetails(){return D}static get DefaultConfig(){return Dt.defaultConfig?Dt.defaultConfig:Pf}static set DefaultConfig(e){Dt.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new ln,this._autoLevelCapping=void 0,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.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,yd(e.debug||!1,"Hls instance");const t=this.config=Mf(Dt.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,t.progressive&&Ff(t);const{abrController:i,bufferController:s,capLevelController:n,errorController:o,fpsController:a}=t,l=new o(this),c=this.abrController=new i(this),d=this.bufferController=new s(this),h=this.capLevelController=new n(this),u=new a(this),f=new lh(this),g=new fh(this),p=t.contentSteeringController,m=p?new p(this):null,A=this.levelController=new Rh(this,m),x=new Dh(this),b=new Ph(this.config),y=this.streamController=new Ou(this,x,b);h.setStreamController(y),u.setStreamController(y);const T=[f,A,y];m&&T.splice(1,0,m),this.networkControllers=T;const E=[c,d,h,u,g,x];this.audioTrackController=this.createController(t.audioTrackController,T);const S=t.audioStreamController;S&&T.push(new S(this,x,b)),this.subtitleTrackController=this.createController(t.subtitleTrackController,T);const R=t.subtitleStreamController;R&&T.push(new R(this,x,b)),this.createController(t.timelineController,E),b.emeController=this.emeController=this.createController(t.emeController,E),this.cmcdController=this.createController(t.cmcdController,E),this.latencyController=this.createController(gh,E),this.coreComponents=E,T.push(l);const w=l.onErrorOut;typeof w=="function"&&this.on(v.ERROR,w,l)}createController(e,t){if(e){const 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,s){this._emitter.off(e,t,i,s)}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){C.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),this.trigger(v.ERROR,{type:q.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:!1,event:e,error:i})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){C.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;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){C.log("attachMedia"),this._media=e,this.trigger(v.MEDIA_ATTACHING,{media:e})}detachMedia(){C.log("detachMedia"),this.trigger(v.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,i=this.url,s=this.url=wr.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});C.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(v.MANIFEST_LOADING,{url:e})}startLoad(e=-1){C.log(`startLoad(${e})`),this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){C.log("stopLoad"),this.networkControllers.forEach(e=>{e.stopLoad()})}swapAudioCodec(){C.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){C.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e,t=0){this.levelController.removeLevel(e,t)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){C.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){C.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){C.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){C.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){C.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){const 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(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(C.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Vr.indexOf(e)>-1&&(this._maxHdcpLevel=e)}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let s=0;s<i;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let s;if(t===-1&&e&&e.length?s=e.length-1:s=t,i)for(let n=s;n--;){const o=e[n].attrs["HDCP-LEVEL"];if(o&&o<=i)return n}return s}get nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const 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}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}Dt.defaultConfig=void 0;var Nf=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function El(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Bf=$i;$i.flatten=$i,$i.unflatten=Cl;function Sl(r){return r&&r.constructor&&typeof r.constructor.isBuffer=="function"&&r.constructor.isBuffer(r)}function Il(r){return r}function $i(r,e){e=e||{};const t=e.delimiter||".",i=e.maxDepth,s=e.transformKey||Il,n={};function o(a,l,c){c=c||1,Object.keys(a).forEach(function(d){const h=a[d],u=e.safe&&Array.isArray(h),f=Object.prototype.toString.call(h),g=Sl(h),p=f==="[object Object]"||f==="[object Array]",m=l?l+t+s(d):s(d);if(!u&&!g&&p&&Object.keys(h).length&&(!e.maxDepth||c<i))return o(h,m,c+1);n[m]=h})}return o(r),n}function Cl(r,e){e=e||{};const t=e.delimiter||".",i=e.overwrite||!1,s=e.transformKey||Il,n={};if(Sl(r)||Object.prototype.toString.call(r)!=="[object Object]")return r;function a(d){const h=Number(d);return isNaN(h)||d.indexOf(".")!==-1||e.object?d:h}function l(d,h,u){return Object.keys(u).reduce(function(f,g){return f[d+t+g]=u[g],f},h)}function c(d){const h=Object.prototype.toString.call(d),u=h==="[object Array]",f=h==="[object Object]";if(d){if(u)return!d.length;if(f)return!Object.keys(d).length}else return!0}return r=Object.keys(r).reduce(function(d,h){const u=Object.prototype.toString.call(r[h]);return!(u==="[object Object]"||u==="[object Array]")||c(r[h])?(d[h]=r[h],d):l(h,d,$i(r[h],e))},{}),Object.keys(r).forEach(function(d){const h=d.split(t).map(s);let u=a(h.shift()),f=a(h[0]),g=n;for(;f!==void 0;){if(u==="__proto__")return;const p=Object.prototype.toString.call(g[u]),m=p==="[object Object]"||p==="[object Array]";if(!i&&!m&&typeof g[u]<"u")return;(i&&!m||!i&&g[u]==null)&&(g[u]=typeof f=="number"&&!e.object?[]:{}),g=g[u],h.length>0&&(u=a(h.shift()),f=a(h[0]))}g[u]=Cl(r[d],e)}),n}const Uf=El(Bf);/**
92
92
  * @license
93
93
  * Copyright 2017 Google LLC
94
94
  * SPDX-License-Identifier: BSD-3-Clause
95
- */const wl=(r,e,t)=>{const i=new Map;for(let s=e;s<=t;s++)i.set(r[s],s);return i},Ll=ui(class extends Wi{constructor(r){if(super(r),r.type!==hi.CHILD)throw Error("repeat() can only be used in text expressions")}dt(r,e,t){let i;t===void 0?t=e:e!==void 0&&(i=e);const s=[],n=[];let o=0;for(const a of r)s[o]=i?i(a,o):o,n[o]=t(a,o),o++;return{values:n,keys:s}}render(r,e,t){return this.dt(r,e,t).values}update(r,[e,t,i]){var s;const n=od(r),{values:o,keys:a}=this.dt(e,t,i);if(!Array.isArray(n))return this.ht=a,o;const l=(s=this.ht)!==null&&s!==void 0?s:this.ht=[],c=[];let d,h,u=0,f=n.length-1,g=0,p=o.length-1;for(;u<=f&&g<=p;)if(n[u]===null)u++;else if(n[f]===null)f--;else if(l[u]===a[g])c[g]=Jt(n[u],o[g]),u++,g++;else if(l[f]===a[p])c[p]=Jt(n[f],o[p]),f--,p--;else if(l[u]===a[p])c[p]=Jt(n[u],o[p]),Yi(r,c[p+1],n[u]),u++,p--;else if(l[f]===a[g])c[g]=Jt(n[f],o[g]),Yi(r,n[u],n[f]),f--,g++;else if(d===void 0&&(d=wl(a,g,p),h=wl(l,u,f)),d.has(l[u]))if(d.has(l[f])){const m=h.get(a[g]),A=m!==void 0?n[m]:null;if(A===null){const T=Yi(r,n[u]);Jt(T,o[g]),c[g]=T}else c[g]=Jt(A,o[g]),Yi(r,n[u],A),n[m]=null;g++}else Sr(n[f]),f--;else Sr(n[u]),u++;for(;g<=p;){const m=Yi(r,c[p+1]);Jt(m,o[g]),c[g++]=m}for(;u<=f;){const m=n[u++];m!==null&&Sr(m)}return this.ht=a,nd(r,c),ot}});var Xe="top",tt="bottom",it="right",qe="left",Sn="auto",es=[Xe,tt,it,qe],Ai="start",ts="end",Hf="clippingParents",Rl="viewport",is="popper",Gf="reference",Dl=es.reduce(function(r,e){return r.concat([e+"-"+Ai,e+"-"+ts])},[]),kl=[].concat(es,[Sn]).reduce(function(r,e){return r.concat([e,e+"-"+Ai,e+"-"+ts])},[]),Vf="beforeRead",jf="read",zf="afterRead",Wf="beforeMain",Yf="main",Kf="afterMain",Xf="beforeWrite",qf="write",Zf="afterWrite",Jf=[Vf,jf,zf,Wf,Yf,Kf,Xf,qf,Zf];function mt(r){return r?(r.nodeName||"").toLowerCase():null}function Qe(r){if(r==null)return window;if(r.toString()!=="[object Window]"){var e=r.ownerDocument;return e&&e.defaultView||window}return r}function ti(r){var e=Qe(r).Element;return r instanceof e||r instanceof Element}function st(r){var e=Qe(r).HTMLElement;return r instanceof e||r instanceof HTMLElement}function In(r){if(typeof ShadowRoot>"u")return!1;var e=Qe(r).ShadowRoot;return r instanceof e||r instanceof ShadowRoot}function Qf(r){var e=r.state;Object.keys(e.elements).forEach(function(t){var i=e.styles[t]||{},s=e.attributes[t]||{},n=e.elements[t];!st(n)||!mt(n)||(Object.assign(n.style,i),Object.keys(s).forEach(function(o){var a=s[o];a===!1?n.removeAttribute(o):n.setAttribute(o,a===!0?"":a)}))})}function _f(r){var e=r.state,t={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(e.elements.popper.style,t.popper),e.styles=t,e.elements.arrow&&Object.assign(e.elements.arrow.style,t.arrow),function(){Object.keys(e.elements).forEach(function(i){var s=e.elements[i],n=e.attributes[i]||{},o=Object.keys(e.styles.hasOwnProperty(i)?e.styles[i]:t[i]),a=o.reduce(function(l,c){return l[c]="",l},{});!st(s)||!mt(s)||(Object.assign(s.style,a),Object.keys(n).forEach(function(l){s.removeAttribute(l)}))})}}const Pl={name:"applyStyles",enabled:!0,phase:"write",fn:Qf,effect:_f,requires:["computeStyles"]};function vt(r){return r.split("-")[0]}var ii=Math.max,zs=Math.min,bi=Math.round;function Cn(){var r=navigator.userAgentData;return r!=null&&r.brands&&Array.isArray(r.brands)?r.brands.map(function(e){return e.brand+"/"+e.version}).join(" "):navigator.userAgent}function Ol(){return!/^((?!chrome|android).)*safari/i.test(Cn())}function xi(r,e,t){e===void 0&&(e=!1),t===void 0&&(t=!1);var i=r.getBoundingClientRect(),s=1,n=1;e&&st(r)&&(s=r.offsetWidth>0&&bi(i.width)/r.offsetWidth||1,n=r.offsetHeight>0&&bi(i.height)/r.offsetHeight||1);var o=ti(r)?Qe(r):window,a=o.visualViewport,l=!Ol()&&t,c=(i.left+(l&&a?a.offsetLeft:0))/s,d=(i.top+(l&&a?a.offsetTop:0))/n,h=i.width/s,u=i.height/n;return{width:h,height:u,top:d,right:c+h,bottom:d+u,left:c,x:c,y:d}}function wn(r){var e=xi(r),t=r.offsetWidth,i=r.offsetHeight;return Math.abs(e.width-t)<=1&&(t=e.width),Math.abs(e.height-i)<=1&&(i=e.height),{x:r.offsetLeft,y:r.offsetTop,width:t,height:i}}function Ml(r,e){var t=e.getRootNode&&e.getRootNode();if(r.contains(e))return!0;if(t&&In(t)){var i=e;do{if(i&&r.isSameNode(i))return!0;i=i.parentNode||i.host}while(i)}return!1}function kt(r){return Qe(r).getComputedStyle(r)}function $f(r){return["table","td","th"].indexOf(mt(r))>=0}function Gt(r){return((ti(r)?r.ownerDocument:r.document)||window.document).documentElement}function Ws(r){return mt(r)==="html"?r:r.assignedSlot||r.parentNode||(In(r)?r.host:null)||Gt(r)}function Fl(r){return!st(r)||kt(r).position==="fixed"?null:r.offsetParent}function e0(r){var e=/firefox/i.test(Cn()),t=/Trident/i.test(Cn());if(t&&st(r)){var i=kt(r);if(i.position==="fixed")return null}var s=Ws(r);for(In(s)&&(s=s.host);st(s)&&["html","body"].indexOf(mt(s))<0;){var n=kt(s);if(n.transform!=="none"||n.perspective!=="none"||n.contain==="paint"||["transform","perspective"].indexOf(n.willChange)!==-1||e&&n.willChange==="filter"||e&&n.filter&&n.filter!=="none")return s;s=s.parentNode}return null}function ss(r){for(var e=Qe(r),t=Fl(r);t&&$f(t)&&kt(t).position==="static";)t=Fl(t);return t&&(mt(t)==="html"||mt(t)==="body"&&kt(t).position==="static")?e:t||e0(r)||e}function Ln(r){return["top","bottom"].indexOf(r)>=0?"x":"y"}function rs(r,e,t){return ii(r,zs(e,t))}function t0(r,e,t){var i=rs(r,e,t);return i>t?t:i}function Nl(){return{top:0,right:0,bottom:0,left:0}}function Bl(r){return Object.assign({},Nl(),r)}function Ul(r,e){return e.reduce(function(t,i){return t[i]=r,t},{})}var i0=function(e,t){return e=typeof e=="function"?e(Object.assign({},t.rects,{placement:t.placement})):e,Bl(typeof e!="number"?e:Ul(e,es))};function s0(r){var e,t=r.state,i=r.name,s=r.options,n=t.elements.arrow,o=t.modifiersData.popperOffsets,a=vt(t.placement),l=Ln(a),c=[qe,it].indexOf(a)>=0,d=c?"height":"width";if(!(!n||!o)){var h=i0(s.padding,t),u=wn(n),f=l==="y"?Xe:qe,g=l==="y"?tt:it,p=t.rects.reference[d]+t.rects.reference[l]-o[l]-t.rects.popper[d],m=o[l]-t.rects.reference[l],A=ss(n),T=A?l==="y"?A.clientHeight||0:A.clientWidth||0:0,b=p/2-m/2,y=h[f],x=T-u[d]-h[g],E=T/2-u[d]/2+b,S=rs(y,E,x),R=l;t.modifiersData[i]=(e={},e[R]=S,e.centerOffset=S-E,e)}}function r0(r){var e=r.state,t=r.options,i=t.element,s=i===void 0?"[data-popper-arrow]":i;s!=null&&(typeof s=="string"&&(s=e.elements.popper.querySelector(s),!s)||Ml(e.elements.popper,s)&&(e.elements.arrow=s))}const n0={name:"arrow",enabled:!0,phase:"main",fn:s0,effect:r0,requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function Ti(r){return r.split("-")[1]}var o0={top:"auto",right:"auto",bottom:"auto",left:"auto"};function a0(r,e){var t=r.x,i=r.y,s=e.devicePixelRatio||1;return{x:bi(t*s)/s||0,y:bi(i*s)/s||0}}function Hl(r){var e,t=r.popper,i=r.popperRect,s=r.placement,n=r.variation,o=r.offsets,a=r.position,l=r.gpuAcceleration,c=r.adaptive,d=r.roundOffsets,h=r.isFixed,u=o.x,f=u===void 0?0:u,g=o.y,p=g===void 0?0:g,m=typeof d=="function"?d({x:f,y:p}):{x:f,y:p};f=m.x,p=m.y;var A=o.hasOwnProperty("x"),T=o.hasOwnProperty("y"),b=qe,y=Xe,x=window;if(c){var E=ss(t),S="clientHeight",R="clientWidth";if(E===Qe(t)&&(E=Gt(t),kt(E).position!=="static"&&a==="absolute"&&(S="scrollHeight",R="scrollWidth")),E=E,s===Xe||(s===qe||s===it)&&n===ts){y=tt;var w=h&&E===x&&x.visualViewport?x.visualViewport.height:E[S];p-=w-i.height,p*=l?1:-1}if(s===qe||(s===Xe||s===tt)&&n===ts){b=it;var I=h&&E===x&&x.visualViewport?x.visualViewport.width:E[R];f-=I-i.width,f*=l?1:-1}}var O=Object.assign({position:a},c&&o0),P=d===!0?a0({x:f,y:p},Qe(t)):{x:f,y:p};if(f=P.x,p=P.y,l){var B;return Object.assign({},O,(B={},B[y]=T?"0":"",B[b]=A?"0":"",B.transform=(x.devicePixelRatio||1)<=1?"translate("+f+"px, "+p+"px)":"translate3d("+f+"px, "+p+"px, 0)",B))}return Object.assign({},O,(e={},e[y]=T?p+"px":"",e[b]=A?f+"px":"",e.transform="",e))}function l0(r){var e=r.state,t=r.options,i=t.gpuAcceleration,s=i===void 0?!0:i,n=t.adaptive,o=n===void 0?!0:n,a=t.roundOffsets,l=a===void 0?!0:a,c={placement:vt(e.placement),variation:Ti(e.placement),popper:e.elements.popper,popperRect:e.rects.popper,gpuAcceleration:s,isFixed:e.options.strategy==="fixed"};e.modifiersData.popperOffsets!=null&&(e.styles.popper=Object.assign({},e.styles.popper,Hl(Object.assign({},c,{offsets:e.modifiersData.popperOffsets,position:e.options.strategy,adaptive:o,roundOffsets:l})))),e.modifiersData.arrow!=null&&(e.styles.arrow=Object.assign({},e.styles.arrow,Hl(Object.assign({},c,{offsets:e.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-placement":e.placement})}const c0={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:l0,data:{}};var Ys={passive:!0};function d0(r){var e=r.state,t=r.instance,i=r.options,s=i.scroll,n=s===void 0?!0:s,o=i.resize,a=o===void 0?!0:o,l=Qe(e.elements.popper),c=[].concat(e.scrollParents.reference,e.scrollParents.popper);return n&&c.forEach(function(d){d.addEventListener("scroll",t.update,Ys)}),a&&l.addEventListener("resize",t.update,Ys),function(){n&&c.forEach(function(d){d.removeEventListener("scroll",t.update,Ys)}),a&&l.removeEventListener("resize",t.update,Ys)}}const h0={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:d0,data:{}};var u0={left:"right",right:"left",bottom:"top",top:"bottom"};function Ks(r){return r.replace(/left|right|bottom|top/g,function(e){return u0[e]})}var f0={start:"end",end:"start"};function Gl(r){return r.replace(/start|end/g,function(e){return f0[e]})}function Rn(r){var e=Qe(r),t=e.pageXOffset,i=e.pageYOffset;return{scrollLeft:t,scrollTop:i}}function Dn(r){return xi(Gt(r)).left+Rn(r).scrollLeft}function g0(r,e){var t=Qe(r),i=Gt(r),s=t.visualViewport,n=i.clientWidth,o=i.clientHeight,a=0,l=0;if(s){n=s.width,o=s.height;var c=Ol();(c||!c&&e==="fixed")&&(a=s.offsetLeft,l=s.offsetTop)}return{width:n,height:o,x:a+Dn(r),y:l}}function p0(r){var e,t=Gt(r),i=Rn(r),s=(e=r.ownerDocument)==null?void 0:e.body,n=ii(t.scrollWidth,t.clientWidth,s?s.scrollWidth:0,s?s.clientWidth:0),o=ii(t.scrollHeight,t.clientHeight,s?s.scrollHeight:0,s?s.clientHeight:0),a=-i.scrollLeft+Dn(r),l=-i.scrollTop;return kt(s||t).direction==="rtl"&&(a+=ii(t.clientWidth,s?s.clientWidth:0)-n),{width:n,height:o,x:a,y:l}}function kn(r){var e=kt(r),t=e.overflow,i=e.overflowX,s=e.overflowY;return/auto|scroll|overlay|hidden/.test(t+s+i)}function Vl(r){return["html","body","#document"].indexOf(mt(r))>=0?r.ownerDocument.body:st(r)&&kn(r)?r:Vl(Ws(r))}function ns(r,e){var t;e===void 0&&(e=[]);var i=Vl(r),s=i===((t=r.ownerDocument)==null?void 0:t.body),n=Qe(i),o=s?[n].concat(n.visualViewport||[],kn(i)?i:[]):i,a=e.concat(o);return s?a:a.concat(ns(Ws(o)))}function Pn(r){return Object.assign({},r,{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height})}function m0(r,e){var t=xi(r,!1,e==="fixed");return t.top=t.top+r.clientTop,t.left=t.left+r.clientLeft,t.bottom=t.top+r.clientHeight,t.right=t.left+r.clientWidth,t.width=r.clientWidth,t.height=r.clientHeight,t.x=t.left,t.y=t.top,t}function jl(r,e,t){return e===Rl?Pn(g0(r,t)):ti(e)?m0(e,t):Pn(p0(Gt(r)))}function v0(r){var e=ns(Ws(r)),t=["absolute","fixed"].indexOf(kt(r).position)>=0,i=t&&st(r)?ss(r):r;return ti(i)?e.filter(function(s){return ti(s)&&Ml(s,i)&&mt(s)!=="body"}):[]}function y0(r,e,t,i){var s=e==="clippingParents"?v0(r):[].concat(e),n=[].concat(s,[t]),o=n[0],a=n.reduce(function(l,c){var d=jl(r,c,i);return l.top=ii(d.top,l.top),l.right=zs(d.right,l.right),l.bottom=zs(d.bottom,l.bottom),l.left=ii(d.left,l.left),l},jl(r,o,i));return a.width=a.right-a.left,a.height=a.bottom-a.top,a.x=a.left,a.y=a.top,a}function zl(r){var e=r.reference,t=r.element,i=r.placement,s=i?vt(i):null,n=i?Ti(i):null,o=e.x+e.width/2-t.width/2,a=e.y+e.height/2-t.height/2,l;switch(s){case Xe:l={x:o,y:e.y-t.height};break;case tt:l={x:o,y:e.y+e.height};break;case it:l={x:e.x+e.width,y:a};break;case qe:l={x:e.x-t.width,y:a};break;default:l={x:e.x,y:e.y}}var c=s?Ln(s):null;if(c!=null){var d=c==="y"?"height":"width";switch(n){case Ai:l[c]=l[c]-(e[d]/2-t[d]/2);break;case ts:l[c]=l[c]+(e[d]/2-t[d]/2);break}}return l}function os(r,e){e===void 0&&(e={});var t=e,i=t.placement,s=i===void 0?r.placement:i,n=t.strategy,o=n===void 0?r.strategy:n,a=t.boundary,l=a===void 0?Hf:a,c=t.rootBoundary,d=c===void 0?Rl:c,h=t.elementContext,u=h===void 0?is:h,f=t.altBoundary,g=f===void 0?!1:f,p=t.padding,m=p===void 0?0:p,A=Bl(typeof m!="number"?m:Ul(m,es)),T=u===is?Gf:is,b=r.rects.popper,y=r.elements[g?T:u],x=y0(ti(y)?y:y.contextElement||Gt(r.elements.popper),l,d,o),E=xi(r.elements.reference),S=zl({reference:E,element:b,strategy:"absolute",placement:s}),R=Pn(Object.assign({},b,S)),w=u===is?R:E,I={top:x.top-w.top+A.top,bottom:w.bottom-x.bottom+A.bottom,left:x.left-w.left+A.left,right:w.right-x.right+A.right},O=r.modifiersData.offset;if(u===is&&O){var P=O[s];Object.keys(I).forEach(function(B){var J=[it,tt].indexOf(B)>=0?1:-1,H=[Xe,tt].indexOf(B)>=0?"y":"x";I[B]+=P[H]*J})}return I}function A0(r,e){e===void 0&&(e={});var t=e,i=t.placement,s=t.boundary,n=t.rootBoundary,o=t.padding,a=t.flipVariations,l=t.allowedAutoPlacements,c=l===void 0?kl:l,d=Ti(i),h=d?a?Dl:Dl.filter(function(g){return Ti(g)===d}):es,u=h.filter(function(g){return c.indexOf(g)>=0});u.length===0&&(u=h);var f=u.reduce(function(g,p){return g[p]=os(r,{placement:p,boundary:s,rootBoundary:n,padding:o})[vt(p)],g},{});return Object.keys(f).sort(function(g,p){return f[g]-f[p]})}function b0(r){if(vt(r)===Sn)return[];var e=Ks(r);return[Gl(r),e,Gl(e)]}function x0(r){var e=r.state,t=r.options,i=r.name;if(!e.modifiersData[i]._skip){for(var s=t.mainAxis,n=s===void 0?!0:s,o=t.altAxis,a=o===void 0?!0:o,l=t.fallbackPlacements,c=t.padding,d=t.boundary,h=t.rootBoundary,u=t.altBoundary,f=t.flipVariations,g=f===void 0?!0:f,p=t.allowedAutoPlacements,m=e.options.placement,A=vt(m),T=A===m,b=l||(T||!g?[Ks(m)]:b0(m)),y=[m].concat(b).reduce(function(X,ie){return X.concat(vt(ie)===Sn?A0(e,{placement:ie,boundary:d,rootBoundary:h,padding:c,flipVariations:g,allowedAutoPlacements:p}):ie)},[]),x=e.rects.reference,E=e.rects.popper,S=new Map,R=!0,w=y[0],I=0;I<y.length;I++){var O=y[I],P=vt(O),B=Ti(O)===Ai,J=[Xe,tt].indexOf(P)>=0,H=J?"width":"height",V=os(e,{placement:O,boundary:d,rootBoundary:h,altBoundary:u,padding:c}),j=J?B?it:qe:B?tt:Xe;x[H]>E[H]&&(j=Ks(j));var F=Ks(j),U=[];if(n&&U.push(V[P]<=0),a&&U.push(V[j]<=0,V[F]<=0),U.every(function(X){return X})){w=O,R=!1;break}S.set(O,U)}if(R)for(var Q=g?3:1,Y=function(ie){var ee=y.find(function(ne){var se=S.get(ne);if(se)return se.slice(0,ie).every(function(ye){return ye})});if(ee)return w=ee,"break"},z=Q;z>0;z--){var K=Y(z);if(K==="break")break}e.placement!==w&&(e.modifiersData[i]._skip=!0,e.placement=w,e.reset=!0)}}const T0={name:"flip",enabled:!0,phase:"main",fn:x0,requiresIfExists:["offset"],data:{_skip:!1}};function Wl(r,e,t){return t===void 0&&(t={x:0,y:0}),{top:r.top-e.height-t.y,right:r.right-e.width+t.x,bottom:r.bottom-e.height+t.y,left:r.left-e.width-t.x}}function Yl(r){return[Xe,it,tt,qe].some(function(e){return r[e]>=0})}function E0(r){var e=r.state,t=r.name,i=e.rects.reference,s=e.rects.popper,n=e.modifiersData.preventOverflow,o=os(e,{elementContext:"reference"}),a=os(e,{altBoundary:!0}),l=Wl(o,i),c=Wl(a,s,n),d=Yl(l),h=Yl(c);e.modifiersData[t]={referenceClippingOffsets:l,popperEscapeOffsets:c,isReferenceHidden:d,hasPopperEscaped:h},e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-reference-hidden":d,"data-popper-escaped":h})}const S0={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:E0};function I0(r,e,t){var i=vt(r),s=[qe,Xe].indexOf(i)>=0?-1:1,n=typeof t=="function"?t(Object.assign({},e,{placement:r})):t,o=n[0],a=n[1];return o=o||0,a=(a||0)*s,[qe,it].indexOf(i)>=0?{x:a,y:o}:{x:o,y:a}}function C0(r){var e=r.state,t=r.options,i=r.name,s=t.offset,n=s===void 0?[0,0]:s,o=kl.reduce(function(d,h){return d[h]=I0(h,e.rects,n),d},{}),a=o[e.placement],l=a.x,c=a.y;e.modifiersData.popperOffsets!=null&&(e.modifiersData.popperOffsets.x+=l,e.modifiersData.popperOffsets.y+=c),e.modifiersData[i]=o}const w0={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:C0};function L0(r){var e=r.state,t=r.name;e.modifiersData[t]=zl({reference:e.rects.reference,element:e.rects.popper,strategy:"absolute",placement:e.placement})}const R0={name:"popperOffsets",enabled:!0,phase:"read",fn:L0,data:{}};function D0(r){return r==="x"?"y":"x"}function k0(r){var e=r.state,t=r.options,i=r.name,s=t.mainAxis,n=s===void 0?!0:s,o=t.altAxis,a=o===void 0?!1:o,l=t.boundary,c=t.rootBoundary,d=t.altBoundary,h=t.padding,u=t.tether,f=u===void 0?!0:u,g=t.tetherOffset,p=g===void 0?0:g,m=os(e,{boundary:l,rootBoundary:c,padding:h,altBoundary:d}),A=vt(e.placement),T=Ti(e.placement),b=!T,y=Ln(A),x=D0(y),E=e.modifiersData.popperOffsets,S=e.rects.reference,R=e.rects.popper,w=typeof p=="function"?p(Object.assign({},e.rects,{placement:e.placement})):p,I=typeof w=="number"?{mainAxis:w,altAxis:w}:Object.assign({mainAxis:0,altAxis:0},w),O=e.modifiersData.offset?e.modifiersData.offset[e.placement]:null,P={x:0,y:0};if(E){if(n){var B,J=y==="y"?Xe:qe,H=y==="y"?tt:it,V=y==="y"?"height":"width",j=E[y],F=j+m[J],U=j-m[H],Q=f?-R[V]/2:0,Y=T===Ai?S[V]:R[V],z=T===Ai?-R[V]:-S[V],K=e.elements.arrow,X=f&&K?wn(K):{width:0,height:0},ie=e.modifiersData["arrow#persistent"]?e.modifiersData["arrow#persistent"].padding:Nl(),ee=ie[J],ne=ie[H],se=rs(0,S[V],X[V]),ye=b?S[V]/2-Q-se-ee-I.mainAxis:Y-se-ee-I.mainAxis,he=b?-S[V]/2+Q+se+ne+I.mainAxis:z+se+ne+I.mainAxis,_e=e.elements.arrow&&ss(e.elements.arrow),Pt=_e?y==="y"?_e.clientTop||0:_e.clientLeft||0:0,Tt=(B=O==null?void 0:O[y])!=null?B:0,Ot=j+ye-Tt-Pt,Te=j+he-Tt,Ae=rs(f?zs(F,Ot):F,j,f?ii(U,Te):U);E[y]=Ae,P[y]=Ae-j}if(a){var Ue,ue=y==="x"?Xe:qe,be=y==="x"?tt:it,Le=E[x],He=x==="y"?"height":"width",Mt=Le+m[ue],Ft=Le-m[be],oi=[Xe,qe].indexOf(A)!==-1,Ri=(Ue=O==null?void 0:O[x])!=null?Ue:0,Di=oi?Mt:Le-S[He]-R[He]-Ri+I.altAxis,ki=oi?Le+S[He]+R[He]-Ri-I.altAxis:Ft,or=f&&oi?t0(Di,Le,ki):rs(f?Di:Mt,Le,f?ki:Ft);E[x]=or,P[x]=or-Le}e.modifiersData[i]=P}}const P0={name:"preventOverflow",enabled:!0,phase:"main",fn:k0,requiresIfExists:["offset"]};function O0(r){return{scrollLeft:r.scrollLeft,scrollTop:r.scrollTop}}function M0(r){return r===Qe(r)||!st(r)?Rn(r):O0(r)}function F0(r){var e=r.getBoundingClientRect(),t=bi(e.width)/r.offsetWidth||1,i=bi(e.height)/r.offsetHeight||1;return t!==1||i!==1}function N0(r,e,t){t===void 0&&(t=!1);var i=st(e),s=st(e)&&F0(e),n=Gt(e),o=xi(r,s,t),a={scrollLeft:0,scrollTop:0},l={x:0,y:0};return(i||!i&&!t)&&((mt(e)!=="body"||kn(n))&&(a=M0(e)),st(e)?(l=xi(e,!0),l.x+=e.clientLeft,l.y+=e.clientTop):n&&(l.x=Dn(n))),{x:o.left+a.scrollLeft-l.x,y:o.top+a.scrollTop-l.y,width:o.width,height:o.height}}function B0(r){var e=new Map,t=new Set,i=[];r.forEach(function(n){e.set(n.name,n)});function s(n){t.add(n.name);var o=[].concat(n.requires||[],n.requiresIfExists||[]);o.forEach(function(a){if(!t.has(a)){var l=e.get(a);l&&s(l)}}),i.push(n)}return r.forEach(function(n){t.has(n.name)||s(n)}),i}function U0(r){var e=B0(r);return Jf.reduce(function(t,i){return t.concat(e.filter(function(s){return s.phase===i}))},[])}function H0(r){var e;return function(){return e||(e=new Promise(function(t){Promise.resolve().then(function(){e=void 0,t(r())})})),e}}function G0(r){var e=r.reduce(function(t,i){var s=t[i.name];return t[i.name]=s?Object.assign({},s,i,{options:Object.assign({},s.options,i.options),data:Object.assign({},s.data,i.data)}):i,t},{});return Object.keys(e).map(function(t){return e[t]})}var Kl={placement:"bottom",modifiers:[],strategy:"absolute"};function Xl(){for(var r=arguments.length,e=new Array(r),t=0;t<r;t++)e[t]=arguments[t];return!e.some(function(i){return!(i&&typeof i.getBoundingClientRect=="function")})}function V0(r){r===void 0&&(r={});var e=r,t=e.defaultModifiers,i=t===void 0?[]:t,s=e.defaultOptions,n=s===void 0?Kl:s;return function(a,l,c){c===void 0&&(c=n);var d={placement:"bottom",orderedModifiers:[],options:Object.assign({},Kl,n),modifiersData:{},elements:{reference:a,popper:l},attributes:{},styles:{}},h=[],u=!1,f={state:d,setOptions:function(A){var T=typeof A=="function"?A(d.options):A;p(),d.options=Object.assign({},n,d.options,T),d.scrollParents={reference:ti(a)?ns(a):a.contextElement?ns(a.contextElement):[],popper:ns(l)};var b=U0(G0([].concat(i,d.options.modifiers)));return d.orderedModifiers=b.filter(function(y){return y.enabled}),g(),f.update()},forceUpdate:function(){if(!u){var A=d.elements,T=A.reference,b=A.popper;if(Xl(T,b)){d.rects={reference:N0(T,ss(b),d.options.strategy==="fixed"),popper:wn(b)},d.reset=!1,d.placement=d.options.placement,d.orderedModifiers.forEach(function(I){return d.modifiersData[I.name]=Object.assign({},I.data)});for(var y=0;y<d.orderedModifiers.length;y++){if(d.reset===!0){d.reset=!1,y=-1;continue}var x=d.orderedModifiers[y],E=x.fn,S=x.options,R=S===void 0?{}:S,w=x.name;typeof E=="function"&&(d=E({state:d,options:R,name:w,instance:f})||d)}}}},update:H0(function(){return new Promise(function(m){f.forceUpdate(),m(d)})}),destroy:function(){p(),u=!0}};if(!Xl(a,l))return f;f.setOptions(c).then(function(m){!u&&c.onFirstUpdate&&c.onFirstUpdate(m)});function g(){d.orderedModifiers.forEach(function(m){var A=m.name,T=m.options,b=T===void 0?{}:T,y=m.effect;if(typeof y=="function"){var x=y({state:d,name:A,instance:f,options:b}),E=function(){};h.push(x||E)}})}function p(){h.forEach(function(m){return m()}),h=[]}return f}}var j0=[h0,R0,c0,Pl,w0,T0,P0,n0,S0],z0=V0({defaultModifiers:j0}),W0="tippy-box",ql="tippy-content",Y0="tippy-backdrop",Zl="tippy-arrow",Jl="tippy-svg-arrow",si={passive:!0,capture:!0},Ql=function(){return document.body};function On(r,e,t){if(Array.isArray(r)){var i=r[e];return i??(Array.isArray(t)?t[e]:t)}return r}function Mn(r,e){var t={}.toString.call(r);return t.indexOf("[object")===0&&t.indexOf(e+"]")>-1}function _l(r,e){return typeof r=="function"?r.apply(void 0,e):r}function $l(r,e){if(e===0)return r;var t;return function(i){clearTimeout(t),t=setTimeout(function(){r(i)},e)}}function K0(r){return r.split(/\s+/).filter(Boolean)}function Ei(r){return[].concat(r)}function ec(r,e){r.indexOf(e)===-1&&r.push(e)}function X0(r){return r.filter(function(e,t){return r.indexOf(e)===t})}function q0(r){return r.split("-")[0]}function Xs(r){return[].slice.call(r)}function tc(r){return Object.keys(r).reduce(function(e,t){return r[t]!==void 0&&(e[t]=r[t]),e},{})}function as(){return document.createElement("div")}function qs(r){return["Element","Fragment"].some(function(e){return Mn(r,e)})}function Z0(r){return Mn(r,"NodeList")}function J0(r){return Mn(r,"MouseEvent")}function Q0(r){return!!(r&&r._tippy&&r._tippy.reference===r)}function _0(r){return qs(r)?[r]:Z0(r)?Xs(r):Array.isArray(r)?r:Xs(document.querySelectorAll(r))}function Fn(r,e){r.forEach(function(t){t&&(t.style.transitionDuration=e+"ms")})}function ic(r,e){r.forEach(function(t){t&&t.setAttribute("data-state",e)})}function $0(r){var e,t=Ei(r),i=t[0];return i!=null&&(e=i.ownerDocument)!=null&&e.body?i.ownerDocument:document}function eg(r,e){var t=e.clientX,i=e.clientY;return r.every(function(s){var n=s.popperRect,o=s.popperState,a=s.props,l=a.interactiveBorder,c=q0(o.placement),d=o.modifiersData.offset;if(!d)return!0;var h=c==="bottom"?d.top.y:0,u=c==="top"?d.bottom.y:0,f=c==="right"?d.left.x:0,g=c==="left"?d.right.x:0,p=n.top-i+h>l,m=i-n.bottom-u>l,A=n.left-t+f>l,T=t-n.right-g>l;return p||m||A||T})}function Nn(r,e,t){var i=e+"EventListener";["transitionend","webkitTransitionEnd"].forEach(function(s){r[i](s,t)})}function sc(r,e){for(var t=e;t;){var i;if(r.contains(t))return!0;t=t.getRootNode==null||(i=t.getRootNode())==null?void 0:i.host}return!1}var yt={isTouch:!1},rc=0;function tg(){yt.isTouch||(yt.isTouch=!0,window.performance&&document.addEventListener("mousemove",nc))}function nc(){var r=performance.now();r-rc<20&&(yt.isTouch=!1,document.removeEventListener("mousemove",nc)),rc=r}function ig(){var r=document.activeElement;if(Q0(r)){var e=r._tippy;r.blur&&!e.state.isVisible&&r.blur()}}function sg(){document.addEventListener("touchstart",tg,si),window.addEventListener("blur",ig)}var rg=typeof window<"u"&&typeof document<"u",ng=rg?!!window.msCrypto:!1,og={animateFill:!1,followCursor:!1,inlinePositioning:!1,sticky:!1},ag={allowHTML:!1,animation:"fade",arrow:!0,content:"",inertia:!1,maxWidth:350,role:"tooltip",theme:"",zIndex:9999},ht=Object.assign({appendTo:Ql,aria:{content:"auto",expanded:"auto"},delay:0,duration:[300,250],getReferenceClientRect:null,hideOnClick:!0,ignoreAttributes:!1,interactive:!1,interactiveBorder:2,interactiveDebounce:0,moveTransition:"",offset:[0,10],onAfterUpdate:function(){},onBeforeUpdate:function(){},onCreate:function(){},onDestroy:function(){},onHidden:function(){},onHide:function(){},onMount:function(){},onShow:function(){},onShown:function(){},onTrigger:function(){},onUntrigger:function(){},onClickOutside:function(){},placement:"top",plugins:[],popperOptions:{},render:null,showOnCreate:!1,touch:!0,trigger:"mouseenter focus",triggerTarget:null},og,ag),lg=Object.keys(ht),cg=function(e){var t=Object.keys(e);t.forEach(function(i){ht[i]=e[i]})};function oc(r){var e=r.plugins||[],t=e.reduce(function(i,s){var n=s.name,o=s.defaultValue;if(n){var a;i[n]=r[n]!==void 0?r[n]:(a=ht[n])!=null?a:o}return i},{});return Object.assign({},r,t)}function dg(r,e){var t=e?Object.keys(oc(Object.assign({},ht,{plugins:e}))):lg,i=t.reduce(function(s,n){var o=(r.getAttribute("data-tippy-"+n)||"").trim();if(!o)return s;if(n==="content")s[n]=o;else try{s[n]=JSON.parse(o)}catch{s[n]=o}return s},{});return i}function ac(r,e){var t=Object.assign({},e,{content:_l(e.content,[r])},e.ignoreAttributes?{}:dg(r,e.plugins));return t.aria=Object.assign({},ht.aria,t.aria),t.aria={expanded:t.aria.expanded==="auto"?e.interactive:t.aria.expanded,content:t.aria.content==="auto"?e.interactive?null:"describedby":t.aria.content},t}var hg=function(){return"innerHTML"};function Bn(r,e){r[hg()]=e}function lc(r){var e=as();return r===!0?e.className=Zl:(e.className=Jl,qs(r)?e.appendChild(r):Bn(e,r)),e}function cc(r,e){qs(e.content)?(Bn(r,""),r.appendChild(e.content)):typeof e.content!="function"&&(e.allowHTML?Bn(r,e.content):r.textContent=e.content)}function Un(r){var e=r.firstElementChild,t=Xs(e.children);return{box:e,content:t.find(function(i){return i.classList.contains(ql)}),arrow:t.find(function(i){return i.classList.contains(Zl)||i.classList.contains(Jl)}),backdrop:t.find(function(i){return i.classList.contains(Y0)})}}function dc(r){var e=as(),t=as();t.className=W0,t.setAttribute("data-state","hidden"),t.setAttribute("tabindex","-1");var i=as();i.className=ql,i.setAttribute("data-state","hidden"),cc(i,r.props),e.appendChild(t),t.appendChild(i),s(r.props,r.props);function s(n,o){var a=Un(e),l=a.box,c=a.content,d=a.arrow;o.theme?l.setAttribute("data-theme",o.theme):l.removeAttribute("data-theme"),typeof o.animation=="string"?l.setAttribute("data-animation",o.animation):l.removeAttribute("data-animation"),o.inertia?l.setAttribute("data-inertia",""):l.removeAttribute("data-inertia"),l.style.maxWidth=typeof o.maxWidth=="number"?o.maxWidth+"px":o.maxWidth,o.role?l.setAttribute("role",o.role):l.removeAttribute("role"),(n.content!==o.content||n.allowHTML!==o.allowHTML)&&cc(c,r.props),o.arrow?d?n.arrow!==o.arrow&&(l.removeChild(d),l.appendChild(lc(o.arrow))):l.appendChild(lc(o.arrow)):d&&l.removeChild(d)}return{popper:e,onUpdate:s}}dc.$$tippy=!0;var ug=1,Zs=[],Hn=[];function fg(r,e){var t=ac(r,Object.assign({},ht,oc(tc(e)))),i,s,n,o=!1,a=!1,l=!1,c=!1,d,h,u,f=[],g=$l(Ot,t.interactiveDebounce),p,m=ug++,A=null,T=X0(t.plugins),b={isEnabled:!0,isVisible:!1,isDestroyed:!1,isMounted:!1,isShown:!1},y={id:m,reference:r,popper:as(),popperInstance:A,props:t,state:b,plugins:T,clearDelayTimeouts:Di,setProps:ki,setContent:or,show:fm,hide:gm,hideWithInteractivity:pm,enable:oi,disable:Ri,unmount:mm,destroy:vm};if(!t.render)return y;var x=t.render(y),E=x.popper,S=x.onUpdate;E.setAttribute("data-tippy-root",""),E.id="tippy-"+y.id,y.popper=E,r._tippy=y,E._tippy=y;var R=T.map(function(k){return k.fn(y)}),w=r.hasAttribute("aria-expanded");return _e(),Q(),j(),F("onCreate",[y]),t.showOnCreate&&Mt(),E.addEventListener("mouseenter",function(){y.props.interactive&&y.state.isVisible&&y.clearDelayTimeouts()}),E.addEventListener("mouseleave",function(){y.props.interactive&&y.props.trigger.indexOf("mouseenter")>=0&&J().addEventListener("mousemove",g)}),y;function I(){var k=y.props.touch;return Array.isArray(k)?k:[k,0]}function O(){return I()[0]==="hold"}function P(){var k;return!!((k=y.props.render)!=null&&k.$$tippy)}function B(){return p||r}function J(){var k=B().parentNode;return k?$0(k):document}function H(){return Un(E)}function V(k){return y.state.isMounted&&!y.state.isVisible||yt.isTouch||d&&d.type==="focus"?0:On(y.props.delay,k?0:1,ht.delay)}function j(k){k===void 0&&(k=!1),E.style.pointerEvents=y.props.interactive&&!k?"":"none",E.style.zIndex=""+y.props.zIndex}function F(k,G,$){if($===void 0&&($=!0),R.forEach(function(oe){oe[k]&&oe[k].apply(oe,G)}),$){var ce;(ce=y.props)[k].apply(ce,G)}}function U(){var k=y.props.aria;if(k.content){var G="aria-"+k.content,$=E.id,ce=Ei(y.props.triggerTarget||r);ce.forEach(function(oe){var Ve=oe.getAttribute(G);if(y.state.isVisible)oe.setAttribute(G,Ve?Ve+" "+$:$);else{var rt=Ve&&Ve.replace($,"").trim();rt?oe.setAttribute(G,rt):oe.removeAttribute(G)}})}}function Q(){if(!(w||!y.props.aria.expanded)){var k=Ei(y.props.triggerTarget||r);k.forEach(function(G){y.props.interactive?G.setAttribute("aria-expanded",y.state.isVisible&&G===B()?"true":"false"):G.removeAttribute("aria-expanded")})}}function Y(){J().removeEventListener("mousemove",g),Zs=Zs.filter(function(k){return k!==g})}function z(k){if(!(yt.isTouch&&(l||k.type==="mousedown"))){var G=k.composedPath&&k.composedPath()[0]||k.target;if(!(y.props.interactive&&sc(E,G))){if(Ei(y.props.triggerTarget||r).some(function($){return sc($,G)})){if(yt.isTouch||y.state.isVisible&&y.props.trigger.indexOf("click")>=0)return}else F("onClickOutside",[y,k]);y.props.hideOnClick===!0&&(y.clearDelayTimeouts(),y.hide(),a=!0,setTimeout(function(){a=!1}),y.state.isMounted||ee())}}}function K(){l=!0}function X(){l=!1}function ie(){var k=J();k.addEventListener("mousedown",z,!0),k.addEventListener("touchend",z,si),k.addEventListener("touchstart",X,si),k.addEventListener("touchmove",K,si)}function ee(){var k=J();k.removeEventListener("mousedown",z,!0),k.removeEventListener("touchend",z,si),k.removeEventListener("touchstart",X,si),k.removeEventListener("touchmove",K,si)}function ne(k,G){ye(k,function(){!y.state.isVisible&&E.parentNode&&E.parentNode.contains(E)&&G()})}function se(k,G){ye(k,G)}function ye(k,G){var $=H().box;function ce(oe){oe.target===$&&(Nn($,"remove",ce),G())}if(k===0)return G();Nn($,"remove",h),Nn($,"add",ce),h=ce}function he(k,G,$){$===void 0&&($=!1);var ce=Ei(y.props.triggerTarget||r);ce.forEach(function(oe){oe.addEventListener(k,G,$),f.push({node:oe,eventType:k,handler:G,options:$})})}function _e(){O()&&(he("touchstart",Tt,{passive:!0}),he("touchend",Te,{passive:!0})),K0(y.props.trigger).forEach(function(k){if(k!=="manual")switch(he(k,Tt),k){case"mouseenter":he("mouseleave",Te);break;case"focus":he(ng?"focusout":"blur",Ae);break;case"focusin":he("focusout",Ae);break}})}function Pt(){f.forEach(function(k){var G=k.node,$=k.eventType,ce=k.handler,oe=k.options;G.removeEventListener($,ce,oe)}),f=[]}function Tt(k){var G,$=!1;if(!(!y.state.isEnabled||Ue(k)||a)){var ce=((G=d)==null?void 0:G.type)==="focus";d=k,p=k.currentTarget,Q(),!y.state.isVisible&&J0(k)&&Zs.forEach(function(oe){return oe(k)}),k.type==="click"&&(y.props.trigger.indexOf("mouseenter")<0||o)&&y.props.hideOnClick!==!1&&y.state.isVisible?$=!0:Mt(k),k.type==="click"&&(o=!$),$&&!ce&&Ft(k)}}function Ot(k){var G=k.target,$=B().contains(G)||E.contains(G);if(!(k.type==="mousemove"&&$)){var ce=He().concat(E).map(function(oe){var Ve,rt=oe._tippy,Pi=(Ve=rt.popperInstance)==null?void 0:Ve.state;return Pi?{popperRect:oe.getBoundingClientRect(),popperState:Pi,props:t}:null}).filter(Boolean);eg(ce,k)&&(Y(),Ft(k))}}function Te(k){var G=Ue(k)||y.props.trigger.indexOf("click")>=0&&o;if(!G){if(y.props.interactive){y.hideWithInteractivity(k);return}Ft(k)}}function Ae(k){y.props.trigger.indexOf("focusin")<0&&k.target!==B()||y.props.interactive&&k.relatedTarget&&E.contains(k.relatedTarget)||Ft(k)}function Ue(k){return yt.isTouch?O()!==k.type.indexOf("touch")>=0:!1}function ue(){be();var k=y.props,G=k.popperOptions,$=k.placement,ce=k.offset,oe=k.getReferenceClientRect,Ve=k.moveTransition,rt=P()?Un(E).arrow:null,Pi=oe?{getBoundingClientRect:oe,contextElement:oe.contextElement||B()}:r,Dc={name:"$$tippy",enabled:!0,phase:"beforeWrite",requires:["computeStyles"],fn:function(ar){var Oi=ar.state;if(P()){var ym=H(),eo=ym.box;["placement","reference-hidden","escaped"].forEach(function(lr){lr==="placement"?eo.setAttribute("data-placement",Oi.placement):Oi.attributes.popper["data-popper-"+lr]?eo.setAttribute("data-"+lr,""):eo.removeAttribute("data-"+lr)}),Oi.attributes.popper={}}}},ai=[{name:"offset",options:{offset:ce}},{name:"preventOverflow",options:{padding:{top:2,bottom:2,left:5,right:5}}},{name:"flip",options:{padding:5}},{name:"computeStyles",options:{adaptive:!Ve}},Dc];P()&&rt&&ai.push({name:"arrow",options:{element:rt,padding:3}}),ai.push.apply(ai,(G==null?void 0:G.modifiers)||[]),y.popperInstance=z0(Pi,E,Object.assign({},G,{placement:$,onFirstUpdate:u,modifiers:ai}))}function be(){y.popperInstance&&(y.popperInstance.destroy(),y.popperInstance=null)}function Le(){var k=y.props.appendTo,G,$=B();y.props.interactive&&k===Ql||k==="parent"?G=$.parentNode:G=_l(k,[$]),G.contains(E)||G.appendChild(E),y.state.isMounted=!0,ue()}function He(){return Xs(E.querySelectorAll("[data-tippy-root]"))}function Mt(k){y.clearDelayTimeouts(),k&&F("onTrigger",[y,k]),ie();var G=V(!0),$=I(),ce=$[0],oe=$[1];yt.isTouch&&ce==="hold"&&oe&&(G=oe),G?i=setTimeout(function(){y.show()},G):y.show()}function Ft(k){if(y.clearDelayTimeouts(),F("onUntrigger",[y,k]),!y.state.isVisible){ee();return}if(!(y.props.trigger.indexOf("mouseenter")>=0&&y.props.trigger.indexOf("click")>=0&&["mouseleave","mousemove"].indexOf(k.type)>=0&&o)){var G=V(!1);G?s=setTimeout(function(){y.state.isVisible&&y.hide()},G):n=requestAnimationFrame(function(){y.hide()})}}function oi(){y.state.isEnabled=!0}function Ri(){y.hide(),y.state.isEnabled=!1}function Di(){clearTimeout(i),clearTimeout(s),cancelAnimationFrame(n)}function ki(k){if(!y.state.isDestroyed){F("onBeforeUpdate",[y,k]),Pt();var G=y.props,$=ac(r,Object.assign({},G,tc(k),{ignoreAttributes:!0}));y.props=$,_e(),G.interactiveDebounce!==$.interactiveDebounce&&(Y(),g=$l(Ot,$.interactiveDebounce)),G.triggerTarget&&!$.triggerTarget?Ei(G.triggerTarget).forEach(function(ce){ce.removeAttribute("aria-expanded")}):$.triggerTarget&&r.removeAttribute("aria-expanded"),Q(),j(),S&&S(G,$),y.popperInstance&&(ue(),He().forEach(function(ce){requestAnimationFrame(ce._tippy.popperInstance.forceUpdate)})),F("onAfterUpdate",[y,k])}}function or(k){y.setProps({content:k})}function fm(){var k=y.state.isVisible,G=y.state.isDestroyed,$=!y.state.isEnabled,ce=yt.isTouch&&!y.props.touch,oe=On(y.props.duration,0,ht.duration);if(!(k||G||$||ce)&&!B().hasAttribute("disabled")&&(F("onShow",[y],!1),y.props.onShow(y)!==!1)){if(y.state.isVisible=!0,P()&&(E.style.visibility="visible"),j(),ie(),y.state.isMounted||(E.style.transition="none"),P()){var Ve=H(),rt=Ve.box,Pi=Ve.content;Fn([rt,Pi],0)}u=function(){var ai;if(!(!y.state.isVisible||c)){if(c=!0,E.offsetHeight,E.style.transition=y.props.moveTransition,P()&&y.props.animation){var $n=H(),ar=$n.box,Oi=$n.content;Fn([ar,Oi],oe),ic([ar,Oi],"visible")}U(),Q(),ec(Hn,y),(ai=y.popperInstance)==null||ai.forceUpdate(),F("onMount",[y]),y.props.animation&&P()&&se(oe,function(){y.state.isShown=!0,F("onShown",[y])})}},Le()}}function gm(){var k=!y.state.isVisible,G=y.state.isDestroyed,$=!y.state.isEnabled,ce=On(y.props.duration,1,ht.duration);if(!(k||G||$)&&(F("onHide",[y],!1),y.props.onHide(y)!==!1)){if(y.state.isVisible=!1,y.state.isShown=!1,c=!1,o=!1,P()&&(E.style.visibility="hidden"),Y(),ee(),j(!0),P()){var oe=H(),Ve=oe.box,rt=oe.content;y.props.animation&&(Fn([Ve,rt],ce),ic([Ve,rt],"hidden"))}U(),Q(),y.props.animation?P()&&ne(ce,y.unmount):y.unmount()}}function pm(k){J().addEventListener("mousemove",g),ec(Zs,g),g(k)}function mm(){y.state.isVisible&&y.hide(),y.state.isMounted&&(be(),He().forEach(function(k){k._tippy.unmount()}),E.parentNode&&E.parentNode.removeChild(E),Hn=Hn.filter(function(k){return k!==y}),y.state.isMounted=!1,F("onHidden",[y]))}function vm(){y.state.isDestroyed||(y.clearDelayTimeouts(),y.unmount(),Pt(),delete r._tippy,y.state.isDestroyed=!0,F("onDestroy",[y]))}}function ri(r,e){e===void 0&&(e={});var t=ht.plugins.concat(e.plugins||[]);sg();var i=Object.assign({},e,{plugins:t}),s=_0(r),n=s.reduce(function(o,a){var l=a&&fg(a,i);return l&&o.push(l),o},[]);return qs(r)?n[0]:n}ri.defaultProps=ht,ri.setDefaultProps=cg,ri.currentInput=yt,Object.assign({},Pl,{effect:function(e){var t=e.state,i={popper:{position:t.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};Object.assign(t.elements.popper.style,i.popper),t.styles=i,t.elements.arrow&&Object.assign(t.elements.arrow.style,i.arrow)}}),ri.setDefaultProps({render:dc});/**
95
+ */const wl=(r,e,t)=>{const i=new Map;for(let s=e;s<=t;s++)i.set(r[s],s);return i},Ll=fi(class extends Wi{constructor(r){if(super(r),r.type!==ui.CHILD)throw Error("repeat() can only be used in text expressions")}dt(r,e,t){let i;t===void 0?t=e:e!==void 0&&(i=e);const s=[],n=[];let o=0;for(const a of r)s[o]=i?i(a,o):o,n[o]=t(a,o),o++;return{values:n,keys:s}}render(r,e,t){return this.dt(r,e,t).values}update(r,[e,t,i]){var s;const n=od(r),{values:o,keys:a}=this.dt(e,t,i);if(!Array.isArray(n))return this.ht=a,o;const l=(s=this.ht)!==null&&s!==void 0?s:this.ht=[],c=[];let d,h,u=0,f=n.length-1,g=0,p=o.length-1;for(;u<=f&&g<=p;)if(n[u]===null)u++;else if(n[f]===null)f--;else if(l[u]===a[g])c[g]=Jt(n[u],o[g]),u++,g++;else if(l[f]===a[p])c[p]=Jt(n[f],o[p]),f--,p--;else if(l[u]===a[p])c[p]=Jt(n[u],o[p]),Yi(r,c[p+1],n[u]),u++,p--;else if(l[f]===a[g])c[g]=Jt(n[f],o[g]),Yi(r,n[u],n[f]),f--,g++;else if(d===void 0&&(d=wl(a,g,p),h=wl(l,u,f)),d.has(l[u]))if(d.has(l[f])){const m=h.get(a[g]),A=m!==void 0?n[m]:null;if(A===null){const x=Yi(r,n[u]);Jt(x,o[g]),c[g]=x}else c[g]=Jt(A,o[g]),Yi(r,n[u],A),n[m]=null;g++}else Sr(n[f]),f--;else Sr(n[u]),u++;for(;g<=p;){const m=Yi(r,c[p+1]);Jt(m,o[g]),c[g++]=m}for(;u<=f;){const m=n[u++];m!==null&&Sr(m)}return this.ht=a,nd(r,c),ot}});var Xe="top",tt="bottom",it="right",qe="left",Sn="auto",es=[Xe,tt,it,qe],bi="start",ts="end",Hf="clippingParents",Rl="viewport",is="popper",Gf="reference",Dl=es.reduce(function(r,e){return r.concat([e+"-"+bi,e+"-"+ts])},[]),kl=[].concat(es,[Sn]).reduce(function(r,e){return r.concat([e,e+"-"+bi,e+"-"+ts])},[]),Vf="beforeRead",jf="read",zf="afterRead",Wf="beforeMain",Yf="main",Kf="afterMain",Xf="beforeWrite",qf="write",Zf="afterWrite",Jf=[Vf,jf,zf,Wf,Yf,Kf,Xf,qf,Zf];function mt(r){return r?(r.nodeName||"").toLowerCase():null}function Qe(r){if(r==null)return window;if(r.toString()!=="[object Window]"){var e=r.ownerDocument;return e&&e.defaultView||window}return r}function ti(r){var e=Qe(r).Element;return r instanceof e||r instanceof Element}function st(r){var e=Qe(r).HTMLElement;return r instanceof e||r instanceof HTMLElement}function In(r){if(typeof ShadowRoot>"u")return!1;var e=Qe(r).ShadowRoot;return r instanceof e||r instanceof ShadowRoot}function Qf(r){var e=r.state;Object.keys(e.elements).forEach(function(t){var i=e.styles[t]||{},s=e.attributes[t]||{},n=e.elements[t];!st(n)||!mt(n)||(Object.assign(n.style,i),Object.keys(s).forEach(function(o){var a=s[o];a===!1?n.removeAttribute(o):n.setAttribute(o,a===!0?"":a)}))})}function _f(r){var e=r.state,t={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(e.elements.popper.style,t.popper),e.styles=t,e.elements.arrow&&Object.assign(e.elements.arrow.style,t.arrow),function(){Object.keys(e.elements).forEach(function(i){var s=e.elements[i],n=e.attributes[i]||{},o=Object.keys(e.styles.hasOwnProperty(i)?e.styles[i]:t[i]),a=o.reduce(function(l,c){return l[c]="",l},{});!st(s)||!mt(s)||(Object.assign(s.style,a),Object.keys(n).forEach(function(l){s.removeAttribute(l)}))})}}const Pl={name:"applyStyles",enabled:!0,phase:"write",fn:Qf,effect:_f,requires:["computeStyles"]};function vt(r){return r.split("-")[0]}var ii=Math.max,zs=Math.min,xi=Math.round;function Cn(){var r=navigator.userAgentData;return r!=null&&r.brands&&Array.isArray(r.brands)?r.brands.map(function(e){return e.brand+"/"+e.version}).join(" "):navigator.userAgent}function Ol(){return!/^((?!chrome|android).)*safari/i.test(Cn())}function Ti(r,e,t){e===void 0&&(e=!1),t===void 0&&(t=!1);var i=r.getBoundingClientRect(),s=1,n=1;e&&st(r)&&(s=r.offsetWidth>0&&xi(i.width)/r.offsetWidth||1,n=r.offsetHeight>0&&xi(i.height)/r.offsetHeight||1);var o=ti(r)?Qe(r):window,a=o.visualViewport,l=!Ol()&&t,c=(i.left+(l&&a?a.offsetLeft:0))/s,d=(i.top+(l&&a?a.offsetTop:0))/n,h=i.width/s,u=i.height/n;return{width:h,height:u,top:d,right:c+h,bottom:d+u,left:c,x:c,y:d}}function wn(r){var e=Ti(r),t=r.offsetWidth,i=r.offsetHeight;return Math.abs(e.width-t)<=1&&(t=e.width),Math.abs(e.height-i)<=1&&(i=e.height),{x:r.offsetLeft,y:r.offsetTop,width:t,height:i}}function Ml(r,e){var t=e.getRootNode&&e.getRootNode();if(r.contains(e))return!0;if(t&&In(t)){var i=e;do{if(i&&r.isSameNode(i))return!0;i=i.parentNode||i.host}while(i)}return!1}function kt(r){return Qe(r).getComputedStyle(r)}function $f(r){return["table","td","th"].indexOf(mt(r))>=0}function Gt(r){return((ti(r)?r.ownerDocument:r.document)||window.document).documentElement}function Ws(r){return mt(r)==="html"?r:r.assignedSlot||r.parentNode||(In(r)?r.host:null)||Gt(r)}function Fl(r){return!st(r)||kt(r).position==="fixed"?null:r.offsetParent}function e0(r){var e=/firefox/i.test(Cn()),t=/Trident/i.test(Cn());if(t&&st(r)){var i=kt(r);if(i.position==="fixed")return null}var s=Ws(r);for(In(s)&&(s=s.host);st(s)&&["html","body"].indexOf(mt(s))<0;){var n=kt(s);if(n.transform!=="none"||n.perspective!=="none"||n.contain==="paint"||["transform","perspective"].indexOf(n.willChange)!==-1||e&&n.willChange==="filter"||e&&n.filter&&n.filter!=="none")return s;s=s.parentNode}return null}function ss(r){for(var e=Qe(r),t=Fl(r);t&&$f(t)&&kt(t).position==="static";)t=Fl(t);return t&&(mt(t)==="html"||mt(t)==="body"&&kt(t).position==="static")?e:t||e0(r)||e}function Ln(r){return["top","bottom"].indexOf(r)>=0?"x":"y"}function rs(r,e,t){return ii(r,zs(e,t))}function t0(r,e,t){var i=rs(r,e,t);return i>t?t:i}function Nl(){return{top:0,right:0,bottom:0,left:0}}function Bl(r){return Object.assign({},Nl(),r)}function Ul(r,e){return e.reduce(function(t,i){return t[i]=r,t},{})}var i0=function(e,t){return e=typeof e=="function"?e(Object.assign({},t.rects,{placement:t.placement})):e,Bl(typeof e!="number"?e:Ul(e,es))};function s0(r){var e,t=r.state,i=r.name,s=r.options,n=t.elements.arrow,o=t.modifiersData.popperOffsets,a=vt(t.placement),l=Ln(a),c=[qe,it].indexOf(a)>=0,d=c?"height":"width";if(!(!n||!o)){var h=i0(s.padding,t),u=wn(n),f=l==="y"?Xe:qe,g=l==="y"?tt:it,p=t.rects.reference[d]+t.rects.reference[l]-o[l]-t.rects.popper[d],m=o[l]-t.rects.reference[l],A=ss(n),x=A?l==="y"?A.clientHeight||0:A.clientWidth||0:0,b=p/2-m/2,y=h[f],T=x-u[d]-h[g],E=x/2-u[d]/2+b,S=rs(y,E,T),R=l;t.modifiersData[i]=(e={},e[R]=S,e.centerOffset=S-E,e)}}function r0(r){var e=r.state,t=r.options,i=t.element,s=i===void 0?"[data-popper-arrow]":i;s!=null&&(typeof s=="string"&&(s=e.elements.popper.querySelector(s),!s)||Ml(e.elements.popper,s)&&(e.elements.arrow=s))}const n0={name:"arrow",enabled:!0,phase:"main",fn:s0,effect:r0,requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function Ei(r){return r.split("-")[1]}var o0={top:"auto",right:"auto",bottom:"auto",left:"auto"};function a0(r,e){var t=r.x,i=r.y,s=e.devicePixelRatio||1;return{x:xi(t*s)/s||0,y:xi(i*s)/s||0}}function Hl(r){var e,t=r.popper,i=r.popperRect,s=r.placement,n=r.variation,o=r.offsets,a=r.position,l=r.gpuAcceleration,c=r.adaptive,d=r.roundOffsets,h=r.isFixed,u=o.x,f=u===void 0?0:u,g=o.y,p=g===void 0?0:g,m=typeof d=="function"?d({x:f,y:p}):{x:f,y:p};f=m.x,p=m.y;var A=o.hasOwnProperty("x"),x=o.hasOwnProperty("y"),b=qe,y=Xe,T=window;if(c){var E=ss(t),S="clientHeight",R="clientWidth";if(E===Qe(t)&&(E=Gt(t),kt(E).position!=="static"&&a==="absolute"&&(S="scrollHeight",R="scrollWidth")),E=E,s===Xe||(s===qe||s===it)&&n===ts){y=tt;var w=h&&E===T&&T.visualViewport?T.visualViewport.height:E[S];p-=w-i.height,p*=l?1:-1}if(s===qe||(s===Xe||s===tt)&&n===ts){b=it;var I=h&&E===T&&T.visualViewport?T.visualViewport.width:E[R];f-=I-i.width,f*=l?1:-1}}var O=Object.assign({position:a},c&&o0),P=d===!0?a0({x:f,y:p},Qe(t)):{x:f,y:p};if(f=P.x,p=P.y,l){var B;return Object.assign({},O,(B={},B[y]=x?"0":"",B[b]=A?"0":"",B.transform=(T.devicePixelRatio||1)<=1?"translate("+f+"px, "+p+"px)":"translate3d("+f+"px, "+p+"px, 0)",B))}return Object.assign({},O,(e={},e[y]=x?p+"px":"",e[b]=A?f+"px":"",e.transform="",e))}function l0(r){var e=r.state,t=r.options,i=t.gpuAcceleration,s=i===void 0?!0:i,n=t.adaptive,o=n===void 0?!0:n,a=t.roundOffsets,l=a===void 0?!0:a,c={placement:vt(e.placement),variation:Ei(e.placement),popper:e.elements.popper,popperRect:e.rects.popper,gpuAcceleration:s,isFixed:e.options.strategy==="fixed"};e.modifiersData.popperOffsets!=null&&(e.styles.popper=Object.assign({},e.styles.popper,Hl(Object.assign({},c,{offsets:e.modifiersData.popperOffsets,position:e.options.strategy,adaptive:o,roundOffsets:l})))),e.modifiersData.arrow!=null&&(e.styles.arrow=Object.assign({},e.styles.arrow,Hl(Object.assign({},c,{offsets:e.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-placement":e.placement})}const c0={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:l0,data:{}};var Ys={passive:!0};function d0(r){var e=r.state,t=r.instance,i=r.options,s=i.scroll,n=s===void 0?!0:s,o=i.resize,a=o===void 0?!0:o,l=Qe(e.elements.popper),c=[].concat(e.scrollParents.reference,e.scrollParents.popper);return n&&c.forEach(function(d){d.addEventListener("scroll",t.update,Ys)}),a&&l.addEventListener("resize",t.update,Ys),function(){n&&c.forEach(function(d){d.removeEventListener("scroll",t.update,Ys)}),a&&l.removeEventListener("resize",t.update,Ys)}}const h0={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:d0,data:{}};var u0={left:"right",right:"left",bottom:"top",top:"bottom"};function Ks(r){return r.replace(/left|right|bottom|top/g,function(e){return u0[e]})}var f0={start:"end",end:"start"};function Gl(r){return r.replace(/start|end/g,function(e){return f0[e]})}function Rn(r){var e=Qe(r),t=e.pageXOffset,i=e.pageYOffset;return{scrollLeft:t,scrollTop:i}}function Dn(r){return Ti(Gt(r)).left+Rn(r).scrollLeft}function g0(r,e){var t=Qe(r),i=Gt(r),s=t.visualViewport,n=i.clientWidth,o=i.clientHeight,a=0,l=0;if(s){n=s.width,o=s.height;var c=Ol();(c||!c&&e==="fixed")&&(a=s.offsetLeft,l=s.offsetTop)}return{width:n,height:o,x:a+Dn(r),y:l}}function p0(r){var e,t=Gt(r),i=Rn(r),s=(e=r.ownerDocument)==null?void 0:e.body,n=ii(t.scrollWidth,t.clientWidth,s?s.scrollWidth:0,s?s.clientWidth:0),o=ii(t.scrollHeight,t.clientHeight,s?s.scrollHeight:0,s?s.clientHeight:0),a=-i.scrollLeft+Dn(r),l=-i.scrollTop;return kt(s||t).direction==="rtl"&&(a+=ii(t.clientWidth,s?s.clientWidth:0)-n),{width:n,height:o,x:a,y:l}}function kn(r){var e=kt(r),t=e.overflow,i=e.overflowX,s=e.overflowY;return/auto|scroll|overlay|hidden/.test(t+s+i)}function Vl(r){return["html","body","#document"].indexOf(mt(r))>=0?r.ownerDocument.body:st(r)&&kn(r)?r:Vl(Ws(r))}function ns(r,e){var t;e===void 0&&(e=[]);var i=Vl(r),s=i===((t=r.ownerDocument)==null?void 0:t.body),n=Qe(i),o=s?[n].concat(n.visualViewport||[],kn(i)?i:[]):i,a=e.concat(o);return s?a:a.concat(ns(Ws(o)))}function Pn(r){return Object.assign({},r,{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height})}function m0(r,e){var t=Ti(r,!1,e==="fixed");return t.top=t.top+r.clientTop,t.left=t.left+r.clientLeft,t.bottom=t.top+r.clientHeight,t.right=t.left+r.clientWidth,t.width=r.clientWidth,t.height=r.clientHeight,t.x=t.left,t.y=t.top,t}function jl(r,e,t){return e===Rl?Pn(g0(r,t)):ti(e)?m0(e,t):Pn(p0(Gt(r)))}function v0(r){var e=ns(Ws(r)),t=["absolute","fixed"].indexOf(kt(r).position)>=0,i=t&&st(r)?ss(r):r;return ti(i)?e.filter(function(s){return ti(s)&&Ml(s,i)&&mt(s)!=="body"}):[]}function y0(r,e,t,i){var s=e==="clippingParents"?v0(r):[].concat(e),n=[].concat(s,[t]),o=n[0],a=n.reduce(function(l,c){var d=jl(r,c,i);return l.top=ii(d.top,l.top),l.right=zs(d.right,l.right),l.bottom=zs(d.bottom,l.bottom),l.left=ii(d.left,l.left),l},jl(r,o,i));return a.width=a.right-a.left,a.height=a.bottom-a.top,a.x=a.left,a.y=a.top,a}function zl(r){var e=r.reference,t=r.element,i=r.placement,s=i?vt(i):null,n=i?Ei(i):null,o=e.x+e.width/2-t.width/2,a=e.y+e.height/2-t.height/2,l;switch(s){case Xe:l={x:o,y:e.y-t.height};break;case tt:l={x:o,y:e.y+e.height};break;case it:l={x:e.x+e.width,y:a};break;case qe:l={x:e.x-t.width,y:a};break;default:l={x:e.x,y:e.y}}var c=s?Ln(s):null;if(c!=null){var d=c==="y"?"height":"width";switch(n){case bi:l[c]=l[c]-(e[d]/2-t[d]/2);break;case ts:l[c]=l[c]+(e[d]/2-t[d]/2);break}}return l}function os(r,e){e===void 0&&(e={});var t=e,i=t.placement,s=i===void 0?r.placement:i,n=t.strategy,o=n===void 0?r.strategy:n,a=t.boundary,l=a===void 0?Hf:a,c=t.rootBoundary,d=c===void 0?Rl:c,h=t.elementContext,u=h===void 0?is:h,f=t.altBoundary,g=f===void 0?!1:f,p=t.padding,m=p===void 0?0:p,A=Bl(typeof m!="number"?m:Ul(m,es)),x=u===is?Gf:is,b=r.rects.popper,y=r.elements[g?x:u],T=y0(ti(y)?y:y.contextElement||Gt(r.elements.popper),l,d,o),E=Ti(r.elements.reference),S=zl({reference:E,element:b,strategy:"absolute",placement:s}),R=Pn(Object.assign({},b,S)),w=u===is?R:E,I={top:T.top-w.top+A.top,bottom:w.bottom-T.bottom+A.bottom,left:T.left-w.left+A.left,right:w.right-T.right+A.right},O=r.modifiersData.offset;if(u===is&&O){var P=O[s];Object.keys(I).forEach(function(B){var J=[it,tt].indexOf(B)>=0?1:-1,H=[Xe,tt].indexOf(B)>=0?"y":"x";I[B]+=P[H]*J})}return I}function A0(r,e){e===void 0&&(e={});var t=e,i=t.placement,s=t.boundary,n=t.rootBoundary,o=t.padding,a=t.flipVariations,l=t.allowedAutoPlacements,c=l===void 0?kl:l,d=Ei(i),h=d?a?Dl:Dl.filter(function(g){return Ei(g)===d}):es,u=h.filter(function(g){return c.indexOf(g)>=0});u.length===0&&(u=h);var f=u.reduce(function(g,p){return g[p]=os(r,{placement:p,boundary:s,rootBoundary:n,padding:o})[vt(p)],g},{});return Object.keys(f).sort(function(g,p){return f[g]-f[p]})}function b0(r){if(vt(r)===Sn)return[];var e=Ks(r);return[Gl(r),e,Gl(e)]}function x0(r){var e=r.state,t=r.options,i=r.name;if(!e.modifiersData[i]._skip){for(var s=t.mainAxis,n=s===void 0?!0:s,o=t.altAxis,a=o===void 0?!0:o,l=t.fallbackPlacements,c=t.padding,d=t.boundary,h=t.rootBoundary,u=t.altBoundary,f=t.flipVariations,g=f===void 0?!0:f,p=t.allowedAutoPlacements,m=e.options.placement,A=vt(m),x=A===m,b=l||(x||!g?[Ks(m)]:b0(m)),y=[m].concat(b).reduce(function(X,ie){return X.concat(vt(ie)===Sn?A0(e,{placement:ie,boundary:d,rootBoundary:h,padding:c,flipVariations:g,allowedAutoPlacements:p}):ie)},[]),T=e.rects.reference,E=e.rects.popper,S=new Map,R=!0,w=y[0],I=0;I<y.length;I++){var O=y[I],P=vt(O),B=Ei(O)===bi,J=[Xe,tt].indexOf(P)>=0,H=J?"width":"height",V=os(e,{placement:O,boundary:d,rootBoundary:h,altBoundary:u,padding:c}),j=J?B?it:qe:B?tt:Xe;T[H]>E[H]&&(j=Ks(j));var F=Ks(j),U=[];if(n&&U.push(V[P]<=0),a&&U.push(V[j]<=0,V[F]<=0),U.every(function(X){return X})){w=O,R=!1;break}S.set(O,U)}if(R)for(var Q=g?3:1,Y=function(ie){var ee=y.find(function(ne){var se=S.get(ne);if(se)return se.slice(0,ie).every(function(ye){return ye})});if(ee)return w=ee,"break"},z=Q;z>0;z--){var K=Y(z);if(K==="break")break}e.placement!==w&&(e.modifiersData[i]._skip=!0,e.placement=w,e.reset=!0)}}const T0={name:"flip",enabled:!0,phase:"main",fn:x0,requiresIfExists:["offset"],data:{_skip:!1}};function Wl(r,e,t){return t===void 0&&(t={x:0,y:0}),{top:r.top-e.height-t.y,right:r.right-e.width+t.x,bottom:r.bottom-e.height+t.y,left:r.left-e.width-t.x}}function Yl(r){return[Xe,it,tt,qe].some(function(e){return r[e]>=0})}function E0(r){var e=r.state,t=r.name,i=e.rects.reference,s=e.rects.popper,n=e.modifiersData.preventOverflow,o=os(e,{elementContext:"reference"}),a=os(e,{altBoundary:!0}),l=Wl(o,i),c=Wl(a,s,n),d=Yl(l),h=Yl(c);e.modifiersData[t]={referenceClippingOffsets:l,popperEscapeOffsets:c,isReferenceHidden:d,hasPopperEscaped:h},e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-reference-hidden":d,"data-popper-escaped":h})}const S0={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:E0};function I0(r,e,t){var i=vt(r),s=[qe,Xe].indexOf(i)>=0?-1:1,n=typeof t=="function"?t(Object.assign({},e,{placement:r})):t,o=n[0],a=n[1];return o=o||0,a=(a||0)*s,[qe,it].indexOf(i)>=0?{x:a,y:o}:{x:o,y:a}}function C0(r){var e=r.state,t=r.options,i=r.name,s=t.offset,n=s===void 0?[0,0]:s,o=kl.reduce(function(d,h){return d[h]=I0(h,e.rects,n),d},{}),a=o[e.placement],l=a.x,c=a.y;e.modifiersData.popperOffsets!=null&&(e.modifiersData.popperOffsets.x+=l,e.modifiersData.popperOffsets.y+=c),e.modifiersData[i]=o}const w0={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:C0};function L0(r){var e=r.state,t=r.name;e.modifiersData[t]=zl({reference:e.rects.reference,element:e.rects.popper,strategy:"absolute",placement:e.placement})}const R0={name:"popperOffsets",enabled:!0,phase:"read",fn:L0,data:{}};function D0(r){return r==="x"?"y":"x"}function k0(r){var e=r.state,t=r.options,i=r.name,s=t.mainAxis,n=s===void 0?!0:s,o=t.altAxis,a=o===void 0?!1:o,l=t.boundary,c=t.rootBoundary,d=t.altBoundary,h=t.padding,u=t.tether,f=u===void 0?!0:u,g=t.tetherOffset,p=g===void 0?0:g,m=os(e,{boundary:l,rootBoundary:c,padding:h,altBoundary:d}),A=vt(e.placement),x=Ei(e.placement),b=!x,y=Ln(A),T=D0(y),E=e.modifiersData.popperOffsets,S=e.rects.reference,R=e.rects.popper,w=typeof p=="function"?p(Object.assign({},e.rects,{placement:e.placement})):p,I=typeof w=="number"?{mainAxis:w,altAxis:w}:Object.assign({mainAxis:0,altAxis:0},w),O=e.modifiersData.offset?e.modifiersData.offset[e.placement]:null,P={x:0,y:0};if(E){if(n){var B,J=y==="y"?Xe:qe,H=y==="y"?tt:it,V=y==="y"?"height":"width",j=E[y],F=j+m[J],U=j-m[H],Q=f?-R[V]/2:0,Y=x===bi?S[V]:R[V],z=x===bi?-R[V]:-S[V],K=e.elements.arrow,X=f&&K?wn(K):{width:0,height:0},ie=e.modifiersData["arrow#persistent"]?e.modifiersData["arrow#persistent"].padding:Nl(),ee=ie[J],ne=ie[H],se=rs(0,S[V],X[V]),ye=b?S[V]/2-Q-se-ee-I.mainAxis:Y-se-ee-I.mainAxis,he=b?-S[V]/2+Q+se+ne+I.mainAxis:z+se+ne+I.mainAxis,_e=e.elements.arrow&&ss(e.elements.arrow),Pt=_e?y==="y"?_e.clientTop||0:_e.clientLeft||0:0,Tt=(B=O==null?void 0:O[y])!=null?B:0,Ot=j+ye-Tt-Pt,Te=j+he-Tt,Ae=rs(f?zs(F,Ot):F,j,f?ii(U,Te):U);E[y]=Ae,P[y]=Ae-j}if(a){var Ue,ue=y==="x"?Xe:qe,be=y==="x"?tt:it,Le=E[T],He=T==="y"?"height":"width",Mt=Le+m[ue],Ft=Le-m[be],oi=[Xe,qe].indexOf(A)!==-1,Di=(Ue=O==null?void 0:O[T])!=null?Ue:0,ki=oi?Mt:Le-S[He]-R[He]-Di+I.altAxis,Pi=oi?Le+S[He]+R[He]-Di-I.altAxis:Ft,or=f&&oi?t0(ki,Le,Pi):rs(f?ki:Mt,Le,f?Pi:Ft);E[T]=or,P[T]=or-Le}e.modifiersData[i]=P}}const P0={name:"preventOverflow",enabled:!0,phase:"main",fn:k0,requiresIfExists:["offset"]};function O0(r){return{scrollLeft:r.scrollLeft,scrollTop:r.scrollTop}}function M0(r){return r===Qe(r)||!st(r)?Rn(r):O0(r)}function F0(r){var e=r.getBoundingClientRect(),t=xi(e.width)/r.offsetWidth||1,i=xi(e.height)/r.offsetHeight||1;return t!==1||i!==1}function N0(r,e,t){t===void 0&&(t=!1);var i=st(e),s=st(e)&&F0(e),n=Gt(e),o=Ti(r,s,t),a={scrollLeft:0,scrollTop:0},l={x:0,y:0};return(i||!i&&!t)&&((mt(e)!=="body"||kn(n))&&(a=M0(e)),st(e)?(l=Ti(e,!0),l.x+=e.clientLeft,l.y+=e.clientTop):n&&(l.x=Dn(n))),{x:o.left+a.scrollLeft-l.x,y:o.top+a.scrollTop-l.y,width:o.width,height:o.height}}function B0(r){var e=new Map,t=new Set,i=[];r.forEach(function(n){e.set(n.name,n)});function s(n){t.add(n.name);var o=[].concat(n.requires||[],n.requiresIfExists||[]);o.forEach(function(a){if(!t.has(a)){var l=e.get(a);l&&s(l)}}),i.push(n)}return r.forEach(function(n){t.has(n.name)||s(n)}),i}function U0(r){var e=B0(r);return Jf.reduce(function(t,i){return t.concat(e.filter(function(s){return s.phase===i}))},[])}function H0(r){var e;return function(){return e||(e=new Promise(function(t){Promise.resolve().then(function(){e=void 0,t(r())})})),e}}function G0(r){var e=r.reduce(function(t,i){var s=t[i.name];return t[i.name]=s?Object.assign({},s,i,{options:Object.assign({},s.options,i.options),data:Object.assign({},s.data,i.data)}):i,t},{});return Object.keys(e).map(function(t){return e[t]})}var Kl={placement:"bottom",modifiers:[],strategy:"absolute"};function Xl(){for(var r=arguments.length,e=new Array(r),t=0;t<r;t++)e[t]=arguments[t];return!e.some(function(i){return!(i&&typeof i.getBoundingClientRect=="function")})}function V0(r){r===void 0&&(r={});var e=r,t=e.defaultModifiers,i=t===void 0?[]:t,s=e.defaultOptions,n=s===void 0?Kl:s;return function(a,l,c){c===void 0&&(c=n);var d={placement:"bottom",orderedModifiers:[],options:Object.assign({},Kl,n),modifiersData:{},elements:{reference:a,popper:l},attributes:{},styles:{}},h=[],u=!1,f={state:d,setOptions:function(A){var x=typeof A=="function"?A(d.options):A;p(),d.options=Object.assign({},n,d.options,x),d.scrollParents={reference:ti(a)?ns(a):a.contextElement?ns(a.contextElement):[],popper:ns(l)};var b=U0(G0([].concat(i,d.options.modifiers)));return d.orderedModifiers=b.filter(function(y){return y.enabled}),g(),f.update()},forceUpdate:function(){if(!u){var A=d.elements,x=A.reference,b=A.popper;if(Xl(x,b)){d.rects={reference:N0(x,ss(b),d.options.strategy==="fixed"),popper:wn(b)},d.reset=!1,d.placement=d.options.placement,d.orderedModifiers.forEach(function(I){return d.modifiersData[I.name]=Object.assign({},I.data)});for(var y=0;y<d.orderedModifiers.length;y++){if(d.reset===!0){d.reset=!1,y=-1;continue}var T=d.orderedModifiers[y],E=T.fn,S=T.options,R=S===void 0?{}:S,w=T.name;typeof E=="function"&&(d=E({state:d,options:R,name:w,instance:f})||d)}}}},update:H0(function(){return new Promise(function(m){f.forceUpdate(),m(d)})}),destroy:function(){p(),u=!0}};if(!Xl(a,l))return f;f.setOptions(c).then(function(m){!u&&c.onFirstUpdate&&c.onFirstUpdate(m)});function g(){d.orderedModifiers.forEach(function(m){var A=m.name,x=m.options,b=x===void 0?{}:x,y=m.effect;if(typeof y=="function"){var T=y({state:d,name:A,instance:f,options:b}),E=function(){};h.push(T||E)}})}function p(){h.forEach(function(m){return m()}),h=[]}return f}}var j0=[h0,R0,c0,Pl,w0,T0,P0,n0,S0],z0=V0({defaultModifiers:j0}),W0="tippy-box",ql="tippy-content",Y0="tippy-backdrop",Zl="tippy-arrow",Jl="tippy-svg-arrow",si={passive:!0,capture:!0},Ql=function(){return document.body};function On(r,e,t){if(Array.isArray(r)){var i=r[e];return i??(Array.isArray(t)?t[e]:t)}return r}function Mn(r,e){var t={}.toString.call(r);return t.indexOf("[object")===0&&t.indexOf(e+"]")>-1}function _l(r,e){return typeof r=="function"?r.apply(void 0,e):r}function $l(r,e){if(e===0)return r;var t;return function(i){clearTimeout(t),t=setTimeout(function(){r(i)},e)}}function K0(r){return r.split(/\s+/).filter(Boolean)}function Si(r){return[].concat(r)}function ec(r,e){r.indexOf(e)===-1&&r.push(e)}function X0(r){return r.filter(function(e,t){return r.indexOf(e)===t})}function q0(r){return r.split("-")[0]}function Xs(r){return[].slice.call(r)}function tc(r){return Object.keys(r).reduce(function(e,t){return r[t]!==void 0&&(e[t]=r[t]),e},{})}function as(){return document.createElement("div")}function qs(r){return["Element","Fragment"].some(function(e){return Mn(r,e)})}function Z0(r){return Mn(r,"NodeList")}function J0(r){return Mn(r,"MouseEvent")}function Q0(r){return!!(r&&r._tippy&&r._tippy.reference===r)}function _0(r){return qs(r)?[r]:Z0(r)?Xs(r):Array.isArray(r)?r:Xs(document.querySelectorAll(r))}function Fn(r,e){r.forEach(function(t){t&&(t.style.transitionDuration=e+"ms")})}function ic(r,e){r.forEach(function(t){t&&t.setAttribute("data-state",e)})}function $0(r){var e,t=Si(r),i=t[0];return i!=null&&(e=i.ownerDocument)!=null&&e.body?i.ownerDocument:document}function eg(r,e){var t=e.clientX,i=e.clientY;return r.every(function(s){var n=s.popperRect,o=s.popperState,a=s.props,l=a.interactiveBorder,c=q0(o.placement),d=o.modifiersData.offset;if(!d)return!0;var h=c==="bottom"?d.top.y:0,u=c==="top"?d.bottom.y:0,f=c==="right"?d.left.x:0,g=c==="left"?d.right.x:0,p=n.top-i+h>l,m=i-n.bottom-u>l,A=n.left-t+f>l,x=t-n.right-g>l;return p||m||A||x})}function Nn(r,e,t){var i=e+"EventListener";["transitionend","webkitTransitionEnd"].forEach(function(s){r[i](s,t)})}function sc(r,e){for(var t=e;t;){var i;if(r.contains(t))return!0;t=t.getRootNode==null||(i=t.getRootNode())==null?void 0:i.host}return!1}var yt={isTouch:!1},rc=0;function tg(){yt.isTouch||(yt.isTouch=!0,window.performance&&document.addEventListener("mousemove",nc))}function nc(){var r=performance.now();r-rc<20&&(yt.isTouch=!1,document.removeEventListener("mousemove",nc)),rc=r}function ig(){var r=document.activeElement;if(Q0(r)){var e=r._tippy;r.blur&&!e.state.isVisible&&r.blur()}}function sg(){document.addEventListener("touchstart",tg,si),window.addEventListener("blur",ig)}var rg=typeof window<"u"&&typeof document<"u",ng=rg?!!window.msCrypto:!1,og={animateFill:!1,followCursor:!1,inlinePositioning:!1,sticky:!1},ag={allowHTML:!1,animation:"fade",arrow:!0,content:"",inertia:!1,maxWidth:350,role:"tooltip",theme:"",zIndex:9999},ht=Object.assign({appendTo:Ql,aria:{content:"auto",expanded:"auto"},delay:0,duration:[300,250],getReferenceClientRect:null,hideOnClick:!0,ignoreAttributes:!1,interactive:!1,interactiveBorder:2,interactiveDebounce:0,moveTransition:"",offset:[0,10],onAfterUpdate:function(){},onBeforeUpdate:function(){},onCreate:function(){},onDestroy:function(){},onHidden:function(){},onHide:function(){},onMount:function(){},onShow:function(){},onShown:function(){},onTrigger:function(){},onUntrigger:function(){},onClickOutside:function(){},placement:"top",plugins:[],popperOptions:{},render:null,showOnCreate:!1,touch:!0,trigger:"mouseenter focus",triggerTarget:null},og,ag),lg=Object.keys(ht),cg=function(e){var t=Object.keys(e);t.forEach(function(i){ht[i]=e[i]})};function oc(r){var e=r.plugins||[],t=e.reduce(function(i,s){var n=s.name,o=s.defaultValue;if(n){var a;i[n]=r[n]!==void 0?r[n]:(a=ht[n])!=null?a:o}return i},{});return Object.assign({},r,t)}function dg(r,e){var t=e?Object.keys(oc(Object.assign({},ht,{plugins:e}))):lg,i=t.reduce(function(s,n){var o=(r.getAttribute("data-tippy-"+n)||"").trim();if(!o)return s;if(n==="content")s[n]=o;else try{s[n]=JSON.parse(o)}catch{s[n]=o}return s},{});return i}function ac(r,e){var t=Object.assign({},e,{content:_l(e.content,[r])},e.ignoreAttributes?{}:dg(r,e.plugins));return t.aria=Object.assign({},ht.aria,t.aria),t.aria={expanded:t.aria.expanded==="auto"?e.interactive:t.aria.expanded,content:t.aria.content==="auto"?e.interactive?null:"describedby":t.aria.content},t}var hg=function(){return"innerHTML"};function Bn(r,e){r[hg()]=e}function lc(r){var e=as();return r===!0?e.className=Zl:(e.className=Jl,qs(r)?e.appendChild(r):Bn(e,r)),e}function cc(r,e){qs(e.content)?(Bn(r,""),r.appendChild(e.content)):typeof e.content!="function"&&(e.allowHTML?Bn(r,e.content):r.textContent=e.content)}function Un(r){var e=r.firstElementChild,t=Xs(e.children);return{box:e,content:t.find(function(i){return i.classList.contains(ql)}),arrow:t.find(function(i){return i.classList.contains(Zl)||i.classList.contains(Jl)}),backdrop:t.find(function(i){return i.classList.contains(Y0)})}}function dc(r){var e=as(),t=as();t.className=W0,t.setAttribute("data-state","hidden"),t.setAttribute("tabindex","-1");var i=as();i.className=ql,i.setAttribute("data-state","hidden"),cc(i,r.props),e.appendChild(t),t.appendChild(i),s(r.props,r.props);function s(n,o){var a=Un(e),l=a.box,c=a.content,d=a.arrow;o.theme?l.setAttribute("data-theme",o.theme):l.removeAttribute("data-theme"),typeof o.animation=="string"?l.setAttribute("data-animation",o.animation):l.removeAttribute("data-animation"),o.inertia?l.setAttribute("data-inertia",""):l.removeAttribute("data-inertia"),l.style.maxWidth=typeof o.maxWidth=="number"?o.maxWidth+"px":o.maxWidth,o.role?l.setAttribute("role",o.role):l.removeAttribute("role"),(n.content!==o.content||n.allowHTML!==o.allowHTML)&&cc(c,r.props),o.arrow?d?n.arrow!==o.arrow&&(l.removeChild(d),l.appendChild(lc(o.arrow))):l.appendChild(lc(o.arrow)):d&&l.removeChild(d)}return{popper:e,onUpdate:s}}dc.$$tippy=!0;var ug=1,Zs=[],Hn=[];function fg(r,e){var t=ac(r,Object.assign({},ht,oc(tc(e)))),i,s,n,o=!1,a=!1,l=!1,c=!1,d,h,u,f=[],g=$l(Ot,t.interactiveDebounce),p,m=ug++,A=null,x=X0(t.plugins),b={isEnabled:!0,isVisible:!1,isDestroyed:!1,isMounted:!1,isShown:!1},y={id:m,reference:r,popper:as(),popperInstance:A,props:t,state:b,plugins:x,clearDelayTimeouts:ki,setProps:Pi,setContent:or,show:fm,hide:gm,hideWithInteractivity:pm,enable:oi,disable:Di,unmount:mm,destroy:vm};if(!t.render)return y;var T=t.render(y),E=T.popper,S=T.onUpdate;E.setAttribute("data-tippy-root",""),E.id="tippy-"+y.id,y.popper=E,r._tippy=y,E._tippy=y;var R=x.map(function(k){return k.fn(y)}),w=r.hasAttribute("aria-expanded");return _e(),Q(),j(),F("onCreate",[y]),t.showOnCreate&&Mt(),E.addEventListener("mouseenter",function(){y.props.interactive&&y.state.isVisible&&y.clearDelayTimeouts()}),E.addEventListener("mouseleave",function(){y.props.interactive&&y.props.trigger.indexOf("mouseenter")>=0&&J().addEventListener("mousemove",g)}),y;function I(){var k=y.props.touch;return Array.isArray(k)?k:[k,0]}function O(){return I()[0]==="hold"}function P(){var k;return!!((k=y.props.render)!=null&&k.$$tippy)}function B(){return p||r}function J(){var k=B().parentNode;return k?$0(k):document}function H(){return Un(E)}function V(k){return y.state.isMounted&&!y.state.isVisible||yt.isTouch||d&&d.type==="focus"?0:On(y.props.delay,k?0:1,ht.delay)}function j(k){k===void 0&&(k=!1),E.style.pointerEvents=y.props.interactive&&!k?"":"none",E.style.zIndex=""+y.props.zIndex}function F(k,G,$){if($===void 0&&($=!0),R.forEach(function(oe){oe[k]&&oe[k].apply(oe,G)}),$){var ce;(ce=y.props)[k].apply(ce,G)}}function U(){var k=y.props.aria;if(k.content){var G="aria-"+k.content,$=E.id,ce=Si(y.props.triggerTarget||r);ce.forEach(function(oe){var Ve=oe.getAttribute(G);if(y.state.isVisible)oe.setAttribute(G,Ve?Ve+" "+$:$);else{var rt=Ve&&Ve.replace($,"").trim();rt?oe.setAttribute(G,rt):oe.removeAttribute(G)}})}}function Q(){if(!(w||!y.props.aria.expanded)){var k=Si(y.props.triggerTarget||r);k.forEach(function(G){y.props.interactive?G.setAttribute("aria-expanded",y.state.isVisible&&G===B()?"true":"false"):G.removeAttribute("aria-expanded")})}}function Y(){J().removeEventListener("mousemove",g),Zs=Zs.filter(function(k){return k!==g})}function z(k){if(!(yt.isTouch&&(l||k.type==="mousedown"))){var G=k.composedPath&&k.composedPath()[0]||k.target;if(!(y.props.interactive&&sc(E,G))){if(Si(y.props.triggerTarget||r).some(function($){return sc($,G)})){if(yt.isTouch||y.state.isVisible&&y.props.trigger.indexOf("click")>=0)return}else F("onClickOutside",[y,k]);y.props.hideOnClick===!0&&(y.clearDelayTimeouts(),y.hide(),a=!0,setTimeout(function(){a=!1}),y.state.isMounted||ee())}}}function K(){l=!0}function X(){l=!1}function ie(){var k=J();k.addEventListener("mousedown",z,!0),k.addEventListener("touchend",z,si),k.addEventListener("touchstart",X,si),k.addEventListener("touchmove",K,si)}function ee(){var k=J();k.removeEventListener("mousedown",z,!0),k.removeEventListener("touchend",z,si),k.removeEventListener("touchstart",X,si),k.removeEventListener("touchmove",K,si)}function ne(k,G){ye(k,function(){!y.state.isVisible&&E.parentNode&&E.parentNode.contains(E)&&G()})}function se(k,G){ye(k,G)}function ye(k,G){var $=H().box;function ce(oe){oe.target===$&&(Nn($,"remove",ce),G())}if(k===0)return G();Nn($,"remove",h),Nn($,"add",ce),h=ce}function he(k,G,$){$===void 0&&($=!1);var ce=Si(y.props.triggerTarget||r);ce.forEach(function(oe){oe.addEventListener(k,G,$),f.push({node:oe,eventType:k,handler:G,options:$})})}function _e(){O()&&(he("touchstart",Tt,{passive:!0}),he("touchend",Te,{passive:!0})),K0(y.props.trigger).forEach(function(k){if(k!=="manual")switch(he(k,Tt),k){case"mouseenter":he("mouseleave",Te);break;case"focus":he(ng?"focusout":"blur",Ae);break;case"focusin":he("focusout",Ae);break}})}function Pt(){f.forEach(function(k){var G=k.node,$=k.eventType,ce=k.handler,oe=k.options;G.removeEventListener($,ce,oe)}),f=[]}function Tt(k){var G,$=!1;if(!(!y.state.isEnabled||Ue(k)||a)){var ce=((G=d)==null?void 0:G.type)==="focus";d=k,p=k.currentTarget,Q(),!y.state.isVisible&&J0(k)&&Zs.forEach(function(oe){return oe(k)}),k.type==="click"&&(y.props.trigger.indexOf("mouseenter")<0||o)&&y.props.hideOnClick!==!1&&y.state.isVisible?$=!0:Mt(k),k.type==="click"&&(o=!$),$&&!ce&&Ft(k)}}function Ot(k){var G=k.target,$=B().contains(G)||E.contains(G);if(!(k.type==="mousemove"&&$)){var ce=He().concat(E).map(function(oe){var Ve,rt=oe._tippy,Oi=(Ve=rt.popperInstance)==null?void 0:Ve.state;return Oi?{popperRect:oe.getBoundingClientRect(),popperState:Oi,props:t}:null}).filter(Boolean);eg(ce,k)&&(Y(),Ft(k))}}function Te(k){var G=Ue(k)||y.props.trigger.indexOf("click")>=0&&o;if(!G){if(y.props.interactive){y.hideWithInteractivity(k);return}Ft(k)}}function Ae(k){y.props.trigger.indexOf("focusin")<0&&k.target!==B()||y.props.interactive&&k.relatedTarget&&E.contains(k.relatedTarget)||Ft(k)}function Ue(k){return yt.isTouch?O()!==k.type.indexOf("touch")>=0:!1}function ue(){be();var k=y.props,G=k.popperOptions,$=k.placement,ce=k.offset,oe=k.getReferenceClientRect,Ve=k.moveTransition,rt=P()?Un(E).arrow:null,Oi=oe?{getBoundingClientRect:oe,contextElement:oe.contextElement||B()}:r,Dc={name:"$$tippy",enabled:!0,phase:"beforeWrite",requires:["computeStyles"],fn:function(ar){var Mi=ar.state;if(P()){var ym=H(),eo=ym.box;["placement","reference-hidden","escaped"].forEach(function(lr){lr==="placement"?eo.setAttribute("data-placement",Mi.placement):Mi.attributes.popper["data-popper-"+lr]?eo.setAttribute("data-"+lr,""):eo.removeAttribute("data-"+lr)}),Mi.attributes.popper={}}}},ai=[{name:"offset",options:{offset:ce}},{name:"preventOverflow",options:{padding:{top:2,bottom:2,left:5,right:5}}},{name:"flip",options:{padding:5}},{name:"computeStyles",options:{adaptive:!Ve}},Dc];P()&&rt&&ai.push({name:"arrow",options:{element:rt,padding:3}}),ai.push.apply(ai,(G==null?void 0:G.modifiers)||[]),y.popperInstance=z0(Oi,E,Object.assign({},G,{placement:$,onFirstUpdate:u,modifiers:ai}))}function be(){y.popperInstance&&(y.popperInstance.destroy(),y.popperInstance=null)}function Le(){var k=y.props.appendTo,G,$=B();y.props.interactive&&k===Ql||k==="parent"?G=$.parentNode:G=_l(k,[$]),G.contains(E)||G.appendChild(E),y.state.isMounted=!0,ue()}function He(){return Xs(E.querySelectorAll("[data-tippy-root]"))}function Mt(k){y.clearDelayTimeouts(),k&&F("onTrigger",[y,k]),ie();var G=V(!0),$=I(),ce=$[0],oe=$[1];yt.isTouch&&ce==="hold"&&oe&&(G=oe),G?i=setTimeout(function(){y.show()},G):y.show()}function Ft(k){if(y.clearDelayTimeouts(),F("onUntrigger",[y,k]),!y.state.isVisible){ee();return}if(!(y.props.trigger.indexOf("mouseenter")>=0&&y.props.trigger.indexOf("click")>=0&&["mouseleave","mousemove"].indexOf(k.type)>=0&&o)){var G=V(!1);G?s=setTimeout(function(){y.state.isVisible&&y.hide()},G):n=requestAnimationFrame(function(){y.hide()})}}function oi(){y.state.isEnabled=!0}function Di(){y.hide(),y.state.isEnabled=!1}function ki(){clearTimeout(i),clearTimeout(s),cancelAnimationFrame(n)}function Pi(k){if(!y.state.isDestroyed){F("onBeforeUpdate",[y,k]),Pt();var G=y.props,$=ac(r,Object.assign({},G,tc(k),{ignoreAttributes:!0}));y.props=$,_e(),G.interactiveDebounce!==$.interactiveDebounce&&(Y(),g=$l(Ot,$.interactiveDebounce)),G.triggerTarget&&!$.triggerTarget?Si(G.triggerTarget).forEach(function(ce){ce.removeAttribute("aria-expanded")}):$.triggerTarget&&r.removeAttribute("aria-expanded"),Q(),j(),S&&S(G,$),y.popperInstance&&(ue(),He().forEach(function(ce){requestAnimationFrame(ce._tippy.popperInstance.forceUpdate)})),F("onAfterUpdate",[y,k])}}function or(k){y.setProps({content:k})}function fm(){var k=y.state.isVisible,G=y.state.isDestroyed,$=!y.state.isEnabled,ce=yt.isTouch&&!y.props.touch,oe=On(y.props.duration,0,ht.duration);if(!(k||G||$||ce)&&!B().hasAttribute("disabled")&&(F("onShow",[y],!1),y.props.onShow(y)!==!1)){if(y.state.isVisible=!0,P()&&(E.style.visibility="visible"),j(),ie(),y.state.isMounted||(E.style.transition="none"),P()){var Ve=H(),rt=Ve.box,Oi=Ve.content;Fn([rt,Oi],0)}u=function(){var ai;if(!(!y.state.isVisible||c)){if(c=!0,E.offsetHeight,E.style.transition=y.props.moveTransition,P()&&y.props.animation){var $n=H(),ar=$n.box,Mi=$n.content;Fn([ar,Mi],oe),ic([ar,Mi],"visible")}U(),Q(),ec(Hn,y),(ai=y.popperInstance)==null||ai.forceUpdate(),F("onMount",[y]),y.props.animation&&P()&&se(oe,function(){y.state.isShown=!0,F("onShown",[y])})}},Le()}}function gm(){var k=!y.state.isVisible,G=y.state.isDestroyed,$=!y.state.isEnabled,ce=On(y.props.duration,1,ht.duration);if(!(k||G||$)&&(F("onHide",[y],!1),y.props.onHide(y)!==!1)){if(y.state.isVisible=!1,y.state.isShown=!1,c=!1,o=!1,P()&&(E.style.visibility="hidden"),Y(),ee(),j(!0),P()){var oe=H(),Ve=oe.box,rt=oe.content;y.props.animation&&(Fn([Ve,rt],ce),ic([Ve,rt],"hidden"))}U(),Q(),y.props.animation?P()&&ne(ce,y.unmount):y.unmount()}}function pm(k){J().addEventListener("mousemove",g),ec(Zs,g),g(k)}function mm(){y.state.isVisible&&y.hide(),y.state.isMounted&&(be(),He().forEach(function(k){k._tippy.unmount()}),E.parentNode&&E.parentNode.removeChild(E),Hn=Hn.filter(function(k){return k!==y}),y.state.isMounted=!1,F("onHidden",[y]))}function vm(){y.state.isDestroyed||(y.clearDelayTimeouts(),y.unmount(),Pt(),delete r._tippy,y.state.isDestroyed=!0,F("onDestroy",[y]))}}function ri(r,e){e===void 0&&(e={});var t=ht.plugins.concat(e.plugins||[]);sg();var i=Object.assign({},e,{plugins:t}),s=_0(r),n=s.reduce(function(o,a){var l=a&&fg(a,i);return l&&o.push(l),o},[]);return qs(r)?n[0]:n}ri.defaultProps=ht,ri.setDefaultProps=cg,ri.currentInput=yt,Object.assign({},Pl,{effect:function(e){var t=e.state,i={popper:{position:t.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};Object.assign(t.elements.popper.style,i.popper),t.styles=i,t.elements.arrow&&Object.assign(t.elements.arrow.style,i.arrow)}}),ri.setDefaultProps({render:dc});/**
96
96
  * @license
97
97
  * Copyright 2018 Google LLC
98
98
  * SPDX-License-Identifier: BSD-3-Clause
99
- */const hc="important",gg=" !"+hc,pg=ui(class extends Wi{constructor(r){var e;if(super(r),r.type!==hi.ATTRIBUTE||r.name!=="style"||((e=r.strings)===null||e===void 0?void 0:e.length)>2)throw Error("The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.")}render(r){return Object.keys(r).reduce((e,t)=>{const i=r[t];return i==null?e:e+`${t=t.includes("-")?t:t.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,"-$&").toLowerCase()}:${i};`},"")}update(r,[e]){const{style:t}=r.element;if(this.ut===void 0){this.ut=new Set;for(const i in e)this.ut.add(i);return this.render(e)}this.ut.forEach(i=>{e[i]==null&&(this.ut.delete(i),i.includes("-")?t.removeProperty(i):t[i]="")});for(const i in e){const s=e[i];if(s!=null){this.ut.add(i);const n=typeof s=="string"&&s.endsWith(gg);i.includes("-")||n?t.setProperty(i,n?s.slice(0,-11):s,n?hc:""):t[i]=s}}return ot}});let Js;const mg=new Uint8Array(16);function vg(){if(!Js&&(Js=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Js))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Js(mg)}const Pe=[];for(let r=0;r<256;++r)Pe.push((r+256).toString(16).slice(1));function yg(r,e=0){return(Pe[r[e+0]]+Pe[r[e+1]]+Pe[r[e+2]]+Pe[r[e+3]]+"-"+Pe[r[e+4]]+Pe[r[e+5]]+"-"+Pe[r[e+6]]+Pe[r[e+7]]+"-"+Pe[r[e+8]]+Pe[r[e+9]]+"-"+Pe[r[e+10]]+Pe[r[e+11]]+Pe[r[e+12]]+Pe[r[e+13]]+Pe[r[e+14]]+Pe[r[e+15]]).toLowerCase()}const uc={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ls(r,e,t){if(uc.randomUUID&&!e&&!r)return uc.randomUUID();r=r||{};const i=r.random||(r.rng||vg)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let s=0;s<16;++s)e[t+s]=i[s];return e}return yg(i)}const Ag=5;class bg{constructor(e){this._caption="",this._currentTime=0,this._activeScenes=[],this._upcomingScenes=[],this._fakeBufferSegments=[],this._canvas=Ze(),this._controls=Ze(),this.host=e}set activeScenes(e){if(e!==this._activeScenes){const t=e[0],i=this._activeScenes[0];this._activeScenes=e,t!==i&&(this.host.dispatchEvent(new CustomEvent("scenechange",{detail:e[0]})),this.host.requestUpdate())}}get activeScenes(){return this._activeScenes}set currentTime(e){var t,i,s,n,o;const a=Math.min(this.host.duration,Math.max(0,e));this._currentTime=a,this.activeScenes=((t=this.host.scenes)==null?void 0:t.filter(({start:d,duration:h})=>a>=d&&a<=d+h))??[],this._upcomingScenes=((i=this.host.scenes)==null?void 0:i.filter(({start:d})=>a>=d-Ag&&a<d))??[],this.loadScenes(),this.syncVideoState(),(s=this._controls.value)==null||s.setAttribute("currentTime",a.toString());const l=this.activeScenes[0],c=to((n=l==null?void 0:l.video)==null?void 0:n.captions);this.caption=((o=c.find(({start:d,end:h})=>{var u;const f=a-l.start+(((u=l.video)==null?void 0:u.start)??0);return d&&h&&f>=fs(d)&&f<=fs(h)}))==null?void 0:o.text)??"",this.draw(a),!this.host.paused&&!this.host.loading&&!this.host.processing&&!this.host.waiting&&!this.host.stalled&&this.host.dispatchEvent(new CustomEvent("timeupdate",{detail:a}))}get currentTime(){return this._currentTime}set fakeBufferSegments(e){e!==this._fakeBufferSegments&&(this._fakeBufferSegments=e,this.host.requestUpdate())}get fakeBufferSegments(){return this._fakeBufferSegments}set caption(e){e!==this._caption&&(this._caption=e,this.host.requestUpdate())}get caption(){return this._caption}canvas(){return Je(this._canvas)}controls(){return Je(this._controls)}loadScenes(){var e;let t=this.fakeBufferSegments;(e=this.host.scenes)==null||e.forEach(({id:i,start:s,duration:n,video:o})=>{var a,l,c,d;const h=(a=this.host.videos)==null?void 0:a[i],u=(l=this.host.videoState)==null?void 0:l[i],f=this.activeScenes.find(p=>i===p.id),g=(this._upcomingScenes.find(p=>i===p.id)||f)&&(this.host.currentTime>0||this.host.preload==="auto"||!this.host.paused);if(o&&h&&u){const p=h.hls,m=h.video;m&&(m.currentTime>=o.start+o.duration||m.ended||g&&(p?(c=p.startLoadOnce)==null||c.call(p,m.currentTime):u.initialised||(d=m.startLoadOnce)==null||d.call(m)))}else if(g){const p={start:Math.max(0,s/this.host.duration*100),end:Math.min((s+n)/this.host.duration*100,100)};this.fakeBufferSegments.find(({start:m})=>m===p.start)||(t=[...t,p])}}),this.fakeBufferSegments=t}syncVideoState(){var e;(e=this.host.scenes)==null||e.forEach(({id:t,video:i})=>{var s,n;const o=(s=this.host.videos)==null?void 0:s[t],a=(n=this.host.videoState)==null?void 0:n[t],l=this.activeScenes.find(c=>t===c.id);if(i&&o){const c=o.video;if(c)if(l&&!this.host.waiting&&!this.host.loading&&!this.host.paused){if(c.paused&&a.initialised)return c.play()}else c.paused||c.pause()}})}draw(e=this.currentTime){var t,i;this.host.scenes&&this._canvas.value&&((i=(t=this.host).compilation)==null||i.call(t,{currentTime:e,transitionDuration:this.host.transitionDuration,scenes:this.host.scenes,canvas:this._canvas.value}))}clear(){var e;const t=this._canvas.value;(e=t==null?void 0:t.getContext("2d"))==null||e.clearRect(0,0,t.width,t.height)}}class xg{constructor(e){this._scenes=[],this._duration=0,this._image=new Image,this._processing=!1,this._getPosterSource=()=>Promise.resolve(this._image),this._getVideoSource=({id:t})=>{var i,s;return((s=(i=this.host.videos)==null?void 0:i[t])==null?void 0:s.video)??null},this.host=e,this._task=new Cr(e,async([t,i,s,n,o])=>{var a,l;if(t&&i&&t.length===Object.keys(i).length)try{this.processing=!0;const c=(l=(a=t[0])==null?void 0:a.video)==null?void 0:l.poster;c&&(this._image.src=c,this._image.onload=()=>{e.draw()});const d=await Promise.all(t.map(async h=>{var u;const f=(u=i[h.video.id])==null?void 0:u.video;let g=h.video.duration||f.duration||0;return g===1/0&&(f?g=await new Promise(p=>{f.currentTime=Number.MAX_SAFE_INTEGER,f.ontimeupdate=()=>{f.ontimeupdate=null,p(f.duration),f.currentTime=0}}):g=0),{...h,video:{...h.video,duration:g}}}));this.scenes=await(o==null?void 0:o({parts:d,transitionDuration:s,burnCaptions:n,getPosterSource:this._getPosterSource,getVideoSource:this._getVideoSource})),this.duration=Math.max(0,...this.scenes.map(({start:h,duration:u})=>h+u)),e.reset(e.currentTime,!e.paused),t.length<=0&&e.clear()}catch{e.dispatchEvent(new ErrorEvent("error",new Error("Failed to generate scenes")))}finally{this.processing=!1,this.host.processing=!1}else e.clear(),this.scenes=[],this.duration=0},()=>[e.parts,e.videos,e.transitionDuration,e.burnCaptions,e.sceneGenerator])}set scenes(e){e!==this._scenes&&(this._scenes=e,this.host.requestUpdate(),requestAnimationFrame(()=>{this.host.dispatchEvent(new CustomEvent("loadeddata"))}))}get scenes(){return this._scenes}set duration(e){!isNaN(e)&&e!==this._duration&&(this._duration=e,this.host.requestUpdate(),this.host.dispatchEvent(new CustomEvent("durationchange",{detail:this._duration})))}get duration(){return this._duration}set processing(e){e!==this._processing&&(this._processing=e,this.host.requestUpdate())}get processing(){return this._processing}}function Tg(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function fc(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}class Eg{constructor(e){this._videoState={},this._processing=!1,this.host=e,this.host.addController(this)}set processing(e){e!==this._processing&&(this._processing=e,this.host.requestUpdate())}get processing(){return this._processing}set videos(e){this._videos=e,this.host.requestUpdate()}get videos(){return this._videos}set videoState(e){this._videoState=e,this.host.requestUpdate()}get videoState(){return this._videoState}_setupTask(){this._task=new Cr(this.host,async([e])=>{try{this.host.reset(),this.processing=!0,this.host.processing=!0,Object.keys(this.videos??{}).forEach(t=>{if(this.videos){const{hls:i,video:s}=this.videos[t];i==null||i.destroy(),s.src=""}}),e&&(this.videoState=e.reduce((t,{video:i})=>{const{id:s}=i;return{...t,[s]:{initialised:!1,waiting:!0,buffered:[]}}},{}),this.videos=(await Promise.all(e.map(({video:t})=>new Promise(i=>{const{id:s,src:n,playlist:o,duration:a}=t;let l=null;const c=document.createElement("video");c.playsInline=!0,c.muted=!0,c.volume=this.host.volume,c.playbackRate=this.host.playbackRate;const d=this._handleLoadedData(t,c),h=this._handleWaiting(t),u=this._handleCanPlay(t),f=this._handleProgress(t,c),g=this._handleSeeked(t,c),p=this._handlePlay(t,c),m=this._handlePlaying(t,c),A=this._handlePause(t,c),T=this._handleStalled(t,c),b=this._handleTimeUpdate(t,c),y=this._handleError(t,c);if(c.addEventListener("loadeddata",d),c.addEventListener("waiting",h),c.addEventListener("canplay",u),c.addEventListener("progress",f),c.addEventListener("seeked",g),c.addEventListener("play",p),c.addEventListener("playing",m),c.addEventListener("pause",A),c.addEventListener("stalled",T),c.addEventListener("timeupdate",b),c.addEventListener("error",y),o&&!Tg()&&Dt.isSupported()){let x=!1;l=new Dt({autoStartLoad:!0,xhrSetup:E=>{const{open:S}=E,R=o.split("?")[1];E.open=function(w,I,O){I.toString().includes("?")||(I+="?"+R),S.apply(this,[w,I,O])}}}),l.loadSource(o),l.attachMedia(c),l.startLoadOnce=(E=-1)=>{if(l&&!x){const S=l==null?void 0:l.levels.findIndex(R=>Math.min(R.height,R.width)===this.host.videoResolution);l.startLevel=l.firstLevel,l.startLoad(E),x=!0,l.currentLevel=S!==-1?S:l.firstLevel}},l.on(Dt.Events.LEVEL_LOADED,()=>{x||l==null||l.stopLoad(),i({id:s,hls:l,video:c,listeners:{loadeddata:d,waiting:h,canplay:u,progress:f,seeked:g}})})}else{c.src=n;let x=!1;if(c.startLoadOnce=()=>{x||(c.preload="auto",c.load(),x=!0)},a)c.preload="none",i({id:s,hls:l,video:c,listeners:{loadeddata:d,waiting:h,canplay:u,progress:f,seeked:g}});else{c.preload="metadata";const E=()=>{i({id:s,hls:l,video:c,listeners:{loadedmetadata:E,loadeddata:d,waiting:h,canplay:u,progress:f,seeked:g}})};c.addEventListener("loadedmetadata",E)}}})))).reduce((t,{id:i,...s})=>({...t,[i]:s}),{}))}catch{this.videos={},this.host.dispatchEvent(new ErrorEvent("error",new Error("Failed to create video elements")))}finally{this.processing=!1}},()=>{var e;const t=(e=this.host.parts)==null?void 0:e.reduce((s,{video:n})=>{const{id:o,src:a,playlist:l}=n;return s=[...s,`${o}:${a}:${l}`],s},[]).join("|");if(this._lastDeps&&this._memoKey===t)return this._lastDeps;const i=[this.host.parts];return this._memoKey=t,this._lastDeps=i,i})}_setVideoCurrentTime({id:e,time:t,node:i}){var s;const{start:n,video:o}=((s=this.host.scenes)==null?void 0:s.find(a=>e===a.id))??{};if(o&&i&&typeof n<"u"){const a=t-n;i.currentTime=Math.max(o.start,Math.min(o.start+o.duration,a+o.start))}}setVideosCurrentTime(e){Object.keys(this.videos??{}).forEach(t=>{if(this.videos){const i=this.videos[t].video;this._setVideoCurrentTime({id:t,time:e,node:i})}})}_handleLoadedData(e,t){return()=>{var i;const s=(i=this.videoState)==null?void 0:i[e.id];s!=null&&s.initialised||(this.videoState={...this.videoState,[e.id]:{...s,initialised:!0,waiting:!1,buffered:(s==null?void 0:s.buffered)??[]}},this._setVideoCurrentTime({id:e.id,time:this.host.currentTime,node:t}),this.host.dispatchEvent(new CustomEvent("video:loadeddata",{detail:{video:e,node:t}})))}}_handleWaiting(e){return()=>{var t,i;const s=(t=this.videoState)==null?void 0:t[e.id];s!=null&&s.initialised&&!(s!=null&&s.waiting)&&(this.videoState={...this.videoState,[e.id]:{...(i=this.videoState)==null?void 0:i[e.id],waiting:!0}})}}_handleCanPlay(e){return()=>{var t;const i=(t=this.videoState)==null?void 0:t[e.id];i!=null&&i.initialised&&i!=null&&i.waiting&&(this.videoState={...this.videoState,[e.id]:{...i,waiting:!1}})}}_handleProgress(e,t){const{id:i}=e;return()=>{var s;const n=t==null?void 0:t.buffered,o=[],{start:a,video:l}=((s=this.host.scenes)==null?void 0:s.find(c=>i===c.id))??{};if(t&&n&&l&&typeof a<"u"){for(let c=0;c<n.length;c++){const d=n.start(c),h=n.end(c);Math.max(d,l.start)<=Math.min(h,l.start+l.duration)&&o.push({start:Math.max(0,(Math.max(d-l.start,0)+a)/this.host.duration*100),end:Math.min((Math.min(h-l.start,l.duration)+a)/this.host.duration*100,100)})}this.videoState={...this.videoState,[i]:{...this.videoState[i],buffered:o}}}}}_handleSeeked(e,t){return()=>{var i;((i=this.videoState)==null?void 0:i[e.id]).initialised&&(this.host.draw(),this.host.dispatchEvent(new CustomEvent("video:seeked",{detail:{video:e,node:t}})))}}_handlePlay(e,t){return()=>{this.host.dispatchEvent(new CustomEvent("video:play",{detail:{video:e,node:t}}))}}_handlePlaying(e,t){return()=>{this.host.dispatchEvent(new CustomEvent("video:playing",{detail:{video:e,node:t}}))}}_handlePause(e,t){return()=>{this.host.dispatchEvent(new CustomEvent("video:pause",{detail:{video:e,node:t}}))}}_handleStalled(e,t){return()=>{this.host.dispatchEvent(new CustomEvent("video:stalled",{detail:{video:e,node:t}}))}}_handleTimeUpdate(e,t){return()=>{this.host.dispatchEvent(new CustomEvent("video:timeupdate",{detail:{video:e,node:t}}))}}_handleError(e,t){return()=>{this.host.dispatchEvent(new CustomEvent("video:error",{detail:{video:e,node:t}}))}}hostConnected(){this._setupTask()}hostDisconnected(){Object.keys(this.videos??{}).forEach(e=>{var t,i;(t=this.videos)!=null&&t[e]&&((i=this.videos[e].hls)==null||i.destroy(),this.videos[e].video.pause(),Object.keys(this.videos[e].listeners).forEach(s=>{var n;(n=this.videos)!=null&&n[e]&&this.videos[e].video.removeEventListener(s,this.videos[e].listeners[s])}),delete this.videos[e])}),this.videos=void 0}}function Sg(r){r.requestFullscreen?r.requestFullscreen():r.mozRequestFullScreen?r.mozRequestFullScreen():r.webkitRequestFullscreen?r.webkitRequestFullscreen():r.msRequestFullscreen&&r.msRequestFullscreen()}function Ig(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}const Qs=["progress","play-large","navigation","play","volume","current-time","duration","speed","captions","fullscreen"],Cg={id:"captions",event:"captions:click",label:"Closed Captions"},wg={id:"fullscreen",event:"fullscreen:click",label:"Full Screen"},gc={title:"Playback Speed",items:[{id:"playback-rate-0.5",event:"playbackRate:click",label:"0.5x",value:.5},{id:"playback-rate-1",event:"playbackRate:click",label:"1.0x",value:1},{id:"playback-rate-1.5",event:"playbackRate:click",label:"1.5x",value:1.5},{id:"playback-rate-2",event:"playbackRate:click",label:"2.0x",value:2}]},Lg={id:"playbackRate",label:"Playback playbackRate",subItems:gc};class Rg extends Do{constructor(e){if(super(e),this.element=null,this.observer=void 0,e.type!==hi.ELEMENT)throw new Error("Resize directive must be used in an Element expression")}disconnected(){var e;(e=this.observer)==null||e.disconnect(),this.observer=void 0}reconnected(){var e;this.element&&((e=this.observer)==null||e.observe(this.element))}update(e,[t]){return this.isConnected&&!this.observer&&(this.observer=new ResizeObserver(t),this.element=e.element,this.observer.observe(this.element)),ot}}const _s=ui(Rg),Dg=`
99
+ */const hc="important",gg=" !"+hc,pg=fi(class extends Wi{constructor(r){var e;if(super(r),r.type!==ui.ATTRIBUTE||r.name!=="style"||((e=r.strings)===null||e===void 0?void 0:e.length)>2)throw Error("The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.")}render(r){return Object.keys(r).reduce((e,t)=>{const i=r[t];return i==null?e:e+`${t=t.includes("-")?t:t.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,"-$&").toLowerCase()}:${i};`},"")}update(r,[e]){const{style:t}=r.element;if(this.ut===void 0){this.ut=new Set;for(const i in e)this.ut.add(i);return this.render(e)}this.ut.forEach(i=>{e[i]==null&&(this.ut.delete(i),i.includes("-")?t.removeProperty(i):t[i]="")});for(const i in e){const s=e[i];if(s!=null){this.ut.add(i);const n=typeof s=="string"&&s.endsWith(gg);i.includes("-")||n?t.setProperty(i,n?s.slice(0,-11):s,n?hc:""):t[i]=s}}return ot}});let Js;const mg=new Uint8Array(16);function vg(){if(!Js&&(Js=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Js))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Js(mg)}const Pe=[];for(let r=0;r<256;++r)Pe.push((r+256).toString(16).slice(1));function yg(r,e=0){return(Pe[r[e+0]]+Pe[r[e+1]]+Pe[r[e+2]]+Pe[r[e+3]]+"-"+Pe[r[e+4]]+Pe[r[e+5]]+"-"+Pe[r[e+6]]+Pe[r[e+7]]+"-"+Pe[r[e+8]]+Pe[r[e+9]]+"-"+Pe[r[e+10]]+Pe[r[e+11]]+Pe[r[e+12]]+Pe[r[e+13]]+Pe[r[e+14]]+Pe[r[e+15]]).toLowerCase()}const uc={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ls(r,e,t){if(uc.randomUUID&&!e&&!r)return uc.randomUUID();r=r||{};const i=r.random||(r.rng||vg)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let s=0;s<16;++s)e[t+s]=i[s];return e}return yg(i)}const Ag=5;class bg{constructor(e){this._caption="",this._currentTime=0,this._activeScenes=[],this._upcomingScenes=[],this._fakeBufferSegments=[],this._canvas=Ze(),this._controls=Ze(),this.host=e}set activeScenes(e){if(e!==this._activeScenes){const t=e[0],i=this._activeScenes[0];this._activeScenes=e,t!==i&&(this.host.dispatchEvent(new CustomEvent("scenechange",{detail:e[0]})),this.host.requestUpdate())}}get activeScenes(){return this._activeScenes}set currentTime(e){var t,i,s,n,o;const a=Math.min(this.host.duration,Math.max(0,e));this._currentTime=a,this.activeScenes=((t=this.host.scenes)==null?void 0:t.filter(({start:d,duration:h})=>a>=d&&a<=d+h))??[],this._upcomingScenes=((i=this.host.scenes)==null?void 0:i.filter(({start:d})=>a>=d-Ag&&a<d))??[],this.loadScenes(),this.syncVideoState(),(s=this._controls.value)==null||s.setAttribute("currentTime",a.toString());const l=this.activeScenes[0],c=to((n=l==null?void 0:l.video)==null?void 0:n.captions);this.caption=((o=c.find(({start:d,end:h})=>{var u;const f=a-l.start+(((u=l.video)==null?void 0:u.start)??0);return d&&h&&f>=fs(d)&&f<=fs(h)}))==null?void 0:o.text)??"",this.draw(a),!this.host.paused&&!this.host.loading&&!this.host.processing&&!this.host.waiting&&!this.host.stalled&&this.host.dispatchEvent(new CustomEvent("timeupdate",{detail:a}))}get currentTime(){return this._currentTime}set fakeBufferSegments(e){e!==this._fakeBufferSegments&&(this._fakeBufferSegments=e,this.host.requestUpdate())}get fakeBufferSegments(){return this._fakeBufferSegments}set caption(e){e!==this._caption&&(this._caption=e,this.host.requestUpdate())}get caption(){return this._caption}canvas(){return Je(this._canvas)}controls(){return Je(this._controls)}loadScenes(){var e;let t=this.fakeBufferSegments;(e=this.host.scenes)==null||e.forEach(({id:i,start:s,duration:n,video:o})=>{var a,l,c,d;const h=(a=this.host.videos)==null?void 0:a[i],u=(l=this.host.videoState)==null?void 0:l[i],f=this.activeScenes.find(p=>i===p.id),g=(this._upcomingScenes.find(p=>i===p.id)||f)&&(this.host.currentTime>0||this.host.preload==="auto"||!this.host.paused);if(o&&h&&u){const p=h.hls,m=h.video;m&&(m.currentTime>=o.start+o.duration||m.ended||g&&(p?(c=p.startLoadOnce)==null||c.call(p,m.currentTime):u.initialised||(d=m.startLoadOnce)==null||d.call(m)))}else if(g){const p={start:Math.max(0,s/this.host.duration*100),end:Math.min((s+n)/this.host.duration*100,100)};this.fakeBufferSegments.find(({start:m})=>m===p.start)||(t=[...t,p])}}),this.fakeBufferSegments=t}syncVideoState(){var e;(e=this.host.scenes)==null||e.forEach(({id:t,video:i})=>{var s,n;const o=(s=this.host.videos)==null?void 0:s[t],a=(n=this.host.videoState)==null?void 0:n[t],l=this.activeScenes.find(c=>t===c.id);if(i&&o){const c=o.video;if(c)if(l&&!this.host.waiting&&!this.host.loading&&!this.host.paused){if(c.paused&&a.initialised)return c.play()}else c.paused||c.pause()}})}draw(e=this.currentTime){var t,i;this.host.scenes&&this._canvas.value&&((i=(t=this.host).compilation)==null||i.call(t,{currentTime:e,transitionDuration:this.host.transitionDuration,scenes:this.host.scenes,canvas:this._canvas.value}))}clear(){var e;const t=this._canvas.value;(e=t==null?void 0:t.getContext("2d"))==null||e.clearRect(0,0,t.width,t.height)}}class xg{constructor(e){this._scenes=[],this._duration=0,this._image=new Image,this._processing=!1,this._getPosterSource=()=>Promise.resolve(this._image),this._getVideoSource=({id:t})=>{var i,s;return((s=(i=this.host.videos)==null?void 0:i[t])==null?void 0:s.video)??null},this.host=e,this._task=new Cr(e,async([t,i,s,n,o])=>{var a,l;if(t&&i&&t.length===Object.keys(i).length)try{this.processing=!0;const c=(l=(a=t[0])==null?void 0:a.video)==null?void 0:l.poster;c&&(this._image.src=c,this._image.onload=()=>{e.draw()});const d=await Promise.all(t.map(async h=>{var u;const f=(u=i[h.video.id])==null?void 0:u.video;let g=h.video.duration||f.duration||0;return g===1/0&&(f?g=await new Promise(p=>{f.currentTime=Number.MAX_SAFE_INTEGER,f.ontimeupdate=()=>{f.ontimeupdate=null,p(f.duration),f.currentTime=0}}):g=0),{...h,video:{...h.video,duration:g}}}));this.scenes=await(o==null?void 0:o({parts:d,transitionDuration:s,burnCaptions:n,getPosterSource:this._getPosterSource,getVideoSource:this._getVideoSource})),this.duration=Math.max(0,...this.scenes.map(({start:h,duration:u})=>h+u)),e.reset(e.currentTime,!e.paused),t.length<=0&&e.clear()}catch{e.dispatchEvent(new ErrorEvent("error",new Error("Failed to generate scenes")))}finally{this.processing=!1,this.host.processing=!1}else e.clear(),this.scenes=[],this.duration=0},()=>[e.parts,e.videos,e.transitionDuration,e.burnCaptions,e.sceneGenerator])}set scenes(e){e!==this._scenes&&(this._scenes=e,this.host.requestUpdate(),requestAnimationFrame(()=>{this.host.dispatchEvent(new CustomEvent("loadeddata"))}))}get scenes(){return this._scenes}set duration(e){!isNaN(e)&&e!==this._duration&&(this._duration=e,this.host.requestUpdate(),this.host.dispatchEvent(new CustomEvent("durationchange",{detail:this._duration})))}get duration(){return this._duration}set processing(e){e!==this._processing&&(this._processing=e,this.host.requestUpdate())}get processing(){return this._processing}}function Tg(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function fc(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}class Eg{constructor(e){this._videoState={},this._processing=!1,this.host=e,this.host.addController(this)}set processing(e){e!==this._processing&&(this._processing=e,this.host.requestUpdate())}get processing(){return this._processing}set videos(e){this._videos=e,this.host.requestUpdate()}get videos(){return this._videos}set videoState(e){this._videoState=e,this.host.requestUpdate()}get videoState(){return this._videoState}_setupTask(){this._task=new Cr(this.host,async([e])=>{try{this.host.reset(),this.processing=!0,this.host.processing=!0,Object.keys(this.videos??{}).forEach(t=>{if(this.videos){const{hls:i,video:s}=this.videos[t];i==null||i.destroy(),s.src=""}}),e&&(this.videoState=e.reduce((t,{video:i})=>{const{id:s}=i;return{...t,[s]:{initialised:!1,waiting:!0,buffered:[]}}},{}),this.videos=(await Promise.all(e.map(({video:t})=>new Promise(i=>{const{id:s,src:n,playlist:o,duration:a}=t;let l=null;const c=document.createElement("video");c.playsInline=!0,c.muted=!0,c.volume=this.host.volume,c.playbackRate=this.host.playbackRate;const d=this._handleLoadedData(t,c),h=this._handleWaiting(t),u=this._handleCanPlay(t),f=this._handleProgress(t,c),g=this._handleSeeked(t,c),p=this._handlePlay(t,c),m=this._handlePlaying(t,c),A=this._handlePause(t,c),x=this._handleStalled(t,c),b=this._handleTimeUpdate(t,c),y=this._handleError(t,c);if(c.addEventListener("loadeddata",d),c.addEventListener("waiting",h),c.addEventListener("canplay",u),c.addEventListener("progress",f),c.addEventListener("seeked",g),c.addEventListener("play",p),c.addEventListener("playing",m),c.addEventListener("pause",A),c.addEventListener("stalled",x),c.addEventListener("timeupdate",b),c.addEventListener("error",y),o&&!Tg()&&Dt.isSupported()){let T=!1;l=new Dt({autoStartLoad:!0,xhrSetup:E=>{const{open:S}=E,R=o.split("?")[1];E.open=function(w,I,O){I.toString().includes("?")||(I+="?"+R),S.apply(this,[w,I,O])}}}),l.loadSource(o),l.attachMedia(c),l.startLoadOnce=(E=-1)=>{if(l&&!T){const S=l==null?void 0:l.levels.findIndex(R=>Math.min(R.height,R.width)===this.host.videoResolution);l.startLevel=l.firstLevel,l.startLoad(E),T=!0,l.currentLevel=S!==-1?S:l.firstLevel}},l.on(Dt.Events.LEVEL_LOADED,()=>{T||l==null||l.stopLoad(),i({id:s,hls:l,video:c,listeners:{loadeddata:d,waiting:h,canplay:u,progress:f,seeked:g}})})}else{c.src=n;let T=!1;if(c.startLoadOnce=()=>{T||(c.preload="auto",c.load(),T=!0)},a)c.preload="none",i({id:s,hls:l,video:c,listeners:{loadeddata:d,waiting:h,canplay:u,progress:f,seeked:g}});else{c.preload="metadata";const E=()=>{i({id:s,hls:l,video:c,listeners:{loadedmetadata:E,loadeddata:d,waiting:h,canplay:u,progress:f,seeked:g}})};c.addEventListener("loadedmetadata",E)}}})))).reduce((t,{id:i,...s})=>({...t,[i]:s}),{}))}catch{this.videos={},this.host.dispatchEvent(new ErrorEvent("error",new Error("Failed to create video elements")))}finally{this.processing=!1}},()=>{var e;const t=(e=this.host.parts)==null?void 0:e.reduce((s,{video:n})=>{const{id:o,src:a,playlist:l}=n;return s=[...s,`${o}:${a}:${l}`],s},[]).join("|");if(this._lastDeps&&this._memoKey===t)return this._lastDeps;const i=[this.host.parts];return this._memoKey=t,this._lastDeps=i,i})}_setVideoCurrentTime({id:e,time:t,node:i}){var s;const{start:n,video:o}=((s=this.host.scenes)==null?void 0:s.find(a=>e===a.id))??{};if(o&&i&&typeof n<"u"){const a=t-n;i.currentTime=Math.max(o.start,Math.min(o.start+o.duration,a+o.start))}}setVideosCurrentTime(e){Object.keys(this.videos??{}).forEach(t=>{if(this.videos){const i=this.videos[t].video;this._setVideoCurrentTime({id:t,time:e,node:i})}})}_handleLoadedData(e,t){return()=>{var i;const s=(i=this.videoState)==null?void 0:i[e.id];s!=null&&s.initialised||(this.videoState={...this.videoState,[e.id]:{...s,initialised:!0,waiting:!1,buffered:(s==null?void 0:s.buffered)??[]}},this._setVideoCurrentTime({id:e.id,time:this.host.currentTime,node:t}),this.host.dispatchEvent(new CustomEvent("video:loadeddata",{detail:{video:e,node:t}})))}}_handleWaiting(e){return()=>{var t,i;const s=(t=this.videoState)==null?void 0:t[e.id];s!=null&&s.initialised&&!(s!=null&&s.waiting)&&(this.videoState={...this.videoState,[e.id]:{...(i=this.videoState)==null?void 0:i[e.id],waiting:!0}})}}_handleCanPlay(e){return()=>{var t;const i=(t=this.videoState)==null?void 0:t[e.id];i!=null&&i.initialised&&i!=null&&i.waiting&&(this.videoState={...this.videoState,[e.id]:{...i,waiting:!1}})}}_handleProgress(e,t){const{id:i}=e;return()=>{var s;const n=t==null?void 0:t.buffered,o=[],{start:a,video:l}=((s=this.host.scenes)==null?void 0:s.find(c=>i===c.id))??{};if(t&&n&&l&&typeof a<"u"){for(let c=0;c<n.length;c++){const d=n.start(c),h=n.end(c);Math.max(d,l.start)<=Math.min(h,l.start+l.duration)&&o.push({start:Math.max(0,(Math.max(d-l.start,0)+a)/this.host.duration*100),end:Math.min((Math.min(h-l.start,l.duration)+a)/this.host.duration*100,100)})}this.videoState={...this.videoState,[i]:{...this.videoState[i],buffered:o}}}}}_handleSeeked(e,t){return()=>{var i;((i=this.videoState)==null?void 0:i[e.id]).initialised&&(this.host.draw(),this.host.dispatchEvent(new CustomEvent("video:seeked",{detail:{video:e,node:t}})))}}_handlePlay(e,t){return()=>{this.host.dispatchEvent(new CustomEvent("video:play",{detail:{video:e,node:t}}))}}_handlePlaying(e,t){return()=>{this.host.dispatchEvent(new CustomEvent("video:playing",{detail:{video:e,node:t}}))}}_handlePause(e,t){return()=>{this.host.dispatchEvent(new CustomEvent("video:pause",{detail:{video:e,node:t}}))}}_handleStalled(e,t){return()=>{this.host.dispatchEvent(new CustomEvent("video:stalled",{detail:{video:e,node:t}}))}}_handleTimeUpdate(e,t){return()=>{this.host.dispatchEvent(new CustomEvent("video:timeupdate",{detail:{video:e,node:t}}))}}_handleError(e,t){return()=>{this.host.dispatchEvent(new CustomEvent("video:error",{detail:{video:e,node:t}}))}}hostConnected(){this._setupTask()}hostDisconnected(){Object.keys(this.videos??{}).forEach(e=>{var t,i;(t=this.videos)!=null&&t[e]&&((i=this.videos[e].hls)==null||i.destroy(),this.videos[e].video.pause(),Object.keys(this.videos[e].listeners).forEach(s=>{var n;(n=this.videos)!=null&&n[e]&&this.videos[e].video.removeEventListener(s,this.videos[e].listeners[s])}),delete this.videos[e])}),this.videos=void 0}}function Sg(r){r.requestFullscreen?r.requestFullscreen():r.mozRequestFullScreen?r.mozRequestFullScreen():r.webkitRequestFullscreen?r.webkitRequestFullscreen():r.msRequestFullscreen&&r.msRequestFullscreen()}function Ig(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}const Qs=["progress","play-large","navigation","play","volume","current-time","duration","speed","captions","fullscreen"],Cg={id:"captions",event:"captions:click",label:"Closed Captions"},wg={id:"fullscreen",event:"fullscreen:click",label:"Full Screen"},gc={title:"Playback Speed",items:[{id:"playback-rate-0.5",event:"playbackRate:click",label:"0.5x",value:.5},{id:"playback-rate-1",event:"playbackRate:click",label:"1.0x",value:1},{id:"playback-rate-1.5",event:"playbackRate:click",label:"1.5x",value:1.5},{id:"playback-rate-2",event:"playbackRate:click",label:"2.0x",value:2}]},Lg={id:"playbackRate",label:"Playback playbackRate",subItems:gc};class Rg extends Do{constructor(e){if(super(e),this.element=null,this.observer=void 0,e.type!==ui.ELEMENT)throw new Error("Resize directive must be used in an Element expression")}disconnected(){var e;(e=this.observer)==null||e.disconnect(),this.observer=void 0}reconnected(){var e;this.element&&((e=this.observer)==null||e.observe(this.element))}update(e,[t]){return this.isConnected&&!this.observer&&(this.observer=new ResizeObserver(t),this.element=e.element,this.observer.observe(this.element)),ot}}const _s=fi(Rg),Dg=`
100
100
  @font-face {
101
101
  font-family: "CiscoSansTT";
102
102
  font-weight: 500;
@@ -156,7 +156,7 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
156
156
  scroll-behavior: auto !important
157
157
  }
158
158
  }
159
- `],e},le=Fg(zi),Ng=(r,e)=>(typeof window<"u"&&(window.customElements.get(r)??window.customElements.define(r,e)),e),Bg=(r,e)=>{const{kind:t,elements:i}=e;return{kind:t,elements:i,finisher(s){typeof window<"u"&&(window.customElements.get(r)??window.customElements.define(r,s))}}},Ge=r=>e=>typeof e=="function"?Ng(r,e):Bg(r,e);class Ug extends Wi{constructor(e){if(super(e),e.type!==hi.ELEMENT)throw new Error("Resize directive must be used in an Element expression")}update(e,[t]){return t==null||t(e.element),ot}}const mc=ui(Ug);class Hg{constructor(e){this.hiddenControls=[],this._measureRef=Ze(),this._prevControlsWidth=0,this._hideables={},this._showables={},this._onResize=t=>{var i,s,n;const o=this._measureRef.value,a=(n=(s=(i=t==null?void 0:t[0])==null?void 0:i.borderBoxSize)==null?void 0:s[0])==null?void 0:n.inlineSize;if(o&&a&&a!==this._prevControlsWidth){Object.keys(this._hideables).forEach(c=>{this._hideables[c].element.style.display=""}),Object.keys(this._showables).forEach(c=>{this._showables[c].element.style.display="none"});const l=[];for(;o.scrollWidth>o.offsetWidth;){const c=Object.keys(this._hideables).find(d=>this._hideables[d].hideIndex===l.length);if(c){const d=this._hideables[c].element;d&&(d.style.display="none"),l.push(c)}Object.keys(this._showables).forEach(d=>{this._showables[d].showOn.some(h=>l.includes(h))&&(this._showables[d].element.style.display="flex")})}this.hiddenControls=l,this._prevControlsWidth=a,this.host.requestUpdate()}},this.host=e}measure(){return Je(this._measureRef)}contain(){return _s(this._onResize)}hide(e,t){return mc(i=>{this._hideables[e]={element:i,hideIndex:t}})}show(e,t){return mc(i=>{this._showables[e]={element:i,showOn:t}})}}function vc(r,e={}){const t=Math.max(0,r||0),i=Math.floor(t/3600),s=Math.floor(t%3600/60),n=Math.floor(t%3600%60),o=Math.floor(t%1*1e3);let a=i?`${i}:${`${s}`.padStart(2,"0")}:${`${n}`.padStart(2,"0")}`:`${s}:${`${n}`.padStart(2,"0")}`;return e.includeMs&&(a+=`:${`${o}`.padStart(3,"0")}`),a}var Gg=Object.defineProperty,Vg=Object.getOwnPropertyDescriptor,Si=(r,e,t,i)=>{for(var s=i>1?void 0:i?Vg(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Gg(e,t,s),s};let Vt=class extends le{constructor(){super(...arguments),this.active=!1,this.size="small",this.rounded="medium",this.weight="light"}render(){return te`<button
159
+ `],e},le=Fg(zi),Ng=(r,e)=>(typeof window<"u"&&(window.customElements.get(r)??window.customElements.define(r,e)),e),Bg=(r,e)=>{const{kind:t,elements:i}=e;return{kind:t,elements:i,finisher(s){typeof window<"u"&&(window.customElements.get(r)??window.customElements.define(r,s))}}},Ge=r=>e=>typeof e=="function"?Ng(r,e):Bg(r,e);class Ug extends Wi{constructor(e){if(super(e),e.type!==ui.ELEMENT)throw new Error("Resize directive must be used in an Element expression")}update(e,[t]){return t==null||t(e.element),ot}}const mc=fi(Ug);class Hg{constructor(e){this.hiddenControls=[],this._measureRef=Ze(),this._prevControlsWidth=0,this._hideables={},this._showables={},this._onResize=t=>{var i,s,n;const o=this._measureRef.value,a=(n=(s=(i=t==null?void 0:t[0])==null?void 0:i.borderBoxSize)==null?void 0:s[0])==null?void 0:n.inlineSize;if(o&&a&&a!==this._prevControlsWidth){Object.keys(this._hideables).forEach(c=>{this._hideables[c].element.style.display=""}),Object.keys(this._showables).forEach(c=>{this._showables[c].element.style.display="none"});const l=[];for(;o.scrollWidth>o.offsetWidth;){const c=Object.keys(this._hideables).find(d=>this._hideables[d].hideIndex===l.length);if(c){const d=this._hideables[c].element;d&&(d.style.display="none"),l.push(c)}Object.keys(this._showables).forEach(d=>{this._showables[d].showOn.some(h=>l.includes(h))&&(this._showables[d].element.style.display="flex")})}this.hiddenControls=l,this._prevControlsWidth=a,this.host.requestUpdate()}},this.host=e}measure(){return Je(this._measureRef)}contain(){return _s(this._onResize)}hide(e,t){return mc(i=>{this._hideables[e]={element:i,hideIndex:t}})}show(e,t){return mc(i=>{this._showables[e]={element:i,showOn:t}})}}function vc(r,e={}){const t=Math.max(0,r||0),i=Math.floor(t/3600),s=Math.floor(t%3600/60),n=Math.floor(t%3600%60),o=Math.floor(t%1*1e3);let a=i?`${i}:${`${s}`.padStart(2,"0")}:${`${n}`.padStart(2,"0")}`:`${s}:${`${n}`.padStart(2,"0")}`;return e.includeMs&&(a+=`:${`${o}`.padStart(3,"0")}`),a}var Gg=Object.defineProperty,Vg=Object.getOwnPropertyDescriptor,Ii=(r,e,t,i)=>{for(var s=i>1?void 0:i?Vg(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Gg(e,t,s),s};let Vt=class extends le{constructor(){super(...arguments),this.active=!1,this.size="small",this.rounded="medium",this.weight="light"}render(){return te`<button
160
160
  class=${ge({active:this.active,"size-tiny":this.size==="tiny","size-small":this.size==="small","size-large":this.size==="large","radius-medium":this.rounded==="medium","radius-full":this.rounded==="full","weight-light":this.weight==="light","weight-heavy":this.weight==="heavy"})}
161
161
  >
162
162
  <slot></slot>
@@ -237,7 +237,7 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
237
237
  .weight-light:focus {
238
238
  background: #9d9d9d;
239
239
  }
240
- `],Si([N({type:Boolean})],Vt.prototype,"active",2),Si([N({type:String})],Vt.prototype,"size",2),Si([N({type:String})],Vt.prototype,"rounded",2),Si([N({type:String})],Vt.prototype,"weight",2),Si([N({type:String})],Vt.prototype,"icon",2),Vt=Si([Ge("vmp-button")],Vt);const yc={"arrow-left":()=>te`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
240
+ `],Ii([N({type:Boolean})],Vt.prototype,"active",2),Ii([N({type:String})],Vt.prototype,"size",2),Ii([N({type:String})],Vt.prototype,"rounded",2),Ii([N({type:String})],Vt.prototype,"weight",2),Ii([N({type:String})],Vt.prototype,"icon",2),Vt=Ii([Ge("vmp-button")],Vt);const yc={"arrow-left":()=>te`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
241
241
  <path
242
242
  d="M16.6666 9.21875H6.52492L11.1833 4.85156L9.99992 3.75L3.33325 10L9.99992 16.25L11.1749 15.1484L6.52492 10.7812H16.6666V9.21875Z"
243
243
  fill="currentColor"
@@ -400,7 +400,7 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
400
400
  justify-content: center;
401
401
  flex-shrink: 0;
402
402
  }
403
- `],Ac([N({type:String})],$s.prototype,"icon",2),$s=Ac([Ge("vmp-icon")],$s);var Wg=Object.defineProperty,Yg=Object.getOwnPropertyDescriptor,Ii=(r,e,t,i)=>{for(var s=i>1?void 0:i?Yg(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Wg(e,t,s),s};let jt=class extends le{constructor(){super(...arguments),this.active=!1,this.size="small",this.rounded="medium",this.weight="light"}render(){return te`
403
+ `],Ac([N({type:String})],$s.prototype,"icon",2),$s=Ac([Ge("vmp-icon")],$s);var Wg=Object.defineProperty,Yg=Object.getOwnPropertyDescriptor,Ci=(r,e,t,i)=>{for(var s=i>1?void 0:i?Yg(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Wg(e,t,s),s};let jt=class extends le{constructor(){super(...arguments),this.active=!1,this.size="small",this.rounded="medium",this.weight="light"}render(){return te`
404
404
  <vmp-button
405
405
  ?active=${this.active}
406
406
  size=${Nt(this.size)}
@@ -427,8 +427,8 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
427
427
  height: 32px;
428
428
  width: 32px;
429
429
  }
430
- `],Ii([N({type:Boolean})],jt.prototype,"active",2),Ii([N({type:String})],jt.prototype,"size",2),Ii([N({type:String})],jt.prototype,"rounded",2),Ii([N({type:String})],jt.prototype,"weight",2),Ii([N({type:String})],jt.prototype,"icon",2),jt=Ii([Ge("vmp-icon-button")],jt);const Gn=`.tippy-box[data-animation=shift-away-subtle][data-state=hidden]{opacity:0}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=top]{transform:translateY(5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=bottom]{transform:translateY(-5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=left]{transform:translate(5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=right]{transform:translate(-5px)}
431
- `;var Kg=Object.defineProperty,Xg=Object.getOwnPropertyDescriptor,Ci=(r,e,t,i)=>{for(var s=i>1?void 0:i?Xg(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Kg(e,t,s),s};let zt=class extends le{constructor(){super(...arguments),this.bold=!1,this.semibold=!1,this.truncate=!1,this.size="medium",this.content=""}render(){return te`
430
+ `],Ci([N({type:Boolean})],jt.prototype,"active",2),Ci([N({type:String})],jt.prototype,"size",2),Ci([N({type:String})],jt.prototype,"rounded",2),Ci([N({type:String})],jt.prototype,"weight",2),Ci([N({type:String})],jt.prototype,"icon",2),jt=Ci([Ge("vmp-icon-button")],jt);const Gn=`.tippy-box[data-animation=shift-away-subtle][data-state=hidden]{opacity:0}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=top]{transform:translateY(5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=bottom]{transform:translateY(-5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=left]{transform:translate(5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=right]{transform:translate(-5px)}
431
+ `;var Kg=Object.defineProperty,Xg=Object.getOwnPropertyDescriptor,wi=(r,e,t,i)=>{for(var s=i>1?void 0:i?Xg(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Kg(e,t,s),s};let zt=class extends le{constructor(){super(...arguments),this.bold=!1,this.semibold=!1,this.truncate=!1,this.size="medium",this.content=""}render(){return te`
432
432
  <div
433
433
  part="content"
434
434
  class=${ge({bold:this.bold,semibold:this.semibold,truncate:this.truncate,[this.size]:!0})}
@@ -477,7 +477,7 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
477
477
  text-overflow: ellipsis;
478
478
  overflow: hidden;
479
479
  }
480
- `],Ci([N({type:Boolean})],zt.prototype,"bold",2),Ci([N({type:Boolean})],zt.prototype,"semibold",2),Ci([N({type:Boolean})],zt.prototype,"truncate",2),Ci([N({type:String})],zt.prototype,"size",2),Ci([N({type:String})],zt.prototype,"content",2),zt=Ci([Ge("vmp-text")],zt);var qg=Object.defineProperty,Zg=Object.getOwnPropertyDescriptor,Wt=(r,e,t,i)=>{for(var s=i>1?void 0:i?Zg(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&qg(e,t,s),s};const Vn=1.2;let bt=class extends le{constructor(){super(...arguments),this.bold=!1,this.semibold=!1,this.content="",this.minFontSize=16,this.maxFontSize=32,this.fontSize=this.minFontSize,this.lines=void 0,this._textRef=Ze(),this._handleResize=()=>{if(this.lines=void 0,this._textRef.value){let r=this.fontSize;for(;r<this.minFontSize||r<=this.maxFontSize-2&&this._textRef.value.scrollHeight===this._textRef.value.offsetHeight;)r=r+2,this._textRef.value.style.fontSize=`${r}px`;for(;r>this.maxFontSize||r>=this.minFontSize+2&&this._textRef.value.scrollHeight>this._textRef.value.offsetHeight;)r=r-2,this._textRef.value.style.fontSize=`${r}px`;this.fontSize=r,this._textRef.value.scrollHeight>this._textRef.value.offsetHeight&&(this.lines=Math.floor(this._textRef.value.offsetHeight/(this.fontSize*Vn)))}}}updated(r){(r.has("minFontSize")||r.has("maxFontSize")||r.has("content"))&&this._handleResize()}render(){return te`
480
+ `],wi([N({type:Boolean})],zt.prototype,"bold",2),wi([N({type:Boolean})],zt.prototype,"semibold",2),wi([N({type:Boolean})],zt.prototype,"truncate",2),wi([N({type:String})],zt.prototype,"size",2),wi([N({type:String})],zt.prototype,"content",2),zt=wi([Ge("vmp-text")],zt);var qg=Object.defineProperty,Zg=Object.getOwnPropertyDescriptor,Wt=(r,e,t,i)=>{for(var s=i>1?void 0:i?Zg(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&qg(e,t,s),s};const Vn=1.2;let bt=class extends le{constructor(){super(...arguments),this.bold=!1,this.semibold=!1,this.content="",this.minFontSize=16,this.maxFontSize=32,this.fontSize=this.minFontSize,this.lines=void 0,this._textRef=Ze(),this._handleResize=()=>{if(this.lines=void 0,this._textRef.value){let r=this.fontSize;for(;r<this.minFontSize||r<=this.maxFontSize-2&&this._textRef.value.scrollHeight===this._textRef.value.offsetHeight;)r=r+2,this._textRef.value.style.fontSize=`${r}px`;for(;r>this.maxFontSize||r>=this.minFontSize+2&&this._textRef.value.scrollHeight>this._textRef.value.offsetHeight;)r=r-2,this._textRef.value.style.fontSize=`${r}px`;this.fontSize=r,this._textRef.value.scrollHeight>this._textRef.value.offsetHeight&&(this.lines=Math.floor(this._textRef.value.offsetHeight/(this.fontSize*Vn)))}}}updated(r){(r.has("minFontSize")||r.has("maxFontSize")||r.has("content"))&&this._handleResize()}render(){return te`
481
481
  <span
482
482
  ${Je(this._textRef)}
483
483
  ${_s(this._handleResize)}
@@ -763,7 +763,7 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
763
763
  --volume-slider-height: 8px;
764
764
  color: var(--colors-light-800);
765
765
  }
766
- `],zn([N({type:Number})],hs.prototype,"volume",2),zn([N({type:Boolean})],hs.prototype,"muted",2),hs=zn([Ge("vmp-volume-button")],hs);var ip=Object.defineProperty,sp=Object.getOwnPropertyDescriptor,er=(r,e,t,i)=>{for(var s=i>1?void 0:i?sp(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&ip(e,t,s),s};let wi=class extends le{constructor(){super(...arguments),this.duration=0,this.currentTime=0,this.buffer=[]}render(){var r;const e=((r=this.buffer)==null?void 0:r.sort((t,i)=>t.start<i.start?-1:i.start<t.start?1:0).reduce((t,{start:i,end:s},n)=>{const o=t[n-1],a=Math.floor(i),l=Math.ceil(s);return t.push({id:i,start:Math.max(0,a),end:Math.min(l,100)}),o&&o.end>=i-1&&(t[n].start=o.end),t},[]))??[];return te`
766
+ `],zn([N({type:Number})],hs.prototype,"volume",2),zn([N({type:Boolean})],hs.prototype,"muted",2),hs=zn([Ge("vmp-volume-button")],hs);var ip=Object.defineProperty,sp=Object.getOwnPropertyDescriptor,er=(r,e,t,i)=>{for(var s=i>1?void 0:i?sp(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&ip(e,t,s),s};let Li=class extends le{constructor(){super(...arguments),this.duration=0,this.currentTime=0,this.buffer=[]}render(){var r;const e=((r=this.buffer)==null?void 0:r.sort((t,i)=>t.start<i.start?-1:i.start<t.start?1:0).reduce((t,{start:i,end:s},n)=>{const o=t[n-1],a=Math.floor(i),l=Math.ceil(s);return t.push({id:i,start:Math.max(0,a),end:Math.min(l,100)}),o&&o.end>=i-1&&(t[n].start=o.end),t},[]))??[];return te`
767
767
  <div class="container">
768
768
  <input
769
769
  key="scrubber"
@@ -779,7 +779,7 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
779
779
  <div class="buffer" style=${`left: ${t.start}%; width: ${t.end-t.start}%`}></div>
780
780
  `)}
781
781
  </div>
782
- `}};wi.styles=[le.styles??[],Me`
782
+ `}};Li.styles=[le.styles??[],Me`
783
783
  :host {
784
784
  --player-scrubber-height: 8px;
785
785
  --player-scrubber-shadow-width: 4000px;
@@ -912,7 +912,7 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
912
912
  --player-scrubber-height: 16px;
913
913
  color: var(--colors-light-800);
914
914
  }
915
- `],er([N({type:Number})],wi.prototype,"duration",2),er([N({type:Number})],wi.prototype,"currentTime",2),er([N({type:Array})],wi.prototype,"buffer",2),wi=er([Ge("vmp-progress-scrubber")],wi);var rp=Object.defineProperty,np=Object.getOwnPropertyDescriptor,Oe=(r,e,t,i)=>{for(var s=i>1?void 0:i?np(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&rp(e,t,s),s};let we=class extends le{constructor(){super(...arguments),this.resizeHider=new Hg(this),this.playing=!1,this.volume=1,this.muted=!1,this.currentTime=0,this.duration=0,this.level=-1,this.playbackRate=1,this.buffer=[],this.levels=[],this.captions=!1,this.fullscreen=!1,this.controls=Qs,this.volumeMenuOpen=!1,this.levelsMenuOpen=!1,this.playbackRateMenuOpen=!1,this.settingsMenuOpen=!1}_handleNavigateBackClick(){this.dispatchEvent(new CustomEvent("navigate:back",{bubbles:!0,composed:!0}))}_handleNavigateForwardClick(){this.dispatchEvent(new CustomEvent("navigate:forward",{bubbles:!0,composed:!0}))}_handlePlayClick(){this.dispatchEvent(new CustomEvent("play:click",{bubbles:!0,composed:!0,detail:this.playing}))}_handleCaptionsClick(){this.dispatchEvent(new CustomEvent("captions:click",{bubbles:!0,composed:!0,detail:this.captions}))}_handleFullscreenClick(){this.dispatchEvent(new CustomEvent("fullscreen:click",{bubbles:!0,composed:!0,detail:this.fullscreen}))}_handleVolumeMenuToggle({detail:r}){this.volumeMenuOpen=r}_handleLevelsMenuOpen({detail:r}){this.levelsMenuOpen=r}_handlePlaybackMenuToggle({detail:r}){this.playbackRateMenuOpen=r}_handleSettingsMenuToggle({detail:r}){this.settingsMenuOpen=r}hideMenus(){var r,e;(e=Array.from((r=this.shadowRoot)==null?void 0:r.querySelectorAll("vmp-menu, vmp-tooltip, vmp-volume-button")))==null||e.forEach(t=>{var i;(i=t.tippy)==null||i.hide()})}render(){var r,e,t,i,s,n,o,a,l,c,d,h,u;const f=((r=this.levels)==null?void 0:r.map((H,V)=>{const j=Math.min(H.width,H.height);return{id:`level-${V.toString()}`,event:"level:click",label:`${j}p`,value:{resolution:j,level:V}}}))??[],g={title:"Quality",items:[...f.reverse(),{id:"level--1",event:"level:click",label:"Auto",value:{level:-1,resolution:"auto"}}]},p={id:"levels",label:"Quality",subItems:g},m=(e=g.items)==null?void 0:e.find(({value:H})=>H.level===this.level),A=["levels","playback-rate","captions","fullscreen"].filter(H=>{var V;return(V=this.controls)==null?void 0:V.includes(H)}),T={title:"Settings",items:[Cg,wg,p,Lg].filter(({id:H})=>A.includes(H)&&this.resizeHider.hiddenControls.includes(H))},b=(t=this.controls)==null?void 0:t.includes("progress"),y=(i=this.controls)==null?void 0:i.includes("navigation"),x=(s=this.controls)==null?void 0:s.includes("play"),E=(n=this.controls)==null?void 0:n.includes("volume"),S=(o=this.controls)==null?void 0:o.includes("current-time"),R=(a=this.controls)==null?void 0:a.includes("duration"),w=(l=this.controls)==null?void 0:l.includes("levels"),I=(c=this.controls)==null?void 0:c.includes("speed"),O=(d=this.controls)==null?void 0:d.includes("captions"),P=(h=this.controls)==null?void 0:h.includes("fullscreen"),B=x||E||S||R||w||I||O||P,J=[`level-${(u=this.level)==null?void 0:u.toString()}`,`playback-rate-${this.playbackRate.toString()}`,this.captions&&"captions",this.fullscreen&&"fullscreen"].filter(Boolean);return te`
915
+ `],er([N({type:Number})],Li.prototype,"duration",2),er([N({type:Number})],Li.prototype,"currentTime",2),er([N({type:Array})],Li.prototype,"buffer",2),Li=er([Ge("vmp-progress-scrubber")],Li);var rp=Object.defineProperty,np=Object.getOwnPropertyDescriptor,Oe=(r,e,t,i)=>{for(var s=i>1?void 0:i?np(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&rp(e,t,s),s};let we=class extends le{constructor(){super(...arguments),this.resizeHider=new Hg(this),this.playing=!1,this.volume=1,this.muted=!1,this.currentTime=0,this.duration=0,this.level=-1,this.playbackRate=1,this.buffer=[],this.levels=[],this.captions=!1,this.fullscreen=!1,this.controls=Qs,this.volumeMenuOpen=!1,this.levelsMenuOpen=!1,this.playbackRateMenuOpen=!1,this.settingsMenuOpen=!1}_handleNavigateBackClick(){this.dispatchEvent(new CustomEvent("navigate:back",{bubbles:!0,composed:!0}))}_handleNavigateForwardClick(){this.dispatchEvent(new CustomEvent("navigate:forward",{bubbles:!0,composed:!0}))}_handlePlayClick(){this.dispatchEvent(new CustomEvent("play:click",{bubbles:!0,composed:!0,detail:this.playing}))}_handleCaptionsClick(){this.dispatchEvent(new CustomEvent("captions:click",{bubbles:!0,composed:!0,detail:this.captions}))}_handleFullscreenClick(){this.dispatchEvent(new CustomEvent("fullscreen:click",{bubbles:!0,composed:!0,detail:this.fullscreen}))}_handleVolumeMenuToggle({detail:r}){this.volumeMenuOpen=r}_handleLevelsMenuOpen({detail:r}){this.levelsMenuOpen=r}_handlePlaybackMenuToggle({detail:r}){this.playbackRateMenuOpen=r}_handleSettingsMenuToggle({detail:r}){this.settingsMenuOpen=r}hideMenus(){var r,e;(e=Array.from((r=this.shadowRoot)==null?void 0:r.querySelectorAll("vmp-menu, vmp-tooltip, vmp-volume-button")))==null||e.forEach(t=>{var i;(i=t.tippy)==null||i.hide()})}render(){var r,e,t,i,s,n,o,a,l,c,d,h,u;const f=((r=this.levels)==null?void 0:r.map((H,V)=>{const j=Math.min(H.width,H.height);return{id:`level-${V.toString()}`,event:"level:click",label:`${j}p`,value:{resolution:j,level:V}}}))??[],g={title:"Quality",items:[...f.reverse(),{id:"level--1",event:"level:click",label:"Auto",value:{level:-1,resolution:"auto"}}]},p={id:"levels",label:"Quality",subItems:g},m=(e=g.items)==null?void 0:e.find(({value:H})=>H.level===this.level),A=["levels","playback-rate","captions","fullscreen"].filter(H=>{var V;return(V=this.controls)==null?void 0:V.includes(H)}),x={title:"Settings",items:[Cg,wg,p,Lg].filter(({id:H})=>A.includes(H)&&this.resizeHider.hiddenControls.includes(H))},b=(t=this.controls)==null?void 0:t.includes("progress"),y=(i=this.controls)==null?void 0:i.includes("navigation"),T=(s=this.controls)==null?void 0:s.includes("play"),E=(n=this.controls)==null?void 0:n.includes("volume"),S=(o=this.controls)==null?void 0:o.includes("current-time"),R=(a=this.controls)==null?void 0:a.includes("duration"),w=(l=this.controls)==null?void 0:l.includes("levels"),I=(c=this.controls)==null?void 0:c.includes("speed"),O=(d=this.controls)==null?void 0:d.includes("captions"),P=(h=this.controls)==null?void 0:h.includes("fullscreen"),B=T||E||S||R||w||I||O||P,J=[`level-${(u=this.level)==null?void 0:u.toString()}`,`playback-rate-${this.playbackRate.toString()}`,this.captions&&"captions",this.fullscreen&&"fullscreen"].filter(Boolean);return te`
916
916
  <div
917
917
  ${this.resizeHider.measure()}
918
918
  ${this.resizeHider.contain()}
@@ -951,7 +951,7 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
951
951
  ></vmp-icon-button>
952
952
  </div>
953
953
  <vmp-icon-button
954
- class=${ge({hidden:!x})}
954
+ class=${ge({hidden:!T})}
955
955
  icon=${this.playing?"pause":"play"}
956
956
  weight="heavy"
957
957
  rounded="full"
@@ -1031,7 +1031,7 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
1031
1031
  </vmp-tooltip>
1032
1032
  <vmp-menu
1033
1033
  ${this.resizeHider.show("settings",["levels","playback-rate","captions","fullscreen"])}
1034
- .items=${T}
1034
+ .items=${x}
1035
1035
  .activeItems=${J}
1036
1036
  @menu:toggle=${this._handleSettingsMenuToggle}
1037
1037
  >
@@ -1260,7 +1260,7 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
1260
1260
  vmp-captions.hiddenControls {
1261
1261
  transform: translateY(calc(var(--space-small) * -1));
1262
1262
  }
1263
- `],Be([N({type:Boolean})],Re.prototype,"loading",2),Be([N({type:Boolean})],Re.prototype,"playing",2),Be([N({type:Number})],Re.prototype,"volume",2),Be([N({type:Boolean})],Re.prototype,"muted",2),Be([N({type:Number})],Re.prototype,"currentTime",2),Be([N({type:Number})],Re.prototype,"duration",2),Be([N({type:Array,attribute:!1})],Re.prototype,"levels",2),Be([N({type:Number})],Re.prototype,"level",2),Be([N({type:Number})],Re.prototype,"playbackRate",2),Be([N({type:String})],Re.prototype,"caption",2),Be([N({type:Array})],Re.prototype,"buffer",2),Be([N({type:Boolean})],Re.prototype,"captions",2),Be([N({type:Boolean})],Re.prototype,"fullscreen",2),Be([N({type:Array})],Re.prototype,"controls",2),Be([Fe()],Re.prototype,"showControls",2),Re=Be([Ge("vmp-player-overlay")],Re);var gp=Object.defineProperty,pp=Object.getOwnPropertyDescriptor,Ie=(r,e,t,i)=>{for(var s=i>1?void 0:i?pp(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&gp(e,t,s),s};let xe=class extends le{constructor(){super(...arguments),this.parts=[],this.resolution=1080,this.propAspectRatio=0,this.preload="auto",this.autoplay=!1,this.loading=!1,this.burnCaptions=!1,this.frameRate=30,this.transitionDuration=1/3,this.compilation=Yt,this.sceneGenerator=ro,this._sceneController=new xg(this),this._videoController=new Eg(this),this._drawController=new bg(this),this._wasPlaying=!1,this._manualMute=this.muted,this._seekerRAF=null,this._lastWaiting=!1,this._lastTimestamp=null,this._lastTimeUpdate=null,this._playerRef=Ze(),this._canvasRef=Ze(),this.processing=!0,this._aspectRatio=this.propAspectRatio,this._waiting=!1,this._stalled=!1,this._seeking=!1,this._captions=!1,this._fullscreen=!1,this._paused=!0,this._playbackRate=1,this._volume=null,this._muted=null,this._videoResolution=-1,this._handleContainerResize=()=>{this._playerRef.value&&(this.propAspectRatio||(this._aspectRatio=this._playerRef.value.offsetWidth/this._playerRef.value.offsetHeight))},this._handleCanvasResize=()=>{this.draw()},this._syncCurrentTime=()=>{this.videos&&this.scene.video&&(this._drawController.currentTime=this.scene.start+(this.videos[this.scene.video.id].video.currentTime-this.scene.video.start))},this._seeker=r=>{this.scenes.length>0&&(this._waiting=this._drawController.activeScenes.some(({id:e,video:t})=>{var i;if(t){const s=(i=this._videoController.videoState)==null?void 0:i[e];return!s||!s.initialised||s.waiting}}),this.waiting?(this._lastTimestamp=null,this._lastWaiting||this.dispatchEvent(new CustomEvent("waiting"))):this._lastWaiting&&this.dispatchEvent(new CustomEvent("playing")),!this.stalled&&r-(this._lastTimestamp??0)>1e3/this.frameRate&&(this._drawController.currentTime=this._drawController.currentTime+(r-(this._lastTimestamp??r))/1e3*this.playbackRate,this._lastTimestamp=r),this._lastWaiting=this._waiting,this._drawController.currentTime>=this.duration&&(this.pause(),this.dispatchEvent(new CustomEvent("ended")))),this.paused||(this.scene.video?this._lastTimeUpdate&&r-this._lastTimeUpdate>1e3&&(this._stalled=!0):(this._stalled=!1,this._lastTimeUpdate=r),this._seekerRAF=requestAnimationFrame(this._seeker))},this._handleFullscreenChange=()=>{document.fullscreenElement?this._fullscreen=!0:this._fullscreen=!1}}get aspectRatio(){return this._aspectRatio}get waiting(){return!this.paused&&this._waiting}get stalled(){return this._stalled}get seeking(){return this._seeking}get captions(){return this._captions}get fullscreen(){return this._fullscreen}get duration(){return this._sceneController.duration}get scene(){return this._drawController.activeScenes[this._drawController.activeScenes.length-1]}get scenes(){return this._sceneController.scenes??[]}get videos(){return this._videoController.videos}get videoState(){return this._videoController.videoState}set paused(r){r!==this._paused&&(this._paused=r,this.requestUpdate(),this.dispatchEvent(new CustomEvent(r?"pause":"play")))}get paused(){return this._paused}set playbackRate(r){r!==this._playbackRate&&(this._playbackRate=r,Object.keys(this.videos??{}).forEach(e=>{this.videos&&(this.videos[e].video.playbackRate=r)}),this.requestUpdate(),this.dispatchEvent(new CustomEvent("ratechange",{detail:r})))}get playbackRate(){return this._playbackRate}set volume(r){const e=Math.min(1,Math.max(0,r));e!==this._volume&&(Object.keys(this.videos??{}).forEach(t=>{this.videos&&(this.videos[t].video.volume=e)}),localStorage.setItem("vmp-player-volume",e.toString()),this._volume=e,e>0&&(this.muted=!1),this.requestUpdate(),this.dispatchEvent(new CustomEvent("volumechange",{detail:r})))}get volume(){return this._volume??(this._volume=parseFloat(localStorage.getItem("vmp-player-volume")??"1"))}set muted(r){Object.keys(this.videos??{}).forEach(e=>{this.videos&&(this.videos[e].video.muted=r)}),r!==this._muted&&(this._muted=r,localStorage.setItem("vmp-player-muted",r.toString()),this.requestUpdate(),this.dispatchEvent(new CustomEvent("volumechange",{detail:r?0:this.volume})))}get muted(){return this._muted??(this._muted=localStorage.getItem("vmp-player-muted")==="true")}set videoResolution(r){r!==this._videoResolution&&(this._videoResolution=r,Object.keys(this.videos??{}).forEach(e=>{if(this.videos){const t=this.videos[e].hls;if(t){const i=t==null?void 0:t.levels.findIndex(s=>Math.min(s.height,s.width)===r);t.currentLevel=i??-1}}}),this.requestUpdate())}get videoResolution(){return this._videoResolution}set currentTime(r){r!==this._drawController.currentTime&&(this._drawController.currentTime=r,this._videoController.setVideosCurrentTime(r))}get currentTime(){return this._drawController.currentTime}reset(r=0,e=!1){this._lastTimestamp=null,this._drawController.currentTime=r,this._videoController.setVideosCurrentTime(r),e?this.play():this.pause()}clear(){this._drawController.clear()}play(){this.paused=!1,this._lastTimestamp=null,this._lastTimeUpdate=1/0,this.duration>0&&this._drawController.currentTime>=this.duration&&this.reset(0,!0),this._seekerRAF||(this._seekerRAF=requestAnimationFrame(this._seeker))}pause(){this._seekerRAF&&(cancelAnimationFrame(this._seekerRAF),this._seekerRAF=null),this.paused=!0,Object.keys(this.videos??{}).forEach(r=>{this.videos&&this.videos[r].video.pause()})}draw(r){return this._drawController.draw(r)}setScene(r){var e;const t=(e=this.scenes)==null?void 0:e[r];if(!t)return this.dispatchEvent(new ErrorEvent("error",new Error(`No scene at index: ${r}`)));this.reset(t.start+this.transitionDuration,!this.paused)}toggleFullscreen(r){r??this.fullscreen?Ig():this._playerRef.value&&Sg(this._playerRef.value)}connectedCallback(){super.connectedCallback(),document.addEventListener("fullscreenchange",this._handleFullscreenChange),this.addEventListener("video:timeupdate",r=>{this._stalled=!1,this._lastTimeUpdate=r.timeStamp,this._syncCurrentTime()})}willUpdate(r){this.propAspectRatio&&(this._aspectRatio=this.propAspectRatio),r.has("parts")&&(this.clear(),this.processing=!0),r.has("processing")&&!this.processing&&this.autoplay&&this.play(),r.has("transitionDuration")&&fc()&&(this.transitionDuration=0)}updated(r){r.has("_stalled")&&this.stalled&&this.dispatchEvent(new CustomEvent("stalled")),r.has("propAspectRatio")&&!this.propAspectRatio&&this._handleContainerResize()}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener("fullscreenchange",this._handleFullscreenChange)}render(){var r,e,t,i,s,n;const o=this.loading||this.processing||this.duration<=0,{height:a,width:l}=Mi({resolution:this.resolution,aspectRatio:this.aspectRatio}),c=Object.keys(this._videoController.videoState??{}).reduce((p,m)=>{var A;return p.concat(((A=this._videoController.videoState)==null?void 0:A[m].buffered)??[])},[...this._drawController.fakeBufferSegments]),d=o?[]:(r=this.controls??Qs)==null?void 0:r.filter(p=>!(p==="fullscreen"&&fc()||p==="navigation"&&(!this.scenes||this.scenes.length<=1))),h=(((e=this.scenes)==null?void 0:e.length)??0)-1,u=((t=this.scenes)==null?void 0:t.findIndex(p=>p===this._drawController.activeScenes[0]))??0,f=(i=this._drawController.activeScenes[0])==null?void 0:i.id,g=(n=(s=this.videos)==null?void 0:s[f])==null?void 0:n.hls;return te`
1263
+ `],Be([N({type:Boolean})],Re.prototype,"loading",2),Be([N({type:Boolean})],Re.prototype,"playing",2),Be([N({type:Number})],Re.prototype,"volume",2),Be([N({type:Boolean})],Re.prototype,"muted",2),Be([N({type:Number})],Re.prototype,"currentTime",2),Be([N({type:Number})],Re.prototype,"duration",2),Be([N({type:Array,attribute:!1})],Re.prototype,"levels",2),Be([N({type:Number})],Re.prototype,"level",2),Be([N({type:Number})],Re.prototype,"playbackRate",2),Be([N({type:String})],Re.prototype,"caption",2),Be([N({type:Array})],Re.prototype,"buffer",2),Be([N({type:Boolean})],Re.prototype,"captions",2),Be([N({type:Boolean})],Re.prototype,"fullscreen",2),Be([N({type:Array})],Re.prototype,"controls",2),Be([Fe()],Re.prototype,"showControls",2),Re=Be([Ge("vmp-player-overlay")],Re);var gp=Object.defineProperty,pp=Object.getOwnPropertyDescriptor,Ie=(r,e,t,i)=>{for(var s=i>1?void 0:i?pp(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&gp(e,t,s),s};let xe=class extends le{constructor(){super(...arguments),this.parts=[],this.resolution=1080,this.propAspectRatio=0,this.preload="auto",this.autoplay=!1,this.loading=!1,this.burnCaptions=!1,this.frameRate=30,this.transitionDuration=1/3,this.compilation=Yt,this.sceneGenerator=ro,this._sceneController=new xg(this),this._videoController=new Eg(this),this._drawController=new bg(this),this._wasPlaying=!1,this._manualMute=this.muted,this._seekerRAF=null,this._lastWaiting=!1,this._lastTimestamp=null,this._lastTimeUpdate=null,this._playerRef=Ze(),this._canvasRef=Ze(),this.processing=!0,this._aspectRatio=this.propAspectRatio,this._waiting=!1,this._stalled=!1,this._seeking=!1,this._captions=!1,this._fullscreen=!1,this._paused=!0,this._playbackRate=1,this._volume=null,this._muted=null,this._videoResolution=-1,this._handleContainerResize=()=>{this._playerRef.value&&(this.propAspectRatio||(this._aspectRatio=this._playerRef.value.offsetWidth/this._playerRef.value.offsetHeight))},this._handleCanvasResize=()=>{this.draw()},this._syncCurrentTime=()=>{this.videos&&this.scene.video&&(this._drawController.currentTime=this.scene.start+(this.videos[this.scene.video.id].video.currentTime-this.scene.video.start))},this._seeker=r=>{this.scenes.length>0&&(this._waiting=this._drawController.activeScenes.some(({id:e,video:t})=>{var i;if(t){const s=(i=this._videoController.videoState)==null?void 0:i[e];return!s||!s.initialised||s.waiting}}),this.waiting?(this._lastTimestamp=null,this._lastWaiting||this.dispatchEvent(new CustomEvent("waiting"))):this._lastWaiting&&this.dispatchEvent(new CustomEvent("playing")),!this.stalled&&r-(this._lastTimestamp??0)>1e3/this.frameRate&&(this._drawController.currentTime=this._drawController.currentTime+(r-(this._lastTimestamp??r))/1e3*this.playbackRate,this._lastTimestamp=r),this._lastWaiting=this._waiting,this._drawController.currentTime>=this.duration&&(this.pause(),this.dispatchEvent(new CustomEvent("ended")))),this.paused||(this.scene.video?this._lastTimeUpdate&&r-this._lastTimeUpdate>1e3&&(this._stalled=!0):(this._stalled=!1,this._lastTimeUpdate=r),this._seekerRAF=requestAnimationFrame(this._seeker))},this._handleFullscreenChange=()=>{document.fullscreenElement?this._fullscreen=!0:this._fullscreen=!1}}get aspectRatio(){return this._aspectRatio}get waiting(){return!this.paused&&this._waiting}get stalled(){return this._stalled}get seeking(){return this._seeking}get captions(){return this._captions}get fullscreen(){return this._fullscreen}get duration(){return this._sceneController.duration}get scene(){return this._drawController.activeScenes[this._drawController.activeScenes.length-1]}get scenes(){return this._sceneController.scenes??[]}get videos(){return this._videoController.videos}get videoState(){return this._videoController.videoState}set paused(r){r!==this._paused&&(this._paused=r,this.requestUpdate(),this.dispatchEvent(new CustomEvent(r?"pause":"play")))}get paused(){return this._paused}set playbackRate(r){r!==this._playbackRate&&(this._playbackRate=r,Object.keys(this.videos??{}).forEach(e=>{this.videos&&(this.videos[e].video.playbackRate=r)}),this.requestUpdate(),this.dispatchEvent(new CustomEvent("ratechange",{detail:r})))}get playbackRate(){return this._playbackRate}set volume(r){const e=Math.min(1,Math.max(0,r));e!==this._volume&&(Object.keys(this.videos??{}).forEach(t=>{this.videos&&(this.videos[t].video.volume=e)}),localStorage.setItem("vmp-player-volume",e.toString()),this._volume=e,e>0&&(this.muted=!1),this.requestUpdate(),this.dispatchEvent(new CustomEvent("volumechange",{detail:r})))}get volume(){return this._volume??(this._volume=parseFloat(localStorage.getItem("vmp-player-volume")??"1"))}set muted(r){Object.keys(this.videos??{}).forEach(e=>{this.videos&&(this.videos[e].video.muted=r)}),r!==this._muted&&(this._muted=r,localStorage.setItem("vmp-player-muted",r.toString()),this.requestUpdate(),this.dispatchEvent(new CustomEvent("volumechange",{detail:r?0:this.volume})))}get muted(){return this._muted??(this._muted=localStorage.getItem("vmp-player-muted")==="true")}set videoResolution(r){r!==this._videoResolution&&(this._videoResolution=r,Object.keys(this.videos??{}).forEach(e=>{if(this.videos){const t=this.videos[e].hls;if(t){const i=t==null?void 0:t.levels.findIndex(s=>Math.min(s.height,s.width)===r);t.currentLevel=i??-1}}}),this.requestUpdate())}get videoResolution(){return this._videoResolution}set currentTime(r){r!==this._drawController.currentTime&&(this._drawController.currentTime=r,this._videoController.setVideosCurrentTime(r))}get currentTime(){return this._drawController.currentTime}reset(r=0,e=!1){this._lastTimestamp=null,this._drawController.currentTime=r,this._videoController.setVideosCurrentTime(r),e?this.play():this.pause()}clear(){this._drawController.clear()}play(){this.paused=!1,this._lastTimestamp=null,this._lastTimeUpdate=1/0,this.duration>0&&this._drawController.currentTime>=this.duration&&this.reset(0,!0),this._seekerRAF||(this._seekerRAF=requestAnimationFrame(this._seeker))}pause(){this._seekerRAF&&(cancelAnimationFrame(this._seekerRAF),this._seekerRAF=null),this.paused=!0,Object.keys(this.videos??{}).forEach(r=>{this.videos&&this.videos[r].video.pause()})}draw(r){return this._drawController.draw(r)}setScene(r){var e;const t=(e=this.scenes)==null?void 0:e[r];if(!t)return this.dispatchEvent(new ErrorEvent("error",new Error(`No scene at index: ${r}`)));this.reset(t.start+this.transitionDuration,!this.paused)}toggleFullscreen(r){r??this.fullscreen?Ig():this._playerRef.value&&Sg(this._playerRef.value)}connectedCallback(){super.connectedCallback(),document.addEventListener("fullscreenchange",this._handleFullscreenChange),this.addEventListener("video:timeupdate",r=>{this._stalled=!1,this._lastTimeUpdate=r.timeStamp,this._syncCurrentTime()})}willUpdate(r){this.propAspectRatio&&(this._aspectRatio=this.propAspectRatio),r.has("parts")&&(this.clear(),this.processing=!0),r.has("processing")&&!this.processing&&this.autoplay&&this.play(),r.has("transitionDuration")&&fc()&&(this.transitionDuration=0)}updated(r){r.has("_stalled")&&this.stalled&&this.dispatchEvent(new CustomEvent("stalled")),r.has("propAspectRatio")&&!this.propAspectRatio&&this._handleContainerResize()}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener("fullscreenchange",this._handleFullscreenChange)}render(){var r,e,t,i,s,n;const o=this.loading||this.processing||this.duration<=0,{height:a,width:l}=Fi({resolution:this.resolution,aspectRatio:this.aspectRatio}),c=Object.keys(this._videoController.videoState??{}).reduce((p,m)=>{var A;return p.concat(((A=this._videoController.videoState)==null?void 0:A[m].buffered)??[])},[...this._drawController.fakeBufferSegments]),d=o?[]:(r=this.controls??Qs)==null?void 0:r.filter(p=>!(p==="fullscreen"&&fc()||p==="navigation"&&(!this.scenes||this.scenes.length<=1))),h=(((e=this.scenes)==null?void 0:e.length)??0)-1,u=((t=this.scenes)==null?void 0:t.findIndex(p=>p===this._drawController.activeScenes[0]))??0,f=(i=this._drawController.activeScenes[0])==null?void 0:i.id,g=(n=(s=this.videos)==null?void 0:s[f])==null?void 0:n.hls;return te`
1264
1264
  <div
1265
1265
  ${Je(this._playerRef)}
1266
1266
  ${_s(this._handleContainerResize)}
@@ -1297,7 +1297,7 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
1297
1297
  @playbackRate:click=${({detail:p})=>{this.playbackRate=p.value??1}}
1298
1298
  @captions:click=${()=>{this._captions=!this._captions}}
1299
1299
  @fullscreen:click=${()=>{this.toggleFullscreen()}}
1300
- @input=${p=>{const m=p.composedPath()[0],A=m.getAttribute("key");if(A==="scrubber"){const T=parseFloat(m.value);this._drawController.currentTime=T,this._videoController.setVideosCurrentTime(T),this.dispatchEvent(new CustomEvent("seeking",{detail:T}))}A==="volume"&&(this.volume=parseFloat(m.value))}}
1300
+ @input=${p=>{const m=p.composedPath()[0],A=m.getAttribute("key");if(A==="scrubber"){const x=parseFloat(m.value);this._drawController.currentTime=x,this._videoController.setVideosCurrentTime(x),this.dispatchEvent(new CustomEvent("seeking",{detail:x}))}A==="volume"&&(this.volume=parseFloat(m.value))}}
1301
1301
  @pointerdown=${p=>{p.composedPath()[0].getAttribute("key")==="scrubber"&&(this._seeking=!0,this._wasPlaying=!this.paused,this.paused||this.pause())}}
1302
1302
  @pointerup=${p=>{p.composedPath()[0].getAttribute("key")==="scrubber"&&(this._seeking=!1,this._wasPlaying&&(this.play(),this._wasPlaying=!1),this.dispatchEvent(new CustomEvent("seeked",{detail:this._drawController.currentTime})))}}
1303
1303
  ></vmp-player-overlay>
@@ -1335,7 +1335,7 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
1335
1335
  right: 0;
1336
1336
  bottom: 0;
1337
1337
  }
1338
- `],Ie([N({type:Array})],xe.prototype,"parts",2),Ie([N({type:Number})],xe.prototype,"resolution",2),Ie([N({type:Number,attribute:"aspectratio"})],xe.prototype,"propAspectRatio",2),Ie([N({type:String})],xe.prototype,"preload",2),Ie([N({type:Boolean})],xe.prototype,"autoplay",2),Ie([N({type:Boolean})],xe.prototype,"loading",2),Ie([N({type:Boolean})],xe.prototype,"burnCaptions",2),Ie([N({type:Number})],xe.prototype,"frameRate",2),Ie([N({type:Number})],xe.prototype,"transitionDuration",2),Ie([N({type:Array})],xe.prototype,"controls",2),Ie([N({attribute:!1})],xe.prototype,"compilation",2),Ie([N({attribute:!1})],xe.prototype,"sceneGenerator",2),Ie([Fe()],xe.prototype,"processing",2),Ie([Fe()],xe.prototype,"_aspectRatio",2),Ie([Fe()],xe.prototype,"_waiting",2),Ie([Fe()],xe.prototype,"_stalled",2),Ie([Fe()],xe.prototype,"_seeking",2),Ie([Fe()],xe.prototype,"_captions",2),Ie([Fe()],xe.prototype,"_fullscreen",2),xe=Ie([Ge("vmp-canvas-player")],xe);function mp(r,e,t){function i(s){t.dispatchEvent(new CustomEvent(s.type,s))}return e.addEventListener(r,i),()=>{e.removeEventListener(r,i)}}class vp{constructor(e,t){this._events=[],this._cleanup=[],this._forwardElementRef=Ze(),this.host=e,this._events=t,e.addController(this)}register(){return Je(this._forwardElementRef)}hostConnected(){requestAnimationFrame(()=>{this._events.forEach(e=>{this._forwardElementRef.value&&this._cleanup.push(mp(e,this._forwardElementRef.value,this.host))})})}hostDisconnected(){this._cleanup.forEach(e=>{e()}),this._cleanup=[]}}function yp(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ap=function r(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var i,s,n;if(Array.isArray(e)){if(i=e.length,i!=t.length)return!1;for(s=i;s--!==0;)if(!r(e[s],t[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(n=Object.keys(e),i=n.length,i!==Object.keys(t).length)return!1;for(s=i;s--!==0;)if(!Object.prototype.hasOwnProperty.call(t,n[s]))return!1;for(s=i;s--!==0;){var o=n[s];if(!r(e[o],t[o]))return!1}return!0}return e!==e&&t!==t};const bp=Ap;var xp=(r,e=bp,{cachePromiseRejection:t=!1}={})=>{if(!r)throw new TypeError("You have to provide a `fn` function.");let i=!1,s,n;return async(...o)=>(i&&e(o,s)||(n=r(...o),!t&&n.catch&&n.catch(()=>i=!1),i=!0,s=o),n)};const Tp=yp(xp),Yn="https://vouchfor.com",Ep="https://d2rxhdlm2q91uk.cloudfront.net",Sp="https://d1ix11aj5kfygl.cloudfront.net",Ip="https://d157jlwnudd93d.cloudfront.net",Cp="https://bshyfw4h5a.execute-api.ap-southeast-2.amazonaws.com/dev",wp="https://gyzw7rpbq3.execute-api.ap-southeast-2.amazonaws.com/staging",Lp="https://vfcjuim1l3.execute-api.ap-southeast-2.amazonaws.com/prod",Rp="https://embed-dev.vouchfor.com/v1",Dp="https://embed-staging.vouchfor.com/v1",kp="https://embed.vouchfor.com/v1",Pp="https://dev.vouchfor.com",Op="https://staging.vouchfor.com",Mp="https://app.vouchfor.com";function ir(r){if(!["dev","staging","prod"].includes(r))throw new Error(`Unknown environment: ${r}`);if(r==="dev")return{marketingUrl:Yn,videoUrl:Ep,publicApiUrl:Cp,embedApiUrl:Rp,publicRecorderUrl:Pp};if(r==="staging")return{marketingUrl:Yn,videoUrl:Sp,publicApiUrl:wp,embedApiUrl:Dp,publicRecorderUrl:Op};if(r==="prod")return{marketingUrl:Yn,videoUrl:Ip,publicApiUrl:Lp,embedApiUrl:kp,publicRecorderUrl:Mp}}function Fp(r){var e;return(e=r==null?void 0:r.split)==null?void 0:e.call(r,"/").reverse()[0]}function sr({env:r,path:e,videoPath:t,token:i="",suffix:s=""}){const{videoUrl:n}=ir(r),o=t||e,a=Fp(o);return`${`${n}/${o}/${a}${s}`}${i}`}function Np({env:r,path:e,videoPath:t,token:i}){return!e&&!t?null:sr({env:r,path:e,videoPath:t,token:i,suffix:"_poster.0000001.jpg"})}async function xc(r){var e;try{if((e=await window.fetch(r,{method:"HEAD"}))!=null&&e.ok)return r}catch{return}}async function Tc({sources:r,playlists:e}){const t=r.filter(Boolean).map(o=>xc(o)),i=(await Promise.all(t)).find(Boolean),s=e.filter(Boolean).map(o=>xc(o)),n=(await Promise.all(s)).find(Boolean);return{src:i,playlist:n}}async function Kn({env:r,question:e,type:t,format:i,brandLogo:s,isIntroOutro:n=!1,shortName:o=!1,useRoleTitle:a=!1,showBrandLogo:l=!1,showWatermark:c=!0}){var d,h,u,f,g,p,m,A,T,b,y,x,E,S,R,w,I,O,P,B,J,H,V,j,F,U,Q,Y,z,K,X,ie,ee,ne,se;const ye=((d=e==null?void 0:e.answer)==null?void 0:d.label)??(e==null?void 0:e.title),he=((u=(h=e==null?void 0:e.answer)==null?void 0:h.contact)==null?void 0:u.name)!=="Anonymous"?(g=(f=e==null?void 0:e.answer)==null?void 0:f.contact)==null?void 0:g.name:void 0,_e=((A=(m=(p=e==null?void 0:e.answer)==null?void 0:p.contact)==null?void 0:m.client)==null?void 0:A.name)!=="Not Supplied"?(y=(b=(T=e==null?void 0:e.answer)==null?void 0:T.contact)==null?void 0:b.client)==null?void 0:y.name:void 0,Pt=(S=(E=(x=e==null?void 0:e.answer)==null?void 0:x.contact)==null?void 0:E.client)!=null&&S.logoSrc?decodeURIComponent((I=(w=(R=e==null?void 0:e.answer)==null?void 0:R.contact)==null?void 0:w.client)==null?void 0:I.logoSrc):void 0,Tt=(P=(O=e==null?void 0:e.answer)==null?void 0:O.contact)==null?void 0:P.roleTitle,Ot=o?he==null?void 0:he.split(" ")[0]:he,Te=a?Tt:_e,Ae=!n&&!!ye&&["INLINE","JUMBO"].includes(t),Ue=!n&&(!!he||!!_e||!!Pt)&&["BASIC","CISCO","FOUNDIT","INLINE","JUMBO"].includes(t),ue=((J=(B=e==null?void 0:e.answer)==null?void 0:B.metadata)==null?void 0:J.duration)??0,be=ue*(((V=(H=e==null?void 0:e.answer)==null?void 0:H.settings)==null?void 0:V.startOffset)??0),Le=ue*(((F=(j=e==null?void 0:e.answer)==null?void 0:j.settings)==null?void 0:F.endOffset)??0),He=ue-be-Le,Mt={env:r,path:(U=e==null?void 0:e.answer)==null?void 0:U.path,videoPath:(Q=e==null?void 0:e.answer)==null?void 0:Q.videoPath,token:(Y=e==null?void 0:e.answer)==null?void 0:Y.token},Ft=sr({...Mt,suffix:".mp4"}),oi=sr({...Mt,suffix:`_input.${(z=e==null?void 0:e.answer)==null?void 0:z.inputExtension}`}),Ri=sr({...Mt,suffix:".m3u8"}),{src:Di,playlist:ki}=await Tc({sources:[Ft,oi],playlists:[Ri]});return{...Ae?{card:{brandLogo:s,showBrandLogo:l,showWatermark:c,duration:3,title:ye}}:{},...Ue?{header:{title:Ot,subTitle:Te,brandLogo:s,showBrandLogo:l,showWatermark:c,logoSrc:Pt}}:{},video:{id:(K=e==null?void 0:e.answer)==null?void 0:K.id,type:n?"standalone":"question",src:Di??"",playlist:ki,format:i,poster:Np({env:r,path:(X=e==null?void 0:e.answer)==null?void 0:X.path,videoPath:(ie=e==null?void 0:e.answer)==null?void 0:ie.videoPath,token:(ee=e==null?void 0:e.answer)==null?void 0:ee.token}),start:be,duration:He,captions:(se=(ne=e==null?void 0:e.answer)==null?void 0:ne.captions)==null?void 0:se.current}}}async function Bp({question:r,type:e,format:t,brandLogo:i,shortName:s=!1,useRoleTitle:n=!1,showBrandLogo:o=!1,showWatermark:a=!0}){var l,c,d,h,u,f,g,p,m,A,T,b,y,x,E,S,R,w,I,O,P,B,J,H,V,j;const F=((c=(l=r==null?void 0:r.answer)==null?void 0:l.contact)==null?void 0:c.name)!=="Anonymous"?(h=(d=r==null?void 0:r.answer)==null?void 0:d.contact)==null?void 0:h.name:void 0,U=((f=(u=r==null?void 0:r.answer)==null?void 0:u.customer)==null?void 0:f.name)!=="Not Supplied"?(p=(g=r==null?void 0:r.answer)==null?void 0:g.customer)==null?void 0:p.name:void 0,Q=(A=(m=r==null?void 0:r.answer)==null?void 0:m.customer)!=null&&A.logo?decodeURIComponent((b=(T=r==null?void 0:r.answer)==null?void 0:T.customer)==null?void 0:b.logo):void 0,Y=(x=(y=r==null?void 0:r.answer)==null?void 0:y.contact)==null?void 0:x.role,z=s?F==null?void 0:F.split(" ")[0]:F,K=n?Y:U,X=(r==null?void 0:r.text)&&["INLINE","JUMBO"].includes(e),ie=["BASIC","CISCO","FOUNDIT","INLINE","JUMBO"].includes(e),ee=(E=r==null?void 0:r.answer)==null?void 0:E.video,ne=ee==null?void 0:ee.replace(".m3u8",".mp4"),se=(S=r==null?void 0:r.answer)==null?void 0:S.input,ye=ee.includes(".m3u8")?ee:void 0,{src:he,playlist:_e}=await Tc({sources:[ne,se],playlists:[ye]});return{...X?{card:{brandLogo:i,showBrandLogo:o,showWatermark:a,duration:3,title:r==null?void 0:r.text}}:{},...ie?{header:{title:z,subTitle:K,brandLogo:i,showBrandLogo:o,showWatermark:a,logoSrc:Q}}:{},video:{id:(R=r==null?void 0:r.answer)==null?void 0:R.id,src:he??"",playlist:_e,format:t,start:((I=(w=r==null?void 0:r.answer)==null?void 0:w.trimming)==null?void 0:I.start)??0,duration:(O=r==null?void 0:r.answer)!=null&&O.trimming?((B=(P=r==null?void 0:r.answer)==null?void 0:P.trimming)==null?void 0:B.end)-((H=(J=r==null?void 0:r.answer)==null?void 0:J.trimming)==null?void 0:H.start):void 0,captions:(V=r==null?void 0:r.answer)==null?void 0:V.captions,poster:(j=r==null?void 0:r.answer)==null?void 0:j.thumbnail}}}class Up{constructor(e){this._fetching=!1,this._parts=[],this._embedResponse=null,this._captions=null,this._prevFormat=null,this._prevTrack=null,this._prevData=null,this._prevTemplate=null,this._prevVouchHashId=null,this._prevHeaderSubtitle=null,this._prevHeaderShortName=null,this._prevHeaderBrandLogo=null,this._getEmbedResponse=async({env:t,apiKey:i,vouchHashId:s})=>{var n,o;if(!i)throw new Error("No API Key defined!");const{embedApiUrl:a}=ir(t);try{this.fetching=!0;const l=await fetch(`${a}/vouches/${s}`,{method:"GET",headers:{"x-api-key":i}}).then(d=>d.json()),c=await Promise.all(((o=(n=l==null?void 0:l.vouch)==null?void 0:n.questions)==null?void 0:o.map(async d=>{var h;const u={...d,answer:{...d.answer,captions:""}};if(d.answer.captions)try{const f=await fetch(d.answer.captions,{method:"GET"}).then(g=>g.text());return{...d,answer:{...d.answer,captions:f}}}catch{return this.host.dispatchEvent(new ErrorEvent("error",new Error(`Captions failed to fetch for answer ${(h=d==null?void 0:d.answer)==null?void 0:h.id}`))),u}return u}))??[]);return this.embedResponse={...l,vouch:{...l==null?void 0:l.vouch,questions:c}},this.embedResponse}catch{this.host.dispatchEvent(new ErrorEvent("error",new Error(`Could not fetch vouch with hash ID: ${s}`)))}},this.getEmbedResponse=Tp(this._getEmbedResponse),this.host=e,this._task=new Cr(e,async([t,i,s,n,o,a,l,c,d,h,u,f,g])=>{var p,m,A,T,b,y,x,E,S,R,w,I,O,P,B,J,H,V,j,F,U,Q;try{const Y=c??"letterbox-video",z=l??((m=(p=a==null?void 0:a.settings)==null?void 0:p.template)==null?void 0:m.type)??"BARE";if(t){if(s!==this._prevTrack&&(this._captions=null),s&&!this._captions)try{this._prevTrack=s,this._captions=await(await fetch(s,{method:"GET"})).text()}catch{e.dispatchEvent(new ErrorEvent("error",new Error("Track failed to fetch")))}this.parts=[{video:{src:t,playlist:i,poster:n,captions:this._captions,id:"source-video",start:0,format:Y}}],this._embedResponse=null,this._prevData=null,this._prevTemplate=null,this._prevVouchHashId=null,this._prevHeaderShortName=null,this._prevHeaderSubtitle=null,this._prevHeaderBrandLogo=null}else if(a&&(a!==this._prevData||z!==this._prevTemplate||u!==this._prevHeaderShortName||f!==this._prevHeaderSubtitle||g!==this._prevHeaderBrandLogo)){const K=(y=(b=(T=(A=a==null?void 0:a.settings)==null?void 0:A.template)==null?void 0:T.introVouch)==null?void 0:b.questions)==null?void 0:y.items,X=a==null?void 0:a.entity,ie=(x=a==null?void 0:a.questions)==null?void 0:x.items,ee=(w=(R=(S=(E=a==null?void 0:a.settings)==null?void 0:E.template)==null?void 0:S.outroVouch)==null?void 0:R.questions)==null?void 0:w.items,ne=(O=(I=a==null?void 0:a.settings)==null?void 0:I.options)==null?void 0:O.showVouchWatermark;this.parts=await Promise.all([...((P=K==null?void 0:K.filter(se=>!!se.answer))==null?void 0:P.map(async se=>Kn({env:d,question:se,showWatermark:ne,type:z,format:Y,isIntroOutro:!0,brandLogo:X!=null&&X.logoSrc?decodeURIComponent(X==null?void 0:X.logoSrc):void 0,shortName:u,useRoleTitle:f==="role",showBrandLogo:g})))??[],...((B=ie==null?void 0:ie.filter(se=>!!se.answer))==null?void 0:B.map(async se=>Kn({env:d,question:se,showWatermark:ne,type:z,format:Y,shortName:u,brandLogo:X!=null&&X.logoSrc?decodeURIComponent(X==null?void 0:X.logoSrc):void 0,useRoleTitle:f==="role",showBrandLogo:g})))??[],...((J=ee==null?void 0:ee.filter(se=>!!se.answer))==null?void 0:J.map(async se=>Kn({env:d,question:se,showWatermark:ne,type:z,format:Y,isIntroOutro:!0,shortName:u,brandLogo:X!=null&&X.logoSrc?decodeURIComponent(X==null?void 0:X.logoSrc):void 0,useRoleTitle:f==="role",showBrandLogo:g})))??[]]),a.id!==((H=this._prevData)==null?void 0:H.id)&&this.host.dispatchEvent(new CustomEvent("vouch:loaded",{detail:a.id})),this._prevData=a,this._prevVouchHashId=null,this._prevHeaderShortName=u??null,this._prevHeaderSubtitle=f??null,this._prevHeaderBrandLogo=g??null}else if(!a&&o&&(z!==this._prevTemplate||o!==this._prevVouchHashId||u!==this._prevHeaderShortName||f!==this._prevHeaderSubtitle||g!==this._prevHeaderBrandLogo)){const K=await this.getEmbedResponse({env:d,apiKey:h,vouchHashId:o,data:a});this.parts=await Promise.all((F=(j=(V=K==null?void 0:K.vouch)==null?void 0:V.questions)==null?void 0:j.filter(X=>!!X.answer))==null?void 0:F.map(async X=>{var ie,ee,ne,se;return Bp({question:X,type:z,format:Y,brandLogo:(ie=K.entity)!=null&&ie.logo?decodeURIComponent((ee=K.entity)==null?void 0:ee.logo):void 0,shortName:u,useRoleTitle:f==="role",showWatermark:(se=(ne=K==null?void 0:K.vouch)==null?void 0:ne.options)==null?void 0:se.showVouchWatermark,showBrandLogo:g})})),(U=this.embedResponse)!=null&&U.vouch&&this.host.dispatchEvent(new CustomEvent("vouch:loaded",{detail:(Q=this.embedResponse)==null?void 0:Q.vouch.uuid})),this._prevData=null,this._prevTemplate=z,this._prevVouchHashId=o,this._prevHeaderShortName=u??null,this._prevHeaderSubtitle=f??null,this._prevHeaderBrandLogo=g??null}else Y!==this._prevFormat&&(this.parts=this.parts.map(K=>({...K,video:{...K.video,format:Y}})),this._prevFormat=Y);this._setSceneGenerator(z)}catch(Y){e.dispatchEvent(new ErrorEvent("error",Y))}finally{this.fetching=!1}},()=>[e.src,e.playlist,e.track,e.poster,e.vouchHashId,e.data,e.type,e.format,e.env,e.apiKey,e.headerShortName,e.headerSubtitle,e.headerBrandLogo])}set parts(e){e!==this._parts&&(this._parts=e,this.host.requestUpdate())}get parts(){return this._parts}set embedResponse(e){e!==this._embedResponse&&(this._embedResponse=e,this.host.requestUpdate())}get embedResponse(){return this._embedResponse}set fetching(e){e!==this._fetching&&(this._fetching=e,this.host.requestUpdate())}get fetching(){return this._fetching}_setSceneGenerator(e){if(this.host.canvasPlayer)switch(e){case"JUMBO":this.host.canvasPlayer.sceneGenerator=Wc;break;case"CISCO":this.host.canvasPlayer.sceneGenerator=jc;break;case"FOUNDIT":this.host.canvasPlayer.sceneGenerator=Yc;break;default:this.host.canvasPlayer.sceneGenerator=ro}}}const Hp=2e3;class Gp{constructor(e){this._tabId=void 0,this._clientId=void 0,this._visitorId=void 0,this._hasPlayed=!1,this._hasLoaded={},this._answersViewed={},this._streamedTime={},this._streamedPrevTimestamp={},this._createVisitor=t=>{var i,s;const{publicApiUrl:n}=ir(this.host.env);return(s=(i=window.localStorage)==null?void 0:i.setItem)==null||s.call(i,"vouch-uid-visitor",t),navigator.sendBeacon(`${n}/api/visitor`,JSON.stringify({visitorId:t})),t},this._getReportingMetadata=()=>{const[t,i]=Intl.DateTimeFormat().resolvedOptions().timeZone.split("/"),s={};return[...new URLSearchParams(location.search).entries()].forEach(([n,o])=>{if(/utm/.test(n)){const a=n.toLowerCase().replace(/[-_][a-z0-9]/g,l=>l.slice(-1).toUpperCase());s[a]=o}}),{source:this.host.trackingSource,time:new Date,region:i,country:t,screenHeight:window.screen.height,screenWidth:window.screen.width,referrer:document.referrer,currentUrl:location.href,...s}},this._sendTrackingEvent=(t,i)=>{const{publicApiUrl:s}=ir(this.host.env),{client:n,tab:o,request:a,visitor:l}=this._getUids();this.host.enableTracking&&this.host.trackingSource&&navigator.sendBeacon(`${s}/api/events`,JSON.stringify({event:t,payload:i,context:{"x-uid-client":n,"x-uid-tab":o,"x-uid-request":a,"x-uid-visitor":l,"x-reporting-metadata":this._getReportingMetadata()}}))},this._handleVouchLoaded=({detail:t})=>{t&&(this._hasLoaded[t]||(this._sendTrackingEvent("VOUCH_LOADED",{vouchId:t}),this._hasLoaded[t]=!0))},this._handlePlay=()=>{const t=this._findVouchId();t&&(this._hasPlayed||(this._sendTrackingEvent("VIDEO_PLAYED",{vouchId:t,streamStart:this.host.currentTime}),this._hasPlayed=!0))},this._handleVideoPlay=({detail:{video:t,node:i}})=>{const s=this._findVouchId();s&&(this._answersViewed[t.id]||(this._sendTrackingEvent("VOUCH_RESPONSE_VIEWED",{vouchId:s,answerId:t.id}),this._answersViewed[t.id]=!0),this._streamedTime[t.id]=i.currentTime,this._streamedPrevTimestamp[t.id]=Date.now())},this._handleVideoTimeUpdate=({detail:{video:t,node:i}})=>{var s;const n=this._findVouchId();if(!n)return;const o=Date.now();!this.host.paused&&t.id===((s=this.host.scene)==null?void 0:s.id)&&o-this._streamedPrevTimestamp[t.id]>Hp&&(this._sendTrackingEvent("VIDEO_STREAMED",{vouchId:n,answerId:t.id,streamStart:this._streamedTime[t.id],streamEnd:i.currentTime}),this._streamedTime[t.id]=i.currentTime,this._streamedPrevTimestamp[t.id]=o)},this._handleVideoPause=({detail:{video:t,node:i}})=>{const s=this._findVouchId();s&&(this._sendTrackingEvent("VIDEO_STREAMED",{vouchId:s,answerId:t.id,streamStart:this._streamedTime[t.id],streamEnd:i.currentTime}),delete this._streamedTime[t.id],delete this._streamedPrevTimestamp[t.id])},this.host=e,e.addController(this)}_findVouchId(){if(this.host.vouch)return"uuid"in this.host.vouch?this.host.vouch.uuid:this.host.vouch.id}_getUids(){var e,t,i,s,n,o,a,l,c,d,h,u;if(typeof window>"u")return{client:null,tab:null,request:ls()};const f=this._visitorId||((t=(e=window.localStorage)==null?void 0:e.getItem)==null?void 0:t.call(e,"vouch-uid-visitor"))||this._createVisitor(ls()),g=this._clientId||((s=(i=window.localStorage)==null?void 0:i.getItem)==null?void 0:s.call(i,"vouch-uid-client"))||ls(),p=this._tabId||((o=(n=window.sessionStorage)==null?void 0:n.getItem)==null?void 0:o.call(n,"vouch-uid-tab"))||ls(),m=ls();return f!==this._visitorId&&(this._visitorId=f,(l=(a=window.localStorage)==null?void 0:a.setItem)==null||l.call(a,"vouch-uid-visitor",f)),g!==this._clientId&&(this._clientId=g,(d=(c=window.localStorage)==null?void 0:c.setItem)==null||d.call(c,"vouch-uid-client",g)),p!==this._tabId&&(this._tabId=p,(u=(h=window.sessionStorage)==null?void 0:h.setItem)==null||u.call(h,"vouch-uid-tab",p)),{client:g,tab:p,request:m,visitor:f}}hostConnected(){this.host.enableTracking&&this.host.trackingSource&&requestAnimationFrame(()=>{var e,t,i,s;this.host.addEventListener("vouch:loaded",this._handleVouchLoaded),(e=this.host.canvasPlayer)==null||e.addEventListener("play",this._handlePlay),(t=this.host.canvasPlayer)==null||t.addEventListener("video:play",this._handleVideoPlay),(i=this.host.canvasPlayer)==null||i.addEventListener("video:pause",this._handleVideoPause),(s=this.host.canvasPlayer)==null||s.addEventListener("video:timeupdate",this._handleVideoTimeUpdate)})}hostDisconnected(){var e,t,i,s;this.host.enableTracking&&this.host.trackingSource&&(this.host.removeEventListener("vouch:loaded",this._handleVouchLoaded),(e=this.host.canvasPlayer)==null||e.removeEventListener("play",this._handlePlay),(t=this.host.canvasPlayer)==null||t.removeEventListener("video:play",this._handleVideoPlay),(i=this.host.canvasPlayer)==null||i.removeEventListener("video:pause",this._handleVideoPause),(s=this.host.canvasPlayer)==null||s.removeEventListener("video:timeupdate",this._handleVideoTimeUpdate))}}var Vp=Object.defineProperty,jp=Object.getOwnPropertyDescriptor,Se=(r,e,t,i)=>{for(var s=i>1?void 0:i?jp(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Vp(e,t,s),s};let pe=class extends le{constructor(){super(...arguments),this._canvasPlayerRef=Ze(),this.preload="auto",this.autoplay=!1,this.enableTracking=!1,this.trackingSource="media_player",this.env="prod",this.apiKey="",this.resolution=1080,this.aspectRatio=0,this.headerSubtitle="client",this.headerShortName=!1,this.headerBrandLogo=!1,this.controls=Qs,this.eventController=new vp(this,["durationchange","ended","error","loadeddata","pause","stalled","play","playing","ratechange","scenechange","seeking","seeked","timeupdate","volumechange","waiting","video:loadeddata","video:seeked","video:play","video:playing","video:pause","video:stalled","video:timeupdate","video:error"]),this.partsController=new Up(this),this.trackingController=new Gp(this)}get fetching(){return this.partsController.fetching}get waiting(){var r;return(r=this._canvasPlayerRef.value)==null?void 0:r.waiting}get seeking(){var r;return(r=this._canvasPlayerRef.value)==null?void 0:r.seeking}get paused(){var r;return(r=this._canvasPlayerRef.value)==null?void 0:r.paused}get captions(){var r;return(r=this._canvasPlayerRef.value)==null?void 0:r.captions}get fullscreen(){var r;return(r=this._canvasPlayerRef.value)==null?void 0:r.fullscreen}get duration(){var r;return(r=this._canvasPlayerRef.value)==null?void 0:r.duration}set currentTime(r){this._canvasPlayerRef.value&&(this._canvasPlayerRef.value.currentTime=r)}get currentTime(){var r;return((r=this._canvasPlayerRef.value)==null?void 0:r.currentTime)??0}set playbackRate(r){this._canvasPlayerRef.value&&(this._canvasPlayerRef.value.playbackRate=r)}get playbackRate(){var r;return((r=this._canvasPlayerRef.value)==null?void 0:r.playbackRate)??1}set volume(r){this._canvasPlayerRef.value&&(this._canvasPlayerRef.value.volume=r)}get volume(){var r;return((r=this._canvasPlayerRef.value)==null?void 0:r.volume)??1}set muted(r){this._canvasPlayerRef.value&&(this._canvasPlayerRef.value.muted=r)}get muted(){var r;return((r=this._canvasPlayerRef.value)==null?void 0:r.muted)??!1}get vouch(){var r;return this.data??((r=this.partsController.embedResponse)==null?void 0:r.vouch)}get scene(){var r;return((r=this._canvasPlayerRef.value)==null?void 0:r.scene)??null}get scenes(){var r;return((r=this._canvasPlayerRef.value)==null?void 0:r.scenes)??[]}get videos(){var r;return(r=this._canvasPlayerRef.value)==null?void 0:r.videos}get videoState(){var r;return(r=this._canvasPlayerRef.value)==null?void 0:r.videoState}get canvasPlayer(){return this._canvasPlayerRef.value}play(){var r;(r=this._canvasPlayerRef.value)==null||r.play()}pause(){var r;(r=this._canvasPlayerRef.value)==null||r.pause()}setScene(r){var e;(e=this._canvasPlayerRef.value)==null||e.setScene(r)}render(){return te`
1338
+ `],Ie([N({type:Array})],xe.prototype,"parts",2),Ie([N({type:Number})],xe.prototype,"resolution",2),Ie([N({type:Number,attribute:"aspectratio"})],xe.prototype,"propAspectRatio",2),Ie([N({type:String})],xe.prototype,"preload",2),Ie([N({type:Boolean})],xe.prototype,"autoplay",2),Ie([N({type:Boolean})],xe.prototype,"loading",2),Ie([N({type:Boolean})],xe.prototype,"burnCaptions",2),Ie([N({type:Number})],xe.prototype,"frameRate",2),Ie([N({type:Number})],xe.prototype,"transitionDuration",2),Ie([N({type:Array})],xe.prototype,"controls",2),Ie([N({attribute:!1})],xe.prototype,"compilation",2),Ie([N({attribute:!1})],xe.prototype,"sceneGenerator",2),Ie([Fe()],xe.prototype,"processing",2),Ie([Fe()],xe.prototype,"_aspectRatio",2),Ie([Fe()],xe.prototype,"_waiting",2),Ie([Fe()],xe.prototype,"_stalled",2),Ie([Fe()],xe.prototype,"_seeking",2),Ie([Fe()],xe.prototype,"_captions",2),Ie([Fe()],xe.prototype,"_fullscreen",2),xe=Ie([Ge("vmp-canvas-player")],xe);function mp(r,e,t){function i(s){t.dispatchEvent(new CustomEvent(s.type,s))}return e.addEventListener(r,i),()=>{e.removeEventListener(r,i)}}class vp{constructor(e,t){this._events=[],this._cleanup=[],this._forwardElementRef=Ze(),this.host=e,this._events=t,e.addController(this)}register(){return Je(this._forwardElementRef)}hostConnected(){requestAnimationFrame(()=>{this._events.forEach(e=>{this._forwardElementRef.value&&this._cleanup.push(mp(e,this._forwardElementRef.value,this.host))})})}hostDisconnected(){this._cleanup.forEach(e=>{e()}),this._cleanup=[]}}function yp(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ap=function r(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var i,s,n;if(Array.isArray(e)){if(i=e.length,i!=t.length)return!1;for(s=i;s--!==0;)if(!r(e[s],t[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(n=Object.keys(e),i=n.length,i!==Object.keys(t).length)return!1;for(s=i;s--!==0;)if(!Object.prototype.hasOwnProperty.call(t,n[s]))return!1;for(s=i;s--!==0;){var o=n[s];if(!r(e[o],t[o]))return!1}return!0}return e!==e&&t!==t};const bp=Ap;var xp=(r,e=bp,{cachePromiseRejection:t=!1}={})=>{if(!r)throw new TypeError("You have to provide a `fn` function.");let i=!1,s,n;return async(...o)=>(i&&e(o,s)||(n=r(...o),!t&&n.catch&&n.catch(()=>i=!1),i=!0,s=o),n)};const Tp=yp(xp),Yn="https://vouchfor.com",Ep="https://d2rxhdlm2q91uk.cloudfront.net",Sp="https://d1ix11aj5kfygl.cloudfront.net",Ip="https://d157jlwnudd93d.cloudfront.net",Cp="https://bshyfw4h5a.execute-api.ap-southeast-2.amazonaws.com/dev",wp="https://gyzw7rpbq3.execute-api.ap-southeast-2.amazonaws.com/staging",Lp="https://vfcjuim1l3.execute-api.ap-southeast-2.amazonaws.com/prod",Rp="https://embed-dev.vouchfor.com/v1",Dp="https://embed-staging.vouchfor.com/v1",kp="https://embed.vouchfor.com/v1",Pp="https://dev.vouchfor.com",Op="https://staging.vouchfor.com",Mp="https://app.vouchfor.com";function ir(r){if(!["dev","staging","prod"].includes(r))throw new Error(`Unknown environment: ${r}`);if(r==="dev")return{marketingUrl:Yn,videoUrl:Ep,publicApiUrl:Cp,embedApiUrl:Rp,publicRecorderUrl:Pp};if(r==="staging")return{marketingUrl:Yn,videoUrl:Sp,publicApiUrl:wp,embedApiUrl:Dp,publicRecorderUrl:Op};if(r==="prod")return{marketingUrl:Yn,videoUrl:Ip,publicApiUrl:Lp,embedApiUrl:kp,publicRecorderUrl:Mp}}function Fp(r){var e;return(e=r==null?void 0:r.split)==null?void 0:e.call(r,"/").reverse()[0]}function sr({env:r,path:e,videoPath:t,token:i="",suffix:s=""}){const{videoUrl:n}=ir(r),o=t||e,a=Fp(o);return`${`${n}/${o}/${a}${s}`}${i}`}function Np({env:r,path:e,videoPath:t,token:i}){return!e&&!t?null:sr({env:r,path:e,videoPath:t,token:i,suffix:"_poster.0000001.jpg"})}async function xc(r){var e;try{if((e=await window.fetch(r,{method:"HEAD"}))!=null&&e.ok)return r}catch{return}}async function Tc({sources:r,playlists:e}){const t=r.filter(Boolean).map(o=>xc(o)),i=(await Promise.all(t)).find(Boolean),s=e.filter(Boolean).map(o=>xc(o)),n=(await Promise.all(s)).find(Boolean);return{src:i,playlist:n}}async function Kn({env:r,question:e,type:t,format:i,brandLogo:s,isIntroOutro:n=!1,shortName:o=!1,useRoleTitle:a=!1,showBrandLogo:l=!1,showWatermark:c=!0}){var d,h,u,f,g,p,m,A,x,b,y,T,E,S,R,w,I,O,P,B,J,H,V,j,F,U,Q,Y,z,K,X,ie,ee,ne,se;const ye=((d=e==null?void 0:e.answer)==null?void 0:d.label)??(e==null?void 0:e.title),he=((u=(h=e==null?void 0:e.answer)==null?void 0:h.contact)==null?void 0:u.name)!=="Anonymous"?(g=(f=e==null?void 0:e.answer)==null?void 0:f.contact)==null?void 0:g.name:void 0,_e=((A=(m=(p=e==null?void 0:e.answer)==null?void 0:p.contact)==null?void 0:m.client)==null?void 0:A.name)!=="Not Supplied"?(y=(b=(x=e==null?void 0:e.answer)==null?void 0:x.contact)==null?void 0:b.client)==null?void 0:y.name:void 0,Pt=(S=(E=(T=e==null?void 0:e.answer)==null?void 0:T.contact)==null?void 0:E.client)!=null&&S.logoSrc?decodeURIComponent((I=(w=(R=e==null?void 0:e.answer)==null?void 0:R.contact)==null?void 0:w.client)==null?void 0:I.logoSrc):void 0,Tt=(P=(O=e==null?void 0:e.answer)==null?void 0:O.contact)==null?void 0:P.roleTitle,Ot=o?he==null?void 0:he.split(" ")[0]:he,Te=a?Tt:_e,Ae=!n&&!!ye&&["INLINE","JUMBO"].includes(t),Ue=!n&&(!!he||!!_e||!!Pt)&&["BASIC","CISCO","FOUNDIT","INLINE","JUMBO"].includes(t),ue=((J=(B=e==null?void 0:e.answer)==null?void 0:B.metadata)==null?void 0:J.duration)??0,be=ue*(((V=(H=e==null?void 0:e.answer)==null?void 0:H.settings)==null?void 0:V.startOffset)??0),Le=ue*(((F=(j=e==null?void 0:e.answer)==null?void 0:j.settings)==null?void 0:F.endOffset)??0),He=ue-be-Le,Mt={env:r,path:(U=e==null?void 0:e.answer)==null?void 0:U.path,videoPath:(Q=e==null?void 0:e.answer)==null?void 0:Q.videoPath,token:(Y=e==null?void 0:e.answer)==null?void 0:Y.token},Ft=sr({...Mt,suffix:".mp4"}),oi=sr({...Mt,suffix:`_input.${(z=e==null?void 0:e.answer)==null?void 0:z.inputExtension}`}),Di=sr({...Mt,suffix:".m3u8"}),{src:ki,playlist:Pi}=await Tc({sources:[Ft,oi],playlists:[Di]});return{...Ae?{card:{brandLogo:s,showBrandLogo:l,showWatermark:c,duration:3,title:ye}}:{},...Ue?{header:{title:Ot,subTitle:Te,brandLogo:s,showBrandLogo:l,showWatermark:c,logoSrc:Pt}}:{},video:{id:(K=e==null?void 0:e.answer)==null?void 0:K.id,type:n?"standalone":"question",src:ki??"",playlist:Pi,format:i,poster:Np({env:r,path:(X=e==null?void 0:e.answer)==null?void 0:X.path,videoPath:(ie=e==null?void 0:e.answer)==null?void 0:ie.videoPath,token:(ee=e==null?void 0:e.answer)==null?void 0:ee.token}),start:be,duration:He,captions:(se=(ne=e==null?void 0:e.answer)==null?void 0:ne.captions)==null?void 0:se.current}}}async function Bp({question:r,type:e,format:t,brandLogo:i,shortName:s=!1,useRoleTitle:n=!1,showBrandLogo:o=!1,showWatermark:a=!0}){var l,c,d,h,u,f,g,p,m,A,x,b,y,T,E,S,R,w,I,O,P,B,J,H,V,j;const F=((c=(l=r==null?void 0:r.answer)==null?void 0:l.contact)==null?void 0:c.name)!=="Anonymous"?(h=(d=r==null?void 0:r.answer)==null?void 0:d.contact)==null?void 0:h.name:void 0,U=((f=(u=r==null?void 0:r.answer)==null?void 0:u.customer)==null?void 0:f.name)!=="Not Supplied"?(p=(g=r==null?void 0:r.answer)==null?void 0:g.customer)==null?void 0:p.name:void 0,Q=(A=(m=r==null?void 0:r.answer)==null?void 0:m.customer)!=null&&A.logo?decodeURIComponent((b=(x=r==null?void 0:r.answer)==null?void 0:x.customer)==null?void 0:b.logo):void 0,Y=(T=(y=r==null?void 0:r.answer)==null?void 0:y.contact)==null?void 0:T.role,z=s?F==null?void 0:F.split(" ")[0]:F,K=n?Y:U,X=(r==null?void 0:r.text)&&["INLINE","JUMBO"].includes(e),ie=["BASIC","CISCO","FOUNDIT","INLINE","JUMBO"].includes(e),ee=(E=r==null?void 0:r.answer)==null?void 0:E.video,ne=ee==null?void 0:ee.replace(".m3u8",".mp4"),se=(S=r==null?void 0:r.answer)==null?void 0:S.input,ye=ee.includes(".m3u8")?ee:void 0,{src:he,playlist:_e}=await Tc({sources:[ne,se],playlists:[ye]});return{...X?{card:{brandLogo:i,showBrandLogo:o,showWatermark:a,duration:3,title:r==null?void 0:r.text}}:{},...ie?{header:{title:z,subTitle:K,brandLogo:i,showBrandLogo:o,showWatermark:a,logoSrc:Q}}:{},video:{id:(R=r==null?void 0:r.answer)==null?void 0:R.id,src:he??"",playlist:_e,format:t,start:((I=(w=r==null?void 0:r.answer)==null?void 0:w.trimming)==null?void 0:I.start)??0,duration:(O=r==null?void 0:r.answer)!=null&&O.trimming?((B=(P=r==null?void 0:r.answer)==null?void 0:P.trimming)==null?void 0:B.end)-((H=(J=r==null?void 0:r.answer)==null?void 0:J.trimming)==null?void 0:H.start):void 0,captions:(V=r==null?void 0:r.answer)==null?void 0:V.captions,poster:(j=r==null?void 0:r.answer)==null?void 0:j.thumbnail}}}class Up{constructor(e){this._fetching=!1,this._parts=[],this._embedResponse=null,this._captions=null,this._prevFormat=null,this._prevTrack=null,this._prevData=null,this._prevTemplate=null,this._prevVouchHashId=null,this._prevHeaderSubtitle=null,this._prevHeaderShortName=null,this._prevHeaderBrandLogo=null,this._getEmbedResponse=async({env:t,apiKey:i,vouchHashId:s})=>{var n,o;if(!i)throw new Error("No API Key defined!");const{embedApiUrl:a}=ir(t);try{this.fetching=!0;const l=await fetch(`${a}/vouches/${s}`,{method:"GET",headers:{"x-api-key":i}}).then(d=>d.json()),c=await Promise.all(((o=(n=l==null?void 0:l.vouch)==null?void 0:n.questions)==null?void 0:o.map(async d=>{var h;const u={...d,answer:{...d.answer,captions:""}};if(d.answer.captions)try{const f=await fetch(d.answer.captions,{method:"GET"}).then(g=>g.text());return{...d,answer:{...d.answer,captions:f}}}catch{return this.host.dispatchEvent(new ErrorEvent("error",new Error(`Captions failed to fetch for answer ${(h=d==null?void 0:d.answer)==null?void 0:h.id}`))),u}return u}))??[]);return this.embedResponse={...l,vouch:{...l==null?void 0:l.vouch,questions:c}},this.embedResponse}catch{this.host.dispatchEvent(new ErrorEvent("error",new Error(`Could not fetch vouch with hash ID: ${s}`)))}},this.getEmbedResponse=Tp(this._getEmbedResponse),this.host=e,this._task=new Cr(e,async([t,i,s,n,o,a,l,c,d,h,u,f,g])=>{var p,m,A,x,b,y,T,E,S,R,w,I,O,P,B,J,H,V,j,F,U,Q;try{const Y=c??"letterbox-video",z=l??((m=(p=a==null?void 0:a.settings)==null?void 0:p.template)==null?void 0:m.type)??"BARE";if(t){if(s!==this._prevTrack&&(this._captions=null),s&&!this._captions)try{this._prevTrack=s,this._captions=await(await fetch(s,{method:"GET"})).text()}catch{e.dispatchEvent(new ErrorEvent("error",new Error("Track failed to fetch")))}this.parts=[{video:{src:t,playlist:i,poster:n,captions:this._captions,id:"source-video",start:0,format:Y}}],this._embedResponse=null,this._prevData=null,this._prevTemplate=null,this._prevVouchHashId=null,this._prevHeaderShortName=null,this._prevHeaderSubtitle=null,this._prevHeaderBrandLogo=null}else if(a&&(a!==this._prevData||z!==this._prevTemplate||u!==this._prevHeaderShortName||f!==this._prevHeaderSubtitle||g!==this._prevHeaderBrandLogo)){const K=(y=(b=(x=(A=a==null?void 0:a.settings)==null?void 0:A.template)==null?void 0:x.introVouch)==null?void 0:b.questions)==null?void 0:y.items,X=a==null?void 0:a.entity,ie=(T=a==null?void 0:a.questions)==null?void 0:T.items,ee=(w=(R=(S=(E=a==null?void 0:a.settings)==null?void 0:E.template)==null?void 0:S.outroVouch)==null?void 0:R.questions)==null?void 0:w.items,ne=(O=(I=a==null?void 0:a.settings)==null?void 0:I.options)==null?void 0:O.showVouchWatermark;this.parts=await Promise.all([...((P=K==null?void 0:K.filter(se=>!!se.answer))==null?void 0:P.map(async se=>Kn({env:d,question:se,showWatermark:ne,type:z,format:Y,isIntroOutro:!0,brandLogo:X!=null&&X.logoSrc?decodeURIComponent(X==null?void 0:X.logoSrc):void 0,shortName:u,useRoleTitle:f==="role",showBrandLogo:g})))??[],...((B=ie==null?void 0:ie.filter(se=>!!se.answer))==null?void 0:B.map(async se=>Kn({env:d,question:se,showWatermark:ne,type:z,format:Y,shortName:u,brandLogo:X!=null&&X.logoSrc?decodeURIComponent(X==null?void 0:X.logoSrc):void 0,useRoleTitle:f==="role",showBrandLogo:g})))??[],...((J=ee==null?void 0:ee.filter(se=>!!se.answer))==null?void 0:J.map(async se=>Kn({env:d,question:se,showWatermark:ne,type:z,format:Y,isIntroOutro:!0,shortName:u,brandLogo:X!=null&&X.logoSrc?decodeURIComponent(X==null?void 0:X.logoSrc):void 0,useRoleTitle:f==="role",showBrandLogo:g})))??[]]),a.id!==((H=this._prevData)==null?void 0:H.id)&&this.host.dispatchEvent(new CustomEvent("vouch:loaded",{detail:a.id})),this._prevData=a,this._prevVouchHashId=null,this._prevHeaderShortName=u??null,this._prevHeaderSubtitle=f??null,this._prevHeaderBrandLogo=g??null}else if(!a&&o&&(z!==this._prevTemplate||o!==this._prevVouchHashId||u!==this._prevHeaderShortName||f!==this._prevHeaderSubtitle||g!==this._prevHeaderBrandLogo)){const K=await this.getEmbedResponse({env:d,apiKey:h,vouchHashId:o,data:a});this.parts=await Promise.all((F=(j=(V=K==null?void 0:K.vouch)==null?void 0:V.questions)==null?void 0:j.filter(X=>!!X.answer))==null?void 0:F.map(async X=>{var ie,ee,ne,se;return Bp({question:X,type:z,format:Y,brandLogo:(ie=K.entity)!=null&&ie.logo?decodeURIComponent((ee=K.entity)==null?void 0:ee.logo):void 0,shortName:u,useRoleTitle:f==="role",showWatermark:(se=(ne=K==null?void 0:K.vouch)==null?void 0:ne.options)==null?void 0:se.showVouchWatermark,showBrandLogo:g})})),(U=this.embedResponse)!=null&&U.vouch&&this.host.dispatchEvent(new CustomEvent("vouch:loaded",{detail:(Q=this.embedResponse)==null?void 0:Q.vouch.uuid})),this._prevData=null,this._prevTemplate=z,this._prevVouchHashId=o,this._prevHeaderShortName=u??null,this._prevHeaderSubtitle=f??null,this._prevHeaderBrandLogo=g??null}else Y!==this._prevFormat&&(this.parts=this.parts.map(K=>({...K,video:{...K.video,format:Y}})),this._prevFormat=Y);this._setSceneGenerator(z)}catch(Y){e.dispatchEvent(new ErrorEvent("error",Y))}finally{this.fetching=!1}},()=>[e.src,e.playlist,e.track,e.poster,e.vouchHashId,e.data,e.type,e.format,e.env,e.apiKey,e.headerShortName,e.headerSubtitle,e.headerBrandLogo])}set parts(e){e!==this._parts&&(this._parts=e,this.host.requestUpdate())}get parts(){return this._parts}set embedResponse(e){e!==this._embedResponse&&(this._embedResponse=e,this.host.requestUpdate())}get embedResponse(){return this._embedResponse}set fetching(e){e!==this._fetching&&(this._fetching=e,this.host.requestUpdate())}get fetching(){return this._fetching}_setSceneGenerator(e){if(this.host.canvasPlayer)switch(e){case"JUMBO":this.host.canvasPlayer.sceneGenerator=Wc;break;case"CISCO":this.host.canvasPlayer.sceneGenerator=jc;break;case"FOUNDIT":this.host.canvasPlayer.sceneGenerator=Yc;break;default:this.host.canvasPlayer.sceneGenerator=ro}}}const Hp=2e3;class Gp{constructor(e){this._tabId=void 0,this._clientId=void 0,this._visitorId=void 0,this._hasPlayed=!1,this._hasLoaded={},this._answersViewed={},this._streamedTime={},this._streamedPrevTimestamp={},this._createVisitor=t=>{var i,s;const{publicApiUrl:n}=ir(this.host.env);return(s=(i=window.localStorage)==null?void 0:i.setItem)==null||s.call(i,"vouch-uid-visitor",t),navigator.sendBeacon(`${n}/api/visitor`,JSON.stringify({visitorId:t})),t},this._getReportingMetadata=()=>{const[t,i]=Intl.DateTimeFormat().resolvedOptions().timeZone.split("/"),s={};return[...new URLSearchParams(location.search).entries()].forEach(([n,o])=>{if(/utm/.test(n)){const a=n.toLowerCase().replace(/[-_][a-z0-9]/g,l=>l.slice(-1).toUpperCase());s[a]=o}}),{source:this.host.trackingSource,time:new Date,region:i,country:t,screenHeight:window.screen.height,screenWidth:window.screen.width,referrer:document.referrer,currentUrl:location.href,...s}},this._sendTrackingEvent=(t,i)=>{const{publicApiUrl:s}=ir(this.host.env),{client:n,tab:o,request:a,visitor:l}=this._getUids();this.host.enableTracking&&this.host.trackingSource&&navigator.sendBeacon(`${s}/api/events`,JSON.stringify({event:t,payload:i,context:{"x-uid-client":n,"x-uid-tab":o,"x-uid-request":a,"x-uid-visitor":l,"x-reporting-metadata":this._getReportingMetadata()}}))},this._handleVouchLoaded=({detail:t})=>{t&&(this._hasLoaded[t]||(this._sendTrackingEvent("VOUCH_LOADED",{vouchId:t}),this._hasLoaded[t]=!0))},this._handlePlay=()=>{const t=this._findVouchId();t&&(this._hasPlayed||(this._sendTrackingEvent("VIDEO_PLAYED",{vouchId:t,streamStart:this.host.currentTime}),this._hasPlayed=!0))},this._handleVideoPlay=({detail:{video:t,node:i}})=>{const s=this._findVouchId();s&&(this._answersViewed[t.id]||(this._sendTrackingEvent("VOUCH_RESPONSE_VIEWED",{vouchId:s,answerId:t.id}),this._answersViewed[t.id]=!0),this._streamedTime[t.id]=i.currentTime,this._streamedPrevTimestamp[t.id]=Date.now())},this._handleVideoTimeUpdate=({detail:{video:t,node:i}})=>{var s;const n=this._findVouchId();if(!n)return;const o=Date.now();!this.host.paused&&t.id===((s=this.host.scene)==null?void 0:s.id)&&o-this._streamedPrevTimestamp[t.id]>Hp&&(this._sendTrackingEvent("VIDEO_STREAMED",{vouchId:n,answerId:t.id,streamStart:this._streamedTime[t.id],streamEnd:i.currentTime}),this._streamedTime[t.id]=i.currentTime,this._streamedPrevTimestamp[t.id]=o)},this._handleVideoPause=({detail:{video:t,node:i}})=>{const s=this._findVouchId();s&&(this._sendTrackingEvent("VIDEO_STREAMED",{vouchId:s,answerId:t.id,streamStart:this._streamedTime[t.id],streamEnd:i.currentTime}),delete this._streamedTime[t.id],delete this._streamedPrevTimestamp[t.id])},this.host=e,e.addController(this)}_findVouchId(){if(this.host.vouch)return"uuid"in this.host.vouch?this.host.vouch.uuid:this.host.vouch.id}_getUids(){var e,t,i,s,n,o,a,l,c,d,h,u;if(typeof window>"u")return{client:null,tab:null,request:ls()};const f=this._visitorId||((t=(e=window.localStorage)==null?void 0:e.getItem)==null?void 0:t.call(e,"vouch-uid-visitor"))||this._createVisitor(ls()),g=this._clientId||((s=(i=window.localStorage)==null?void 0:i.getItem)==null?void 0:s.call(i,"vouch-uid-client"))||ls(),p=this._tabId||((o=(n=window.sessionStorage)==null?void 0:n.getItem)==null?void 0:o.call(n,"vouch-uid-tab"))||ls(),m=ls();return f!==this._visitorId&&(this._visitorId=f,(l=(a=window.localStorage)==null?void 0:a.setItem)==null||l.call(a,"vouch-uid-visitor",f)),g!==this._clientId&&(this._clientId=g,(d=(c=window.localStorage)==null?void 0:c.setItem)==null||d.call(c,"vouch-uid-client",g)),p!==this._tabId&&(this._tabId=p,(u=(h=window.sessionStorage)==null?void 0:h.setItem)==null||u.call(h,"vouch-uid-tab",p)),{client:g,tab:p,request:m,visitor:f}}hostConnected(){this.host.enableTracking&&this.host.trackingSource&&requestAnimationFrame(()=>{var e,t,i,s;this.host.addEventListener("vouch:loaded",this._handleVouchLoaded),(e=this.host.canvasPlayer)==null||e.addEventListener("play",this._handlePlay),(t=this.host.canvasPlayer)==null||t.addEventListener("video:play",this._handleVideoPlay),(i=this.host.canvasPlayer)==null||i.addEventListener("video:pause",this._handleVideoPause),(s=this.host.canvasPlayer)==null||s.addEventListener("video:timeupdate",this._handleVideoTimeUpdate)})}hostDisconnected(){var e,t,i,s;this.host.enableTracking&&this.host.trackingSource&&(this.host.removeEventListener("vouch:loaded",this._handleVouchLoaded),(e=this.host.canvasPlayer)==null||e.removeEventListener("play",this._handlePlay),(t=this.host.canvasPlayer)==null||t.removeEventListener("video:play",this._handleVideoPlay),(i=this.host.canvasPlayer)==null||i.removeEventListener("video:pause",this._handleVideoPause),(s=this.host.canvasPlayer)==null||s.removeEventListener("video:timeupdate",this._handleVideoTimeUpdate))}}var Vp=Object.defineProperty,jp=Object.getOwnPropertyDescriptor,Se=(r,e,t,i)=>{for(var s=i>1?void 0:i?jp(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Vp(e,t,s),s};let pe=class extends le{constructor(){super(...arguments),this._canvasPlayerRef=Ze(),this.preload="auto",this.autoplay=!1,this.enableTracking=!1,this.trackingSource="media_player",this.env="prod",this.apiKey="",this.resolution=1080,this.aspectRatio=0,this.headerSubtitle="client",this.headerShortName=!1,this.headerBrandLogo=!1,this.controls=Qs,this.eventController=new vp(this,["durationchange","ended","error","loadeddata","pause","stalled","play","playing","ratechange","scenechange","seeking","seeked","timeupdate","volumechange","waiting","video:loadeddata","video:seeked","video:play","video:playing","video:pause","video:stalled","video:timeupdate","video:error"]),this.partsController=new Up(this),this.trackingController=new Gp(this)}get fetching(){return this.partsController.fetching}get waiting(){var r;return(r=this._canvasPlayerRef.value)==null?void 0:r.waiting}get seeking(){var r;return(r=this._canvasPlayerRef.value)==null?void 0:r.seeking}get paused(){var r;return(r=this._canvasPlayerRef.value)==null?void 0:r.paused}get captions(){var r;return(r=this._canvasPlayerRef.value)==null?void 0:r.captions}get fullscreen(){var r;return(r=this._canvasPlayerRef.value)==null?void 0:r.fullscreen}get duration(){var r;return(r=this._canvasPlayerRef.value)==null?void 0:r.duration}set currentTime(r){this._canvasPlayerRef.value&&(this._canvasPlayerRef.value.currentTime=r)}get currentTime(){var r;return((r=this._canvasPlayerRef.value)==null?void 0:r.currentTime)??0}set playbackRate(r){this._canvasPlayerRef.value&&(this._canvasPlayerRef.value.playbackRate=r)}get playbackRate(){var r;return((r=this._canvasPlayerRef.value)==null?void 0:r.playbackRate)??1}set volume(r){this._canvasPlayerRef.value&&(this._canvasPlayerRef.value.volume=r)}get volume(){var r;return((r=this._canvasPlayerRef.value)==null?void 0:r.volume)??1}set muted(r){this._canvasPlayerRef.value&&(this._canvasPlayerRef.value.muted=r)}get muted(){var r;return((r=this._canvasPlayerRef.value)==null?void 0:r.muted)??!1}get vouch(){var r;return this.data??((r=this.partsController.embedResponse)==null?void 0:r.vouch)}get scene(){var r;return((r=this._canvasPlayerRef.value)==null?void 0:r.scene)??null}get scenes(){var r;return((r=this._canvasPlayerRef.value)==null?void 0:r.scenes)??[]}get videos(){var r;return(r=this._canvasPlayerRef.value)==null?void 0:r.videos}get videoState(){var r;return(r=this._canvasPlayerRef.value)==null?void 0:r.videoState}get canvasPlayer(){return this._canvasPlayerRef.value}play(){var r;(r=this._canvasPlayerRef.value)==null||r.play()}pause(){var r;(r=this._canvasPlayerRef.value)==null||r.pause()}setScene(r){var e;(e=this._canvasPlayerRef.value)==null||e.setScene(r)}render(){return te`
1339
1339
  <vmp-canvas-player
1340
1340
  ${Je(this._canvasPlayerRef)}
1341
1341
  ${this.eventController.register()}
@@ -1347,5 +1347,5 @@ var embeds=function(nt){"use strict";var Am=Object.defineProperty;var bm=(nt,Et,
1347
1347
  preload=${Nt(this.preload)}
1348
1348
  .controls=${this.controls}
1349
1349
  ></vmp-canvas-player>
1350
- `}};pe.styles=[le.styles??[]],Se([N({type:String})],pe.prototype,"src",2),Se([N({type:String})],pe.prototype,"playlist",2),Se([N({type:String})],pe.prototype,"track",2),Se([N({type:String})],pe.prototype,"poster",2),Se([N({type:Object})],pe.prototype,"data",2),Se([N({type:String})],pe.prototype,"vouchHashId",2),Se([N({type:String})],pe.prototype,"preload",2),Se([N({type:Boolean})],pe.prototype,"autoplay",2),Se([N({type:Boolean})],pe.prototype,"enableTracking",2),Se([N({type:String})],pe.prototype,"trackingSource",2),Se([N({type:String})],pe.prototype,"env",2),Se([N({type:String})],pe.prototype,"apiKey",2),Se([N({type:String})],pe.prototype,"type",2),Se([N({type:String})],pe.prototype,"format",2),Se([N({type:Number})],pe.prototype,"resolution",2),Se([N({type:Number})],pe.prototype,"aspectRatio",2),Se([N({type:String})],pe.prototype,"headerSubtitle",2),Se([N({type:Boolean})],pe.prototype,"headerShortName",2),Se([N({type:Boolean})],pe.prototype,"headerBrandLogo",2),Se([N({type:Array})],pe.prototype,"controls",2),pe=Se([Ge("vmp-media-player")],pe);var zp=Object.defineProperty,Wp=Object.getOwnPropertyDescriptor,Yp=(r,e,t,i)=>{for(var s=i>1?void 0:i?Wp(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&zp(e,t,s),s};nt.InlineEmbed=class extends pe{},nt.InlineEmbed=Yp([$c("vembed-inline")],nt.InlineEmbed);function xt(r){if(typeof r!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(r))}function Ec(r,e){for(var t="",i=0,s=-1,n=0,o,a=0;a<=r.length;++a){if(a<r.length)o=r.charCodeAt(a);else{if(o===47)break;o=47}if(o===47){if(!(s===a-1||n===1))if(s!==a-1&&n===2){if(t.length<2||i!==2||t.charCodeAt(t.length-1)!==46||t.charCodeAt(t.length-2)!==46){if(t.length>2){var l=t.lastIndexOf("/");if(l!==t.length-1){l===-1?(t="",i=0):(t=t.slice(0,l),i=t.length-1-t.lastIndexOf("/")),s=a,n=0;continue}}else if(t.length===2||t.length===1){t="",i=0,s=a,n=0;continue}}e&&(t.length>0?t+="/..":t="..",i=2)}else t.length>0?t+="/"+r.slice(s+1,a):t=r.slice(s+1,a),i=a-s-1;s=a,n=0}else o===46&&n!==-1?++n:n=-1}return t}function Kp(r,e){var t=e.dir||e.root,i=e.base||(e.name||"")+(e.ext||"");return t?t===e.root?t+i:t+r+i:i}var Li={resolve:function(){for(var e="",t=!1,i,s=arguments.length-1;s>=-1&&!t;s--){var n;s>=0?n=arguments[s]:(i===void 0&&(i=process.cwd()),n=i),xt(n),n.length!==0&&(e=n+"/"+e,t=n.charCodeAt(0)===47)}return e=Ec(e,!t),t?e.length>0?"/"+e:"/":e.length>0?e:"."},normalize:function(e){if(xt(e),e.length===0)return".";var t=e.charCodeAt(0)===47,i=e.charCodeAt(e.length-1)===47;return e=Ec(e,!t),e.length===0&&!t&&(e="."),e.length>0&&i&&(e+="/"),t?"/"+e:e},isAbsolute:function(e){return xt(e),e.length>0&&e.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var e,t=0;t<arguments.length;++t){var i=arguments[t];xt(i),i.length>0&&(e===void 0?e=i:e+="/"+i)}return e===void 0?".":Li.normalize(e)},relative:function(e,t){if(xt(e),xt(t),e===t||(e=Li.resolve(e),t=Li.resolve(t),e===t))return"";for(var i=1;i<e.length&&e.charCodeAt(i)===47;++i);for(var s=e.length,n=s-i,o=1;o<t.length&&t.charCodeAt(o)===47;++o);for(var a=t.length,l=a-o,c=n<l?n:l,d=-1,h=0;h<=c;++h){if(h===c){if(l>c){if(t.charCodeAt(o+h)===47)return t.slice(o+h+1);if(h===0)return t.slice(o+h)}else n>c&&(e.charCodeAt(i+h)===47?d=h:h===0&&(d=0));break}var u=e.charCodeAt(i+h),f=t.charCodeAt(o+h);if(u!==f)break;u===47&&(d=h)}var g="";for(h=i+d+1;h<=s;++h)(h===s||e.charCodeAt(h)===47)&&(g.length===0?g+="..":g+="/..");return g.length>0?g+t.slice(o+d):(o+=d,t.charCodeAt(o)===47&&++o,t.slice(o))},_makeLong:function(e){return e},dirname:function(e){if(xt(e),e.length===0)return".";for(var t=e.charCodeAt(0),i=t===47,s=-1,n=!0,o=e.length-1;o>=1;--o)if(t=e.charCodeAt(o),t===47){if(!n){s=o;break}}else n=!1;return s===-1?i?"/":".":i&&s===1?"//":e.slice(0,s)},basename:function(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');xt(e);var i=0,s=-1,n=!0,o;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var a=t.length-1,l=-1;for(o=e.length-1;o>=0;--o){var c=e.charCodeAt(o);if(c===47){if(!n){i=o+1;break}}else l===-1&&(n=!1,l=o+1),a>=0&&(c===t.charCodeAt(a)?--a===-1&&(s=o):(a=-1,s=l))}return i===s?s=l:s===-1&&(s=e.length),e.slice(i,s)}else{for(o=e.length-1;o>=0;--o)if(e.charCodeAt(o)===47){if(!n){i=o+1;break}}else s===-1&&(n=!1,s=o+1);return s===-1?"":e.slice(i,s)}},extname:function(e){xt(e);for(var t=-1,i=0,s=-1,n=!0,o=0,a=e.length-1;a>=0;--a){var l=e.charCodeAt(a);if(l===47){if(!n){i=a+1;break}continue}s===-1&&(n=!1,s=a+1),l===46?t===-1?t=a:o!==1&&(o=1):t!==-1&&(o=-1)}return t===-1||s===-1||o===0||o===1&&t===s-1&&t===i+1?"":e.slice(t,s)},format:function(e){if(e===null||typeof e!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return Kp("/",e)},parse:function(e){xt(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return t;var i=e.charCodeAt(0),s=i===47,n;s?(t.root="/",n=1):n=0;for(var o=-1,a=0,l=-1,c=!0,d=e.length-1,h=0;d>=n;--d){if(i=e.charCodeAt(d),i===47){if(!c){a=d+1;break}continue}l===-1&&(c=!1,l=d+1),i===46?o===-1?o=d:h!==1&&(h=1):o!==-1&&(h=-1)}return o===-1||l===-1||h===0||h===1&&o===l-1&&o===a+1?l!==-1&&(a===0&&s?t.base=t.name=e.slice(1,l):t.base=t.name=e.slice(a,l)):(a===0&&s?(t.name=e.slice(1,o),t.base=e.slice(1,l)):(t.name=e.slice(a,o),t.base=e.slice(a,l)),t.ext=e.slice(o,l)),a>0?t.dir=e.slice(0,a-1):s&&(t.dir="/"),t},sep:"/",delimiter:":",win32:null,posix:null};Li.posix=Li;var Xp=Li;const{basename:Sc,extname:qp}=Xp;class Zp{constructor(){let e=(()=>typeof Nf>"u")(),t="image/png",i="image/jpeg",s="image/jpeg",n="image/webp",o="application/pdf",a="image/svg+xml";Object.assign(this,{toMime:this.toMime.bind(this),fromMime:this.fromMime.bind(this),expected:e?'"png", "jpg", or "webp"':'"png", "jpg", "pdf", or "svg"',formats:e?{png:t,jpg:i,jpeg:s,webp:n}:{png:t,jpg:i,jpeg:s,pdf:o,svg:a},mimes:e?{[t]:"png",[i]:"jpg",[n]:"webp"}:{[t]:"png",[i]:"jpg",[o]:"pdf",[a]:"svg"}})}toMime(e){return this.formats[(e||"").replace(/^\./,"").toLowerCase()]}fromMime(e){return this.mimes[e]}}function Jp(r,{filename:e="",extension:t="",format:p,page:s,quality:n,matte:o,density:a,outline:l,archive:f}={}){var{fromMime:d,toMime:h,expected:u}=new Zp,f=f||"canvas",g=p||t.replace(/@\d+x$/i,"")||qp(e),p=d(h(g)||g),m=h(p),A=r.length;if(!g)throw new Error("Cannot determine image format (use a filename extension or 'format' argument)");if(!p)throw new Error(`Unsupported file format "${g}" (expected ${u})`);if(!A)throw new RangeError("Canvas has no associated contexts (try calling getContext or newPage first)");let T,b,y=e.replace(/{(\d*)}/g,(E,S)=>(b=!0,S=parseInt(S,10),T=isFinite(S)?S:isFinite(T)?T:-1,"{}")),x=s>0?s-1:s<0?A+s:void 0;if(isFinite(x)&&x<0||x>=A)throw new RangeError(A==1?`Canvas only has a ‘page 1’ (${x} is out of bounds)`:`Canvas has pages 1–${A} (${x} is out of bounds)`);if(r=isFinite(x)?[r[x]]:b||p=="pdf"?r:r.slice(-1),n===void 0)n=.92;else if(typeof n!="number"||!isFinite(n)||n<0||n>1)throw new TypeError("The quality option must be an number in the 0.0–1.0 range");if(a===void 0){let E=(t||Sc(e,g)).match(/@(\d+)x$/i);a=E?parseInt(E[1],10):1}else if(typeof a!="number"||!Number.isInteger(a)||a<1)throw new TypeError("The density option must be a non-negative integer");return l===void 0?l=!0:p=="svg"&&(l=!!l),{filename:e,pattern:y,format:p,mime:m,pages:r,padding:T,quality:n,matte:o,density:a,outline:l,archive:f}}class rr{static for(e){return new rr().append(e).get()}constructor(){this.crc=-1}get(){return~this.crc}append(e){for(var t=this.crc|0,i=this.table,s=0,n=e.length|0;s<n;s++)t=t>>>8^i[(t^e[s])&255];return this.crc=t,this}}rr.prototype.table=(()=>{var r,e,t,i=[];for(r=0;r<256;r++){for(t=r,e=0;e<8;e++)t=t&1?t>>>1^3988292384:t>>>1;i[r]=t}return i})();function Xn(r){let e=new Uint8Array(r),t=new DataView(e.buffer),i={array:e,view:t,size:r,set8(s,n){return t.setUint8(s,n),i},set16(s,n){return t.setUint16(s,n,!0),i},set32(s,n){return t.setUint32(s,n,!0),i},bytes(s,n){return e.set(n,s),i}};return i}const nr=class nr{constructor(e){let t=new Date;Object.assign(this,{directory:e,offset:0,files:[],time:(t.getHours()<<6|t.getMinutes())<<5|t.getSeconds()/2,date:(t.getFullYear()-1980<<4|t.getMonth()+1)<<5|t.getDate()}),this.add(e)}async add(e,t){let i=!t,s=nr.encoder.encode(`${this.directory}/${i?"":e}`),n=new Uint8Array(i?0:await t.arrayBuffer()),o=30+s.length,a=o+n.length,l=16,{offset:c}=this,d=Xn(26).set32(0,134742036).set16(6,this.time).set16(8,this.date).set32(10,rr.for(n)).set32(14,n.length).set32(18,n.length).set16(22,s.length);c+=o;let h=Xn(o+n.length+l).set32(0,67324752).bytes(4,d.array).bytes(30,s).bytes(o,n);c+=n.length,h.set32(a,134695760).bytes(a+4,d.array.slice(10,22)),c+=l,this.files.push({offset:c,folder:i,name:s,header:d,payload:h}),this.offset=c}toBuffer(){let e=this.files.reduce((h,{name:u})=>46+u.length+h,0),t=Xn(e+22),i=0;for(var{offset:s,name:n,header:o,folder:a}of this.files)t.set32(i,33639248).set16(i+4,20).bytes(i+6,o.array).set8(i+38,a?16:0).set32(i+42,s).bytes(i+46,n),i+=46+n.length;t.set32(i,101010256).set16(i+8,this.files.length).set16(i+10,this.files.length).set32(i+12,e).set32(i+16,this.offset);let l=new Uint8Array(this.offset+t.size),c=0;for(var{payload:d}of this.files)l.set(d.array,c),c+=d.size;return l.set(t.array,c),l}get blob(){return new Blob([this.toBuffer()],{type:"application/zip"})}};kc(nr,"encoder",new TextEncoder);let qn=nr;const Zn=(r,e,t,i)=>{if(i){let{width:s,height:n}=r,o=Object.assign(document.createElement("canvas"),{width:s,height:n}),a=o.getContext("2d");a.fillStyle=i,a.fillRect(0,0,s,n),a.drawImage(r,0,0),r=o}return new Promise((s,n)=>r.toBlob(s,e,t))},Qp=(...r)=>Zn(...r).then(e=>e.arrayBuffer()),_p=async(r,e,t,i,s)=>{Ic(s,await Zn(r,e,t,i))},$p=async(r,e,t,i,s,n,o)=>{let a=d=>n.replace("{}",String(d+1).padStart(o,"0")),l=Sc(s,".zip")||"archive",c=new qn(l);await Promise.all(r.map(async(d,h)=>{let u=a(h);await c.add(u,await Zn(d,e,t,i))})),Ic(`${l}.zip`,c.blob)},Ic=(r,e)=>{const t=window.URL.createObjectURL(e),i=document.createElement("a");i.style.display="none",i.href=t,i.setAttribute("download",r),typeof i.download>"u"&&i.setAttribute("target","_blank"),document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(()=>window.URL.revokeObjectURL(t),100)};var em={asBuffer:Qp,asDownload:_p,asZipDownload:$p,atScale:(r,e,t)=>r.map(i=>{if(e==1&&!t)return i.canvas;let s=document.createElement("canvas"),n=s.getContext("2d"),o=i.canvas?i.canvas:i;return s.width=o.width*e,s.height=o.height*e,t&&(n.fillStyle=t,n.fillRect(0,0,s.width,s.height)),n.scale(e,e),n.drawImage(o,0,0),s}),options:Jp};const{asBuffer:Jn,asDownload:tm,asZipDownload:im,atScale:Qn,options:_n}=em,Cc=Symbol.for("toDataURL"),sm=r=>{let e=Object.assign(new wc,{crossOrigin:"Anonymous",src:r});return e.decode().then(()=>e)};class rm{constructor(e,t){let i=document.createElement("canvas"),s=[];Object.defineProperty(i,"async",{value:!0,writable:!1,enumerable:!0});for(var[n,o]of Object.entries({png:()=>Jn(i,"image/png"),jpg:()=>Jn(i,"image/jpeg"),pages:()=>s.concat(i).map(a=>a.getContext("2d"))}))Object.defineProperty(i,n,{get:o});return Object.assign(i,{width:e,height:t,newPage(...a){var{width:c,height:d}=i,l=Object.assign(document.createElement("canvas"),{width:c,height:d});l.getContext("2d").drawImage(i,0,0),s.push(l);var[c,d]=a.length?a:[c,d];return Object.assign(i,{width:c,height:d}).getContext("2d")},saveAs(a,l){l=typeof l=="number"?{quality:l}:l;let c=_n(this.pages,{filename:a,...l}),{pattern:d,padding:h,mime:u,quality:f,matte:g,density:p,archive:m}=c,A=Qn(c.pages,p);return h==null?tm(A[0],u,f,g,a):im(A,u,f,g,m,d,h)},toBuffer(a="png",l={}){l=typeof l=="number"?{quality:l}:l;let c=_n(this.pages,{extension:a,...l}),{mime:d,quality:h,matte:u,pages:f,density:g}=c,p=Qn(f,g,u)[0];return Jn(p,d,h,u)},[Cc]:i.toDataURL.bind(i),toDataURL(a="png",l={}){l=typeof l=="number"?{quality:l}:l;let c=_n(this.pages,{extension:a,...l}),{mime:d,quality:h,matte:u,pages:f,density:g}=c,p=Qn(f,g,u)[0],m=p[p===i?Cc:"toDataURL"](d,h);return Promise.resolve(m)}})}}const{CanvasRenderingContext2D:nm,CanvasGradient:om,CanvasPattern:am,Image:wc,ImageData:lm,Path2D:cm,DOMMatrix:dm,DOMRect:hm,DOMPoint:um}=window;var Lc={Canvas:rm,loadImage:sm,CanvasRenderingContext2D:nm,CanvasGradient:om,CanvasPattern:am,Image:wc,ImageData:lm,Path2D:cm,DOMMatrix:dm,DOMRect:hm,DOMPoint:um};const Rc=Et({__proto__:null,default:El(Lc)},[Lc]);return Object.defineProperty(nt,Symbol.toStringTag,{value:"Module"}),nt}({});
1350
+ `}};pe.styles=[le.styles??[]],Se([N({type:String})],pe.prototype,"src",2),Se([N({type:String})],pe.prototype,"playlist",2),Se([N({type:String})],pe.prototype,"track",2),Se([N({type:String})],pe.prototype,"poster",2),Se([N({type:Object})],pe.prototype,"data",2),Se([N({type:String})],pe.prototype,"vouchHashId",2),Se([N({type:String})],pe.prototype,"preload",2),Se([N({type:Boolean})],pe.prototype,"autoplay",2),Se([N({type:Boolean})],pe.prototype,"enableTracking",2),Se([N({type:String})],pe.prototype,"trackingSource",2),Se([N({type:String})],pe.prototype,"env",2),Se([N({type:String})],pe.prototype,"apiKey",2),Se([N({type:String})],pe.prototype,"type",2),Se([N({type:String})],pe.prototype,"format",2),Se([N({type:Number})],pe.prototype,"resolution",2),Se([N({type:Number})],pe.prototype,"aspectRatio",2),Se([N({type:String})],pe.prototype,"headerSubtitle",2),Se([N({type:Boolean})],pe.prototype,"headerShortName",2),Se([N({type:Boolean})],pe.prototype,"headerBrandLogo",2),Se([N({type:Array})],pe.prototype,"controls",2),pe=Se([Ge("vmp-media-player")],pe);var zp=Object.defineProperty,Wp=Object.getOwnPropertyDescriptor,Yp=(r,e,t,i)=>{for(var s=i>1?void 0:i?Wp(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&zp(e,t,s),s};nt.InlineEmbed=class extends pe{},nt.InlineEmbed=Yp([$c("vembed-inline")],nt.InlineEmbed);function xt(r){if(typeof r!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(r))}function Ec(r,e){for(var t="",i=0,s=-1,n=0,o,a=0;a<=r.length;++a){if(a<r.length)o=r.charCodeAt(a);else{if(o===47)break;o=47}if(o===47){if(!(s===a-1||n===1))if(s!==a-1&&n===2){if(t.length<2||i!==2||t.charCodeAt(t.length-1)!==46||t.charCodeAt(t.length-2)!==46){if(t.length>2){var l=t.lastIndexOf("/");if(l!==t.length-1){l===-1?(t="",i=0):(t=t.slice(0,l),i=t.length-1-t.lastIndexOf("/")),s=a,n=0;continue}}else if(t.length===2||t.length===1){t="",i=0,s=a,n=0;continue}}e&&(t.length>0?t+="/..":t="..",i=2)}else t.length>0?t+="/"+r.slice(s+1,a):t=r.slice(s+1,a),i=a-s-1;s=a,n=0}else o===46&&n!==-1?++n:n=-1}return t}function Kp(r,e){var t=e.dir||e.root,i=e.base||(e.name||"")+(e.ext||"");return t?t===e.root?t+i:t+r+i:i}var Ri={resolve:function(){for(var e="",t=!1,i,s=arguments.length-1;s>=-1&&!t;s--){var n;s>=0?n=arguments[s]:(i===void 0&&(i=process.cwd()),n=i),xt(n),n.length!==0&&(e=n+"/"+e,t=n.charCodeAt(0)===47)}return e=Ec(e,!t),t?e.length>0?"/"+e:"/":e.length>0?e:"."},normalize:function(e){if(xt(e),e.length===0)return".";var t=e.charCodeAt(0)===47,i=e.charCodeAt(e.length-1)===47;return e=Ec(e,!t),e.length===0&&!t&&(e="."),e.length>0&&i&&(e+="/"),t?"/"+e:e},isAbsolute:function(e){return xt(e),e.length>0&&e.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var e,t=0;t<arguments.length;++t){var i=arguments[t];xt(i),i.length>0&&(e===void 0?e=i:e+="/"+i)}return e===void 0?".":Ri.normalize(e)},relative:function(e,t){if(xt(e),xt(t),e===t||(e=Ri.resolve(e),t=Ri.resolve(t),e===t))return"";for(var i=1;i<e.length&&e.charCodeAt(i)===47;++i);for(var s=e.length,n=s-i,o=1;o<t.length&&t.charCodeAt(o)===47;++o);for(var a=t.length,l=a-o,c=n<l?n:l,d=-1,h=0;h<=c;++h){if(h===c){if(l>c){if(t.charCodeAt(o+h)===47)return t.slice(o+h+1);if(h===0)return t.slice(o+h)}else n>c&&(e.charCodeAt(i+h)===47?d=h:h===0&&(d=0));break}var u=e.charCodeAt(i+h),f=t.charCodeAt(o+h);if(u!==f)break;u===47&&(d=h)}var g="";for(h=i+d+1;h<=s;++h)(h===s||e.charCodeAt(h)===47)&&(g.length===0?g+="..":g+="/..");return g.length>0?g+t.slice(o+d):(o+=d,t.charCodeAt(o)===47&&++o,t.slice(o))},_makeLong:function(e){return e},dirname:function(e){if(xt(e),e.length===0)return".";for(var t=e.charCodeAt(0),i=t===47,s=-1,n=!0,o=e.length-1;o>=1;--o)if(t=e.charCodeAt(o),t===47){if(!n){s=o;break}}else n=!1;return s===-1?i?"/":".":i&&s===1?"//":e.slice(0,s)},basename:function(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');xt(e);var i=0,s=-1,n=!0,o;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var a=t.length-1,l=-1;for(o=e.length-1;o>=0;--o){var c=e.charCodeAt(o);if(c===47){if(!n){i=o+1;break}}else l===-1&&(n=!1,l=o+1),a>=0&&(c===t.charCodeAt(a)?--a===-1&&(s=o):(a=-1,s=l))}return i===s?s=l:s===-1&&(s=e.length),e.slice(i,s)}else{for(o=e.length-1;o>=0;--o)if(e.charCodeAt(o)===47){if(!n){i=o+1;break}}else s===-1&&(n=!1,s=o+1);return s===-1?"":e.slice(i,s)}},extname:function(e){xt(e);for(var t=-1,i=0,s=-1,n=!0,o=0,a=e.length-1;a>=0;--a){var l=e.charCodeAt(a);if(l===47){if(!n){i=a+1;break}continue}s===-1&&(n=!1,s=a+1),l===46?t===-1?t=a:o!==1&&(o=1):t!==-1&&(o=-1)}return t===-1||s===-1||o===0||o===1&&t===s-1&&t===i+1?"":e.slice(t,s)},format:function(e){if(e===null||typeof e!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return Kp("/",e)},parse:function(e){xt(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return t;var i=e.charCodeAt(0),s=i===47,n;s?(t.root="/",n=1):n=0;for(var o=-1,a=0,l=-1,c=!0,d=e.length-1,h=0;d>=n;--d){if(i=e.charCodeAt(d),i===47){if(!c){a=d+1;break}continue}l===-1&&(c=!1,l=d+1),i===46?o===-1?o=d:h!==1&&(h=1):o!==-1&&(h=-1)}return o===-1||l===-1||h===0||h===1&&o===l-1&&o===a+1?l!==-1&&(a===0&&s?t.base=t.name=e.slice(1,l):t.base=t.name=e.slice(a,l)):(a===0&&s?(t.name=e.slice(1,o),t.base=e.slice(1,l)):(t.name=e.slice(a,o),t.base=e.slice(a,l)),t.ext=e.slice(o,l)),a>0?t.dir=e.slice(0,a-1):s&&(t.dir="/"),t},sep:"/",delimiter:":",win32:null,posix:null};Ri.posix=Ri;var Xp=Ri;const{basename:Sc,extname:qp}=Xp;class Zp{constructor(){let e=(()=>typeof Nf>"u")(),t="image/png",i="image/jpeg",s="image/jpeg",n="image/webp",o="application/pdf",a="image/svg+xml";Object.assign(this,{toMime:this.toMime.bind(this),fromMime:this.fromMime.bind(this),expected:e?'"png", "jpg", or "webp"':'"png", "jpg", "pdf", or "svg"',formats:e?{png:t,jpg:i,jpeg:s,webp:n}:{png:t,jpg:i,jpeg:s,pdf:o,svg:a},mimes:e?{[t]:"png",[i]:"jpg",[n]:"webp"}:{[t]:"png",[i]:"jpg",[o]:"pdf",[a]:"svg"}})}toMime(e){return this.formats[(e||"").replace(/^\./,"").toLowerCase()]}fromMime(e){return this.mimes[e]}}function Jp(r,{filename:e="",extension:t="",format:p,page:s,quality:n,matte:o,density:a,outline:l,archive:f}={}){var{fromMime:d,toMime:h,expected:u}=new Zp,f=f||"canvas",g=p||t.replace(/@\d+x$/i,"")||qp(e),p=d(h(g)||g),m=h(p),A=r.length;if(!g)throw new Error("Cannot determine image format (use a filename extension or 'format' argument)");if(!p)throw new Error(`Unsupported file format "${g}" (expected ${u})`);if(!A)throw new RangeError("Canvas has no associated contexts (try calling getContext or newPage first)");let x,b,y=e.replace(/{(\d*)}/g,(E,S)=>(b=!0,S=parseInt(S,10),x=isFinite(S)?S:isFinite(x)?x:-1,"{}")),T=s>0?s-1:s<0?A+s:void 0;if(isFinite(T)&&T<0||T>=A)throw new RangeError(A==1?`Canvas only has a ‘page 1’ (${T} is out of bounds)`:`Canvas has pages 1–${A} (${T} is out of bounds)`);if(r=isFinite(T)?[r[T]]:b||p=="pdf"?r:r.slice(-1),n===void 0)n=.92;else if(typeof n!="number"||!isFinite(n)||n<0||n>1)throw new TypeError("The quality option must be an number in the 0.0–1.0 range");if(a===void 0){let E=(t||Sc(e,g)).match(/@(\d+)x$/i);a=E?parseInt(E[1],10):1}else if(typeof a!="number"||!Number.isInteger(a)||a<1)throw new TypeError("The density option must be a non-negative integer");return l===void 0?l=!0:p=="svg"&&(l=!!l),{filename:e,pattern:y,format:p,mime:m,pages:r,padding:x,quality:n,matte:o,density:a,outline:l,archive:f}}class rr{static for(e){return new rr().append(e).get()}constructor(){this.crc=-1}get(){return~this.crc}append(e){for(var t=this.crc|0,i=this.table,s=0,n=e.length|0;s<n;s++)t=t>>>8^i[(t^e[s])&255];return this.crc=t,this}}rr.prototype.table=(()=>{var r,e,t,i=[];for(r=0;r<256;r++){for(t=r,e=0;e<8;e++)t=t&1?t>>>1^3988292384:t>>>1;i[r]=t}return i})();function Xn(r){let e=new Uint8Array(r),t=new DataView(e.buffer),i={array:e,view:t,size:r,set8(s,n){return t.setUint8(s,n),i},set16(s,n){return t.setUint16(s,n,!0),i},set32(s,n){return t.setUint32(s,n,!0),i},bytes(s,n){return e.set(n,s),i}};return i}const nr=class nr{constructor(e){let t=new Date;Object.assign(this,{directory:e,offset:0,files:[],time:(t.getHours()<<6|t.getMinutes())<<5|t.getSeconds()/2,date:(t.getFullYear()-1980<<4|t.getMonth()+1)<<5|t.getDate()}),this.add(e)}async add(e,t){let i=!t,s=nr.encoder.encode(`${this.directory}/${i?"":e}`),n=new Uint8Array(i?0:await t.arrayBuffer()),o=30+s.length,a=o+n.length,l=16,{offset:c}=this,d=Xn(26).set32(0,134742036).set16(6,this.time).set16(8,this.date).set32(10,rr.for(n)).set32(14,n.length).set32(18,n.length).set16(22,s.length);c+=o;let h=Xn(o+n.length+l).set32(0,67324752).bytes(4,d.array).bytes(30,s).bytes(o,n);c+=n.length,h.set32(a,134695760).bytes(a+4,d.array.slice(10,22)),c+=l,this.files.push({offset:c,folder:i,name:s,header:d,payload:h}),this.offset=c}toBuffer(){let e=this.files.reduce((h,{name:u})=>46+u.length+h,0),t=Xn(e+22),i=0;for(var{offset:s,name:n,header:o,folder:a}of this.files)t.set32(i,33639248).set16(i+4,20).bytes(i+6,o.array).set8(i+38,a?16:0).set32(i+42,s).bytes(i+46,n),i+=46+n.length;t.set32(i,101010256).set16(i+8,this.files.length).set16(i+10,this.files.length).set32(i+12,e).set32(i+16,this.offset);let l=new Uint8Array(this.offset+t.size),c=0;for(var{payload:d}of this.files)l.set(d.array,c),c+=d.size;return l.set(t.array,c),l}get blob(){return new Blob([this.toBuffer()],{type:"application/zip"})}};kc(nr,"encoder",new TextEncoder);let qn=nr;const Zn=(r,e,t,i)=>{if(i){let{width:s,height:n}=r,o=Object.assign(document.createElement("canvas"),{width:s,height:n}),a=o.getContext("2d");a.fillStyle=i,a.fillRect(0,0,s,n),a.drawImage(r,0,0),r=o}return new Promise((s,n)=>r.toBlob(s,e,t))},Qp=(...r)=>Zn(...r).then(e=>e.arrayBuffer()),_p=async(r,e,t,i,s)=>{Ic(s,await Zn(r,e,t,i))},$p=async(r,e,t,i,s,n,o)=>{let a=d=>n.replace("{}",String(d+1).padStart(o,"0")),l=Sc(s,".zip")||"archive",c=new qn(l);await Promise.all(r.map(async(d,h)=>{let u=a(h);await c.add(u,await Zn(d,e,t,i))})),Ic(`${l}.zip`,c.blob)},Ic=(r,e)=>{const t=window.URL.createObjectURL(e),i=document.createElement("a");i.style.display="none",i.href=t,i.setAttribute("download",r),typeof i.download>"u"&&i.setAttribute("target","_blank"),document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(()=>window.URL.revokeObjectURL(t),100)};var em={asBuffer:Qp,asDownload:_p,asZipDownload:$p,atScale:(r,e,t)=>r.map(i=>{if(e==1&&!t)return i.canvas;let s=document.createElement("canvas"),n=s.getContext("2d"),o=i.canvas?i.canvas:i;return s.width=o.width*e,s.height=o.height*e,t&&(n.fillStyle=t,n.fillRect(0,0,s.width,s.height)),n.scale(e,e),n.drawImage(o,0,0),s}),options:Jp};const{asBuffer:Jn,asDownload:tm,asZipDownload:im,atScale:Qn,options:_n}=em,Cc=Symbol.for("toDataURL"),sm=r=>{let e=Object.assign(new wc,{crossOrigin:"Anonymous",src:r});return e.decode().then(()=>e)};class rm{constructor(e,t){let i=document.createElement("canvas"),s=[];Object.defineProperty(i,"async",{value:!0,writable:!1,enumerable:!0});for(var[n,o]of Object.entries({png:()=>Jn(i,"image/png"),jpg:()=>Jn(i,"image/jpeg"),pages:()=>s.concat(i).map(a=>a.getContext("2d"))}))Object.defineProperty(i,n,{get:o});return Object.assign(i,{width:e,height:t,newPage(...a){var{width:c,height:d}=i,l=Object.assign(document.createElement("canvas"),{width:c,height:d});l.getContext("2d").drawImage(i,0,0),s.push(l);var[c,d]=a.length?a:[c,d];return Object.assign(i,{width:c,height:d}).getContext("2d")},saveAs(a,l){l=typeof l=="number"?{quality:l}:l;let c=_n(this.pages,{filename:a,...l}),{pattern:d,padding:h,mime:u,quality:f,matte:g,density:p,archive:m}=c,A=Qn(c.pages,p);return h==null?tm(A[0],u,f,g,a):im(A,u,f,g,m,d,h)},toBuffer(a="png",l={}){l=typeof l=="number"?{quality:l}:l;let c=_n(this.pages,{extension:a,...l}),{mime:d,quality:h,matte:u,pages:f,density:g}=c,p=Qn(f,g,u)[0];return Jn(p,d,h,u)},[Cc]:i.toDataURL.bind(i),toDataURL(a="png",l={}){l=typeof l=="number"?{quality:l}:l;let c=_n(this.pages,{extension:a,...l}),{mime:d,quality:h,matte:u,pages:f,density:g}=c,p=Qn(f,g,u)[0],m=p[p===i?Cc:"toDataURL"](d,h);return Promise.resolve(m)}})}}const{CanvasRenderingContext2D:nm,CanvasGradient:om,CanvasPattern:am,Image:wc,ImageData:lm,Path2D:cm,DOMMatrix:dm,DOMRect:hm,DOMPoint:um}=window;var Lc={Canvas:rm,loadImage:sm,CanvasRenderingContext2D:nm,CanvasGradient:om,CanvasPattern:am,Image:wc,ImageData:lm,Path2D:cm,DOMMatrix:dm,DOMRect:hm,DOMPoint:um};const Rc=Et({__proto__:null,default:El(Lc)},[Lc]);return Object.defineProperty(nt,Symbol.toStringTag,{value:"Module"}),nt}({});
1351
1351
  //# sourceMappingURL=embeds.iife.js.map