@vouchfor/embeds 5.0.4 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2473,7 +2473,7 @@ vec4 transition(vec2 uv) {
2473
2473
  return mix(a, b, step(0.0+p.y,progress));
2474
2474
  }
2475
2475
  `,author:"Jake Nelson",license:"MIT",createdAt:"Wed, 1 Nov 2017 15:24:36 -0500",updatedAt:"Thu, 2 Nov 2017 18:37:42 -0500"}];const Ih=Fa(dv);var vh;function fv(r){if(typeof r=="string"){const[e,t]=r.split(":");return Math.min(parseFloat(e),parseFloat(t))}return r}function gv(r){if(typeof r=="string"){const[e,t]=r.split(":"),i=parseFloat(e),n=parseFloat(t);return i/n}return r}function dl({resolution:r,aspectRatio:e}){const t=fv(r),i=gv(e),n=i>=1,s=Math.min(n?t*i:t/i,t),o=Math.max(n?t*i:t/i,t);return{resolution:t,aspectRatio:i,height:n?s:o,width:n?o:s}}const yh={linear:xm,easeIn:ka,easeInOut:_m,easeOut:Qm,circIn:gu,circInOut:wm,circOut:pu,backIn:Ma,backInOut:Dm,backOut:Rm,anticipate:Lm,bounceIn:Pm,bounceInOut:Nm,bounceOut:Ms};ws((r,e,{clamp:t=!0,ease:i="easeIn",...n}={})=>ym(r,e,{...n,clamp:t,ease:yh[i]}),{cacheKey:([r,e,t])=>JSON.stringify({from:r,to:e,options:t})});function pv({animation:r,sceneTime:e}){const t=r.keyframes;if(!t||t.length===0)return null;const i=[...t].sort((s,o)=>s.time-o.time);if(e<i[0].time)return null;const n=i[i.length-1];if(e>=n.time)return r.renderer.processor.getTargetState(n.value);for(let s=0;s<i.length-1;s++){const o=i[s],a=i[s+1];if(e>=o.time&&e<=a.time){const l=a.time-o.time,A=l===0?0:(e-o.time)/l,u=o.easing||"linear",c=r.renderer.processor.getTargetState(o.value);return r.renderer.processor.interpolateState({easing:u,progress:A,from:c,value:a.value})}}return null}function mv({layout:r,sceneTime:e,animations:t}){var i,n,s,o,a,l,A,u,c,h,d;let f={clip:null,opacity:((i=r==null?void 0:r.transform)==null?void 0:i.opacity)??1,translation:{x:((s=(n=r==null?void 0:r.transform)==null?void 0:n.translate)==null?void 0:s.x)??0,y:((a=(o=r==null?void 0:r.transform)==null?void 0:o.translate)==null?void 0:a.y)??0},scale:((l=r==null?void 0:r.transform)==null?void 0:l.scale)??1,rotation:((A=r==null?void 0:r.transform)==null?void 0:A.rotation)??0,dimensions:{widthRatio:((c=(u=r==null?void 0:r.transform)==null?void 0:u.dimension)==null?void 0:c.widthRatio)??1,heightRatio:((d=(h=r==null?void 0:r.transform)==null?void 0:h.dimension)==null?void 0:d.heightRatio)??1}};if(!t)return f;for(const g of Object.values(t)){const p=pv({animation:g,sceneTime:e});p&&(f={...f,...p})}return f}let io;const Ev=new Uint8Array(16);function Iv(){if(!io&&(io=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!io))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return io(Ev)}const _t=[];for(let r=0;r<256;++r)_t.push((r+256).toString(16).slice(1));function vv(r,e=0){return _t[r[e+0]]+_t[r[e+1]]+_t[r[e+2]]+_t[r[e+3]]+"-"+_t[r[e+4]]+_t[r[e+5]]+"-"+_t[r[e+6]]+_t[r[e+7]]+"-"+_t[r[e+8]]+_t[r[e+9]]+"-"+_t[r[e+10]]+_t[r[e+11]]+_t[r[e+12]]+_t[r[e+13]]+_t[r[e+14]]+_t[r[e+15]]}const Ch={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function yv(r,e,t){if(Ch.randomUUID&&!r)return Ch.randomUUID();r=r||{};const i=r.random||(r.rng||Iv)();return i[6]=i[6]&15|64,i[8]=i[8]&63|128,vv(i)}function Cv(r=.4,e=.4){const t=Math.max(.1,Math.min(.8,r)),i=Math.max(.2,Math.min(.6,e)),s=(1-t)/2,a=1-i;return[{x:0,y:s},{x:a,y:s},{x:a,y:0},{x:1,y:.5},{x:a,y:1},{x:a,y:1-s},{x:0,y:1-s}]}const ro=64;function Bv(){const r=[],e={x:.5,y:.5},t=.5;for(let i=0;i<ro;i++){const n=i/ro*2*Math.PI,s=e.x+t*Math.cos(n),o=e.y+t*Math.sin(n);r.push({x:s,y:o})}return r}function Tv(r=1){const e=[],t={x:.5,y:.5};let i,n;r>=1?(i=.5,n=.5/r):(i=.5*r,n=.5);for(let s=0;s<ro;s++){const o=s/ro*2*Math.PI,a=t.x+i*Math.cos(o),l=t.y+n*Math.sin(o);e.push({x:a,y:l})}return e}function bv(){const r=[];for(let t=0;t<=100;t++){const i=t/100*2*Math.PI,n=16*Math.sin(i)**3,s=-(13*Math.cos(i)-5*Math.cos(2*i)-2*Math.cos(3*i)-Math.cos(4*i)),o=(n+16)/32,a=(s+13)/26;r.push({x:o,y:a})}return r}function Bh(r=0,e=1){if(r===0)return[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}];const t=r*Math.PI/180,i=Math.tan(t)/e;return[{x:Math.max(0,Math.min(1,0+i)),y:0},{x:Math.max(0,Math.min(1,1+i)),y:0},{x:Math.max(0,Math.min(1,1-i)),y:1},{x:Math.max(0,Math.min(1,0-i)),y:1}]}function no(r){if(r<3)throw new Error("A polygon must have at least 3 sides");const e=[],t=[];for(let A=0;A<r;A++){const u=A*2*Math.PI/r-Math.PI/2,c=Math.cos(u),h=Math.sin(u);t.push({x:c,y:h})}const i=Math.min(...t.map(A=>A.x)),n=Math.max(...t.map(A=>A.x)),s=Math.min(...t.map(A=>A.y)),o=Math.max(...t.map(A=>A.y)),a=n-i,l=o-s;for(const A of t){const u=(A.x-i)/a,c=(A.y-s)/l;e.push({x:u,y:c})}return e}function Th(r=90){const e=r*Math.PI/180,i=.5/Math.tan(e),s=1/(1+Math.abs(i)*2),o=i*s;return[{x:.5+o,y:0},{x:1,y:.5},{x:.5-o,y:1},{x:0,y:.5}]}function Sv(r=5,e=.4){const t=[];for(let n=0;n<r*2;n++){const s=n*Math.PI/r-Math.PI/2,o=n%2===0?.5:e,a=.5+o*Math.cos(s),l=.5+o*Math.sin(s);t.push({x:a,y:l})}return t}function xv(r="isosceles",e={}){switch(r){case"equilateral":return Qv();case"isosceles":return bh(e.baseAngle??60);case"right":return _v(e.rightAnglePosition??"bottom-left");case"scalene":return wv(e.angles??[60,60,60])}}function Qv(){return[{x:.5,y:0},{x:0,y:1},{x:1,y:1}]}function bh(r){const e=r*Math.PI/180,t=.5/Math.tan(e),i=Math.max(.1,Math.min(2,t));return[{x:.5,y:1-Math.min(1,i)},{x:0,y:1},{x:1,y:1}]}function _v(r){switch(r){case"top":return[{x:.5,y:0},{x:0,y:1},{x:1,y:1}];case"bottom-left":return[{x:.5,y:0},{x:0,y:1},{x:1,y:1}];case"bottom-right":return[{x:.5,y:0},{x:0,y:1},{x:1,y:1}]}}function wv(r){return bh(r[0])}function Rv(r={},e=1){const{type:t="rectangle",customPolygon:i,parallelogram:n,triangle:s,rhombus:o,arrow:a,star:l,regularPolygon:A}=r;switch(t){case"rectangle":return Bh(0,e);case"parallelogram":return Bh((n==null?void 0:n.angle)??30,e);case"triangle":return xv((s==null?void 0:s.type)??"isosceles",{baseAngle:s==null?void 0:s.baseAngle,angles:s==null?void 0:s.angles,rightAnglePosition:s==null?void 0:s.rightAnglePosition});case"rhombus":return Th((o==null?void 0:o.angle)??90);case"diamond":return Th(90);case"pentagon":return no(5);case"hexagon":return no(6);case"octagon":return no(8);case"star":return Sv((l==null?void 0:l.points)??5,(l==null?void 0:l.innerRadius)??.4);case"arrow":return Cv((a==null?void 0:a.shaftRatio)??.4,(a==null?void 0:a.headRatio)??.4);case"heart":return bv();case"circle":return Bv();case"ellipse":return Tv(e);case"custom-polygon":if(!(i!=null&&i.points)||i.points.length<3)throw new Error("Custom polygon must have at least 3 points");return i.points;default:return no((A==null?void 0:A.sides)??6)}}function Dv(r,e){let t=!1;const i=r.x,n=r.y;for(let s=0,o=e.length-1;s<e.length;o=s++){const a=e[s].x,l=e[s].y,A=e[o].x,u=e[o].y;l>n!=u>n&&i<(A-a)*(n-l)/(u-l)+a&&(t=!t)}return t}function Lv(r,e){let t=1,i=0;const n=200;for(let s=0;s<=n;s++){const o=s/n;Dv({x:o,y:r},e)&&(t=Math.min(t,o),i=Math.max(i,o))}return i>=t?{left:t,right:i}:null}function kv(r){const e=Math.min(...r.map(l=>l.y)),t=Math.max(...r.map(l=>l.y));let i={x:0,y:0,width:0,height:0},n=0;const s=200,o=(t-e)/s,a=[];for(let l=0;l<=s;l++){const A=e+l*o;a.push({y:A,span:Lv(A,r)})}for(let l=0;l<a.length-1;l++){const A=a[l].y;for(let u=l+1;u<a.length;u++){const h=a[u].y-A;let d=0,f=1,g=!0;const p=Math.min(5,u-l+1);for(let v=0;v<p;v++){const B=l+Math.floor(v/(p-1)*(u-l)),C=a[B].span;if(C){if(d=Math.max(d,C.left),f=Math.min(f,C.right),d>=f){g=!1;break}}else{g=!1;break}}if(g&&f>d){const v=f-d,B=v*h;B>n&&(n=B,i={x:d,y:A,width:v,height:h})}}}return i}function Mv(r,e=1){const t=Rv(r,e);if(t.length<3)return{top:0,right:0,bottom:0,left:0};if(r.type==="rectangle")return{top:0,right:0,bottom:0,left:0};const i=kv(t),n=i.y,s=i.x,o=1-(i.x+i.width),a=1-(i.y+i.height);return{top:Math.max(0,n),right:Math.max(0,o),bottom:Math.max(0,a),left:Math.max(0,s)}}function Fv(r){return typeof r=="number"?{topLeft:r,topRight:r,bottomRight:r,bottomLeft:r}:{topLeft:(r==null?void 0:r.topLeft)??0,topRight:(r==null?void 0:r.topRight)??0,bottomRight:(r==null?void 0:r.bottomRight)??0,bottomLeft:(r==null?void 0:r.bottomLeft)??0}}function Pv(r,e){return typeof r=="number"?{top:r*e,right:r*e,bottom:r*e,left:r*e}:typeof r=="string"?{top:r,right:r,bottom:r,left:r}:{top:typeof r.top=="number"?r.top*e:r.top,right:typeof r.right=="number"?r.right*e:r.right,bottom:typeof r.bottom=="number"?r.bottom*e:r.bottom,left:typeof r.left=="number"?r.left*e:r.left}}function Nv(r,e){return typeof r=="number"?{top:r*e,right:r*e,bottom:r*e,left:r*e}:typeof r=="string"?{top:r,right:r,bottom:r,left:r}:{top:(typeof r.top=="number"?r.top*e:r.top)??0,right:(typeof r.right=="number"?r.right*e:r.right)??0,bottom:(typeof r.bottom=="number"?r.bottom*e:r.bottom)??0,left:(typeof r.left=="number"?r.left*e:r.left)??0}}function Ov(r,e){return typeof r=="number"?{top:r*e,right:r*e,bottom:r*e,left:r*e}:typeof r=="string"?{top:r,right:r,bottom:r,left:r}:{top:(typeof r.top=="number"?r.top*e:r.top)??0,right:(typeof r.right=="number"?r.right*e:r.right)??0,bottom:(typeof r.bottom=="number"?r.bottom*e:r.bottom)??0,left:(typeof r.left=="number"?r.left*e:r.left)??0}}function Uv(r){if(r===null||typeof r!="object")return!1;if(Object.getPrototypeOf(r)===null)return!0;let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}function Gv(r){return r.replace(/\\/g,"\\\\").replace(/\//g,"\\/").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/\f/g,"\\f").replace(/"/g,'\\"')}const $v=Ji(()=>mu.loadYoga());function Sh(r,e,{layout:t,scale:i=1}){const{position:n="relative",inset:s,width:o,height:a,minWidth:l,minHeight:A,maxWidth:u,maxHeight:c,flex:h,flexGrow:d,flexShrink:f,gap:g,margin:p,padding:v,direction:B="column",align:C="start",alignSelf:y,justify:x="start"}=t??{},w={static:r.POSITION_TYPE_STATIC,relative:r.POSITION_TYPE_RELATIVE,absolute:r.POSITION_TYPE_ABSOLUTE};if(e.setPositionType(w[n]),typeof s<"u"){const{top:M,right:j,bottom:X,left:le}=Pv(s,i);typeof M<"u"&&e.setPosition(r.EDGE_TOP,M),typeof j<"u"&&e.setPosition(r.EDGE_RIGHT,j),typeof X<"u"&&e.setPosition(r.EDGE_BOTTOM,X),typeof le<"u"&&e.setPosition(r.EDGE_LEFT,le)}const D={row:r.FLEX_DIRECTION_ROW,column:r.FLEX_DIRECTION_COLUMN,"row-reverse":r.FLEX_DIRECTION_ROW_REVERSE,"column-reverse":r.FLEX_DIRECTION_COLUMN_REVERSE};e.setFlexDirection(D[B]);const F={start:r.ALIGN_FLEX_START,end:r.ALIGN_FLEX_END,center:r.ALIGN_CENTER,stretch:r.ALIGN_STRETCH};e.setAlignItems(F[C]),y&&e.setAlignSelf(F[y]);const O={start:r.JUSTIFY_FLEX_START,end:r.JUSTIFY_FLEX_END,center:r.JUSTIFY_CENTER,"space-between":r.JUSTIFY_SPACE_BETWEEN,"space-around":r.JUSTIFY_SPACE_AROUND,"space-evenly":r.JUSTIFY_SPACE_EVENLY};if(e.setJustifyContent(O[x]),typeof p<"u"){const{top:M,right:j,bottom:X,left:le}=Nv(p,i);e.setMargin(r.EDGE_TOP,M),e.setMargin(r.EDGE_RIGHT,j),e.setMargin(r.EDGE_BOTTOM,X),e.setMargin(r.EDGE_LEFT,le)}if(typeof v<"u"){const{top:M,right:j,bottom:X,left:le}=Ov(v,i);e.setPadding(r.EDGE_TOP,M),e.setPadding(r.EDGE_RIGHT,j),e.setPadding(r.EDGE_BOTTOM,X),e.setPadding(r.EDGE_LEFT,le)}typeof d<"u"||typeof f<"u"?(typeof d<"u"&&e.setFlexGrow(d),typeof f<"u"&&e.setFlexShrink(f)):typeof h<"u"&&e.setFlex(h),e.setGap(r.GUTTER_ALL,(g??0)*i),typeof o<"u"&&e.setWidth(typeof o=="number"?o*i:o),typeof a<"u"&&e.setHeight(typeof a=="number"?a*i:a),typeof l<"u"&&e.setMinWidth(typeof l=="number"?l*i:l),typeof A<"u"&&e.setMinHeight(typeof A=="number"?A*i:A),typeof u<"u"&&e.setMaxWidth(typeof u=="number"?u*i:u),typeof c<"u"&&e.setMaxHeight(typeof c=="number"?c*i:c)}async function xh({id:r,yoga:e,index:t,parent:i,element:n,resolvers:s}){var o,a,l;const{layout:A={},config:u={},options:c={},renderer:h}=n,d=e.Node.create();Sh(e,d,{layout:A}),i.insertChild(d,t);let f=null;s&&((h==null?void 0:h.type)==="text"||(h==null?void 0:h.type)==="caption"||(h==null?void 0:h.type)==="image"||(h==null?void 0:h.type)==="video")&&((h==null?void 0:h.type)==="caption"?f=await((o=s.text)==null?void 0:o.call(s,{id:r,config:u,options:c}))??null:f=await((a=s[h.type])==null?void 0:a.call(s,{id:r,config:u,options:c}))??null);const g=[];for await(const[p,v]of((l=n.children)==null?void 0:l.entries())??[])g.push(await xh({id:r,yoga:e,index:p,parent:d,element:v,resolvers:s}));return{node:d,radius:Fv(A.radius),element:n,renderer:h,config:u,options:c,dependencies:f,childNodes:g}}function Qh(r,e,t=0,i=0){const{top:n,left:s}=r.getComputedLayout(),{top:o,left:a,width:l,height:A}=e.node.getComputedLayout(),u=t+a,c=i+o,h=e.childNodes.map(d=>Qh(r,d,u,c));return{...e,x:s+u,y:n+c,width:l,height:A,childNodes:h}}async function fl({yoga:r,root:e,tree:t,measureCanvas:i}){for await(const{node:n,options:s,dependencies:o,renderer:a,childNodes:l}of t){if(a){const{width:A,height:u}=a;if(A&&i){e.calculateLayout();const c=await A({node:n,options:s,dependencies:o,measureCanvas:i});c&&n.setWidth(c)}if(u&&i){e.calculateLayout();const c=await u({node:n,options:s,dependencies:o,measureCanvas:i});c&&n.setHeight(c)}if(await fl({yoga:r,root:e,tree:l,measureCanvas:i}),s!=null&&s.shape){const c=n.getComputedWidth(),h=n.getComputedHeight(),d=Mv(s.shape,c/h);n.setPadding(r.EDGE_TOP,d.top*h),n.setPadding(r.EDGE_RIGHT,d.right*c),n.setPadding(r.EDGE_BOTTOM,d.bottom*h),n.setPadding(r.EDGE_LEFT,d.left*c)}}e.calculateLayout(),await fl({yoga:r,root:e,tree:l,measureCanvas:i})}}async function _h({id:r,root:e,resolvers:t,measureCanvas:i}){const n=await $v(),s=n.Node.create();Sh(n,s,{layout:e.layout});const o=await xh({id:r,yoga:n,index:0,parent:s,element:e.element,resolvers:t});await fl({yoga:n,root:s,tree:[o],measureCanvas:i});const{top:a,left:l,width:A,height:u}=s.getComputedLayout(),c={root:{x:l,y:a,width:A,height:u},node:Qh(s,o)};return s.freeRecursive(),c}const Hv={type:"audio"},Nn=/(?<value>\d+\.?\d*)(?=px)/;function gl({words:r,spaceMetrics:e,strokeWidth:t=0}){return r.reduce((i,n,s)=>{const o=n.metrics.width+t,a=s<r.length-1?e.width:0;return i+o+a},0)}ws(({context:r,font:e,fontSizes:t,words:i,maxW:n=1/0,strokeWidth:s=0,letterSpacing:o=0})=>{try{r.save(),r.letterSpacing=`${o}px`,r.font=e.replace(Nn,t[0].toString());const a=r.measureText("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");if(i.length<=0)return[];const l=r.measureText(i[0].text);return i.slice(1).reduce((A,u)=>{const c=A[A.length-1],h=r.measureText(u.text),d={...u,metrics:h},f=[...c.words,d],g=gl({strokeWidth:s,words:f,spaceMetrics:c.spaceMetrics});if(g>n){const p=t[A.length%t.length];r.font=e.replace(Nn,p.toString());const v=r.measureText(" "),B=r.measureText(u.text),C=[{...u,metrics:B}],y=r.measureText("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");A=[...A,{allMetrics:y,spaceMetrics:v,lineWidth:gl({strokeWidth:s,spaceMetrics:v,words:C}),font:r.font,words:C,lineHeight:y.actualBoundingBoxAscent+y.actualBoundingBoxDescent+s}]}else A[A.length-1]={...c,lineWidth:g,words:f};return A},[{allMetrics:a,lineWidth:gl({strokeWidth:s,words:[{...i[0],metrics:l}],spaceMetrics:r.measureText(" ")}),lineHeight:a.actualBoundingBoxAscent+a.actualBoundingBoxDescent+s,font:r.font,words:[{...i[0],metrics:l}],spaceMetrics:r.measureText(" ")}])}finally{r.restore()}},{cacheKey:([{font:r,fontSizes:e,words:t,maxW:i,strokeWidth:n,letterSpacing:s}])=>`${r}_${JSON.stringify(e)}_${JSON.stringify(t)}_${i}_${n}_${s}`});function Yv(r){return r.slice(0,1).toUpperCase()+r.slice(1)}const wh=[{family:"Noto Arabic",regex:new RegExp("\\p{Script=Arabic}","u"),url:"https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/NotoSansArabic-VariableFont_wdth%2Cwght.woff2",style:"normal"},{family:"Noto Chinese",regex:new RegExp("\\p{Script=Han}","u"),url:"https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/NotoSansSC-VariableFont_wght.woff2",style:"normal"},{family:"Noto Hebrew",regex:new RegExp("\\p{Script=Hebrew}","u"),url:"https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/NotoSansHebrew-VariableFont_wdth%2Cwght.woff2",style:"normal"},{family:"Noto Hindi",regex:new RegExp("\\p{Script=Devanagari}","u"),url:"https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/NotoSansDevanagari-VariableFont_wdth%2Cwght.woff2",style:"normal"},{family:"Noto Japanese",regex:new RegExp("\\p{Script=Han}|\\p{Script=Katakana}|\\p{Script=Hiragana}","u"),url:"https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/NotoSansJP-VariableFont_wght.woff2",style:"normal"},{family:"Noto Korean",regex:new RegExp("\\p{Script=Hangul}","u"),url:"https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/NotoSansKR-VariableFont_wght.woff2",style:"normal"},{family:"Noto Color Emoji",regex:new RegExp("\\p{Extended_Pictographic}","u"),url:"https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/NotoColorEmoji-Regular.woff2",style:"normal"}];function Vv({text:r,font:e}){let t=e;return wh.forEach(({family:i,regex:n})=>{n.exec(r)&&(t+=`, ${i}`)}),t}const Kv="caption";Object.keys(yh).map(r=>({label:Yv(r),value:r,data:r}));const Wv={type:Kv},qv={type:"image"};function Rh({context:r,word:e,maxW:t=1/0}){const i=[],n=r.measureText(e);if(Math.floor(n.width)<=t)return[{text:e,metrics:n}];for(let s=0;s<e.length;s++){const o=i[i.length-1],a=((o==null?void 0:o.text)??"")+e[s],l=r.measureText(a);l.width<t?i[o?i.length-1:0]={text:a,metrics:l}:i.push({text:e[s],metrics:r.measureText(e[s])})}return i}const Jv=ws(({font:r,context:e,fontSizes:t,text:i,maxW:n=1/0,letterSpacing:s=0})=>{try{return e.save(),e.letterSpacing=`${s}px`,e.font=r.replace(Nn,t[0].toString()),i.split(`
2476
- `).flatMap(a=>{const l=a.split(" ").filter(Boolean);return l.length?l.slice(1).reduce((A,u,c)=>{const d=`${A[A.length-1].text} ${u}`.trim(),f=e.measureText(d);if(f.width>n)A=[...A,...Rh({context:e,word:u,maxW:n})];else{const g=t[c%t.length];e.font=r.replace(Nn,g.toString()),A[A.length-1]={text:d,metrics:f}}return A},Rh({context:e,word:l[0],maxW:n})):{text:"",metrics:e.measureText("")}})}finally{e.restore()}},{cacheKey:([{font:r,fontSizes:e,text:t,maxW:i,letterSpacing:n}])=>`${r}_${JSON.stringify(e)}_${t}_${i}_${n}`});ws(({font:r,text:e,scale:t,context:i,maxW:n,maxH:s,minSize:o,maxSize:a,letterSpacing:l=0})=>{var A,u;let c=0;if(a){c=(o??0)*t;let d=0;for(;a*t>c+1;){c+=1;const f=Jv({font:r,context:i,fontSizes:[c],text:e,maxW:n,letterSpacing:l});if(d=f.reduce((g,p)=>(p.metrics.width>g&&(g=p.metrics.width),g),0),d>n||f.length*c>s){c-=1;break}}}else c=parseFloat(((u=(A=r.match(Nn))==null?void 0:A.groups)==null?void 0:u.value)??"0")*t;return c},{cacheKey:([{font:r,text:e,scale:t,maxW:i,maxH:n,minSize:s,maxSize:o,letterSpacing:a}])=>`${r}_${e}_${s}_${o}_${t}_${i}_${n}_${a}`});const jv={type:"text"},Xv={type:"video"};function Dh(){return document.createElement("canvas")}function zv(r,e){return Object.keys(r).reduce((t,i)=>(e.includes(i)||(t[i]=r[i]),t),{})}function qt(r){let e=0;for(const t of r)Array.isArray(t)?e+=qt(t):e+=t;return e}function so(r){return r.map(({type:e,duration:t},i)=>{var n,s,o,a;if(e==="transition"){const l=((n=r[i-2])==null?void 0:n.type)==="transition"?r[i-2]:null,A=((s=r[i-1])==null?void 0:s.duration)??1/0,u=((o=r[i+1])==null?void 0:o.duration)??1/0,c=((a=r[i+2])==null?void 0:a.type)==="transition"?r[i+2]:null;return Math.min(l?A/2:A,t,c?u/2:u)*-1}return t})}function Lh(r){var e;return{...r,children:((e=r.children)==null?void 0:e.map(t=>{if(!t.renderer)return Lh(t)}).filter(Boolean))??[]}}function kh(r){const e={box:0,shape:0,image:0,video:0,text:0,audio:0,gradient:0,caption:0};r.renderer&&(e[r.renderer.type]+=1);for(const t of r.children??[]){const{box:i,shape:n,image:s,video:o,text:a,audio:l,gradient:A,caption:u}=kh(t);e.box+=i,e.shape+=n,e.image+=s,e.video+=o,e.text+=a,e.audio+=l,e.gradient+=A,e.caption+=u}return e}function Zv(r){return r.video>0?Xv.type:r.image>0?qv.type:r.audio>0?Hv.type:r.caption>0?Wv.type:jv.type}function Mh({node:r,duration:e,parentAnimations:t}){const i=[],n={...t,...r.element.animations};if(r.renderer){const s=Lh({...r.element,layout:{...r.element.layout?zv(r.element.layout,["maxWidth","maxHeight"]):{},width:"100%",height:"100%",margin:0}}),o=kh(s);i.push({type:Zv(o),id:yv(),x:r.x,y:r.y,width:r.width,height:r.height,duration:e,root:{element:s}})}for(const s of r.childNodes)i.push(...Mh({node:s,duration:e,parentAnimations:n}));return i}Om.filters.define("parse",r=>typeof r>"u"?null:typeof r=="string"?`"${Gv(r)}"`:Uv(r)||Array.isArray(r)?JSON.stringify(r):r);const ey="3";async function ty({scene:r,start:e=0}){const{id:t,root:i,duration:n}=r,s=await _h({id:t,root:i});return{type:r.type,start:e,duration:n,layout:s,id:r.id,config:r}}async function iy({track:r}){const e=so(r),t=await Promise.all(r.reduce((s,o,a)=>{if(o.type!=="audio")return s;const l=qt(e.slice(0,a));return s.push(ty({scene:o,start:l})),s},[])),i=r.reduce((s,o,a)=>{if(o.type!=="gap")return s;const l=qt(e.slice(0,a));return s.push({type:o.type,id:o.id,start:l,config:o,duration:o.duration}),s},[]),n=r.map(({id:s})=>t.find(({id:o})=>o===s)??i.find(({id:o})=>o===s)).filter(Boolean);return{type:"audio",scenes:t,gapScenes:i,mergedScenes:n,config:r,duration:Math.max(...n.map(({start:s,duration:o})=>s+o))}}async function Fh({node:r,canvases:e,sceneTime:t,parentOpacity:i=1,parentTransform:n,debug:s=!1}){var o,a;const l=e.sceneCanvas.getContext("2d");if(l){l.save(),l.setTransform(n);const A=mv({layout:r.element.layout,sceneTime:t,animations:r.element.animations}),{opacity:u,translation:c,scale:h,clip:d,dimensions:f,rotation:g}=A,p=r.width*f.widthRatio,v=r.height*f.heightRatio;if(l.globalAlpha=u*i,(c.x||c.y)&&l.translate(c.x,c.y),(h!==1||g!==0)&&(l.translate(r.x+p/2,r.y+v/2),l.scale(h,h),l.rotate(g*Math.PI/180),l.translate(-(r.x+p/2),-(r.y+v/2))),d){l.beginPath();const B={x:r.x+d.x*p,y:r.y+d.y*v,width:d.width*p,height:d.height*v};l.rect(B.x,B.y,B.width,B.height),l.clip()}if(s){const B=l.globalAlpha;l.globalAlpha=1,l.strokeStyle="red",l.strokeRect(r.x,r.y,p,v),l.globalAlpha=B}await((a=(o=r.renderer)==null?void 0:o.render)==null?void 0:a.call(o,{canvases:e,sceneTime:t,dx:r.x,dy:r.y,dw:p,dh:v,radius:r.radius,options:r.options,dependencies:r.dependencies}));for await(const B of r.childNodes)await Fh({debug:s,node:B,canvases:e,sceneTime:t,parentOpacity:l.globalAlpha,parentTransform:l.getTransform()});l.restore()}}async function ry({layout:r,canvases:e,sceneTime:t,debug:i=!1}){const{node:n}=r;await Fh({debug:i,node:n,canvases:e,sceneTime:t})}async function oo({debug:r=!1,scene:e,start:t=0,resolvers:i,rootWidth:n,rootHeight:s,canvasFactory:o=Dh}){var a,l;const{id:A,x:u,y:c,width:h,height:d,root:f,duration:g}=e,p=o(),v=o(),B=o(),C=o(),y=o(),x=await _h({id:A,root:{...f,layout:{...f.layout,width:n,height:s},element:{...f.element,layout:{...f.element.layout,...typeof u=="number"&&typeof c=="number"?{position:"absolute",inset:{top:c,left:u}}:{},width:h??((a=f.element.layout)==null?void 0:a.width),height:d??((l=f.element.layout)==null?void 0:l.height)}}},resolvers:i,measureCanvas:y}),w=async D=>{const F=Math.max(0,D-t);p.width=p.height=0,p.width=n,p.height=s,await ry({debug:r,layout:x,sceneTime:F,canvases:{sceneCanvas:p,cropCanvas:v,letterboxCanvas:B,posterCanvas:C}})};return{id:A,type:e.type,start:t,duration:g,layout:x,sceneCanvas:p,draw:w,config:e,childScenes:Mh({node:x.node,duration:g})}}async function ny({debug:r=!1,track:e,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}){const o=so(e),a=await Promise.all(e.reduce((c,h,d)=>{const f=qt(o.slice(0,d));return h.type==="caption"&&c.push(oo({debug:r,scene:h,start:f,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s})),c},[])),l=e.reduce((c,h,d)=>{if(h.type!=="gap")return c;const f=qt(o.slice(0,d));return c.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),c},[]),A=e.reduce((c,h,d)=>{if(h.type!=="transition")return c;const f=h.duration,g=qt(o.slice(0,d))-f;return c.push({type:h.type,id:h.id,name:h.name,start:g,duration:f,config:h,transitionCanvas:s(),to:a.find(({id:p})=>{var v;return p===((v=e[d+1])==null?void 0:v.id)}),from:a.find(({id:p})=>{var v;return p===((v=e[d-1])==null?void 0:v.id)})}),c},[]),u=e.map(({id:c})=>a.find(({id:h})=>h===c)??l.find(({id:h})=>h===c)??A.find(({id:h})=>h===c)).filter(Boolean);return{type:"caption",scenes:a,gapScenes:l,transitions:A,mergedScenes:u,duration:Math.max(...u.map(({start:c,duration:h})=>c+h)),trackCanvas:s()}}async function sy({debug:r=!1,track:e,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}){const o=so(e),a=await Promise.all(e.reduce((c,h,d)=>{const f=qt(o.slice(0,d));return h.type==="video"&&c.push(oo({debug:r,scene:h,start:f,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s})),h.type==="image"&&c.push(oo({debug:r,scene:h,start:f,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s})),c},[])),l=e.reduce((c,h,d)=>{if(h.type!=="gap")return c;const f=qt(o.slice(0,d));return c.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),c},[]),A=e.reduce((c,h,d)=>{if(h.type!=="transition")return c;const f=h.duration,g=qt(o.slice(0,d))-f;return c.push({type:h.type,id:h.id,name:h.name,start:g,duration:f,config:h,transitionCanvas:s(),to:a.find(({id:p})=>{var v;return p===((v=e[d+1])==null?void 0:v.id)}),from:a.find(({id:p})=>{var v;return p===((v=e[d-1])==null?void 0:v.id)})}),c},[]),u=e.map(({id:c})=>a.find(({id:h})=>h===c)??l.find(({id:h})=>h===c)??A.find(({id:h})=>h===c)).filter(Boolean);return{type:"picture",scenes:a,gapScenes:l,transitions:A,mergedScenes:u,duration:Math.max(0,...u.map(({start:c,duration:h})=>c+h)),trackCanvas:s()}}async function oy({debug:r=!1,track:e,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}){const o=so(e),a=await Promise.all(e.reduce((c,h,d)=>{const f=qt(o.slice(0,d));return h.type==="text"&&c.push(oo({debug:r,scene:h,start:f,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s})),c},[])),l=e.reduce((c,h,d)=>{if(h.type!=="gap")return c;const f=qt(o.slice(0,d));return c.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),c},[]),A=e.reduce((c,h,d)=>{if(h.type!=="transition")return c;const f=h.duration,g=qt(o.slice(0,d))-f;return c.push({type:h.type,id:h.id,name:h.name,start:g,duration:f,config:h,transitionCanvas:s(),to:a.find(({id:p})=>{var v;return p===((v=e[d+1])==null?void 0:v.id)}),from:a.find(({id:p})=>{var v;return p===((v=e[d-1])==null?void 0:v.id)})}),c},[]),u=e.map(({id:c})=>a.find(({id:h})=>h===c)??l.find(({id:h})=>h===c)??A.find(({id:h})=>h===c)).filter(Boolean);return{type:"text",scenes:a,gapScenes:l,transitions:A,mergedScenes:u,duration:Math.max(...u.map(({start:c,duration:h})=>c+h)),trackCanvas:s()}}function ay(r){return r.some(({type:e})=>e==="text")}function ly(r){return r.some(({type:e})=>e==="caption")}function Ay(r){return r.some(({type:e})=>e==="audio")}function cy(r){return r.some(({type:e})=>e==="video"||e==="image")}function uy(r){return r.type==="audio"}const hy=(((vh=Ih)==null?void 0:vh.default)??Ih).reduce((r,e)=>(r[e.name]=e,r),{});function dy(r,e){return r.has(e)||r.set(e,{buffer:null,transitions:{},fromTexture:null,toTexture:null}),r.get(e)}function fy({name:r,to:e,from:t,progress:i,width:n,height:s,glContext:o,contextResources:a,returnPixels:l=!0}){var A,u,c;const h=dy(a,o);if(o.disable(o.DEPTH_TEST),h.buffer?o.bindBuffer(o.ARRAY_BUFFER,h.buffer):(h.buffer=o.createBuffer(),o.bindBuffer(o.ARRAY_BUFFER,h.buffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array([-1,-1,-1,4,4,-1]),o.STATIC_DRAW)),o.viewport(0,0,n,s),h.fromTexture?h.fromTexture.setPixels(t):(h.fromTexture=(((A=zs)==null?void 0:A.default)??zs)(o,t),h.fromTexture.minFilter=o.LINEAR,h.fromTexture.magFilter=o.LINEAR),h.toTexture?h.toTexture.setPixels(e):(h.toTexture=(((u=zs)==null?void 0:u.default)??zs)(o,e),h.toTexture.minFilter=o.LINEAR,h.toTexture.magFilter=o.LINEAR),h.transitions[r]||(h.transitions[r]=(((c=Eh)==null?void 0:c.default)??Eh)(o,hy[r])),h.transitions[r].draw(i,h.fromTexture,h.toTexture,n,s),!l)return o.flush(),new Uint8Array(0);const f=new Uint8Array(n*s*4);return o.readPixels(0,0,n,s,o.RGBA,o.UNSIGNED_BYTE,f),o.flush(),f}function gy(r){for(const[e,t]of r.entries())t.buffer&&e.deleteBuffer(t.buffer),t.fromTexture&&t.fromTexture.dispose(),t.toTexture&&t.toTexture.dispose(),Object.values(t.transitions).forEach(i=>{i.dispose()}),r.delete(e)}function py({name:r,to:e,from:t,progress:i,canvas:n,contextResources:s}){const o=n.getContext("webgl",{alpha:!0,depth:!1,antialias:!1,preserveDrawingBuffer:!1});o&&(o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,!0),fy({name:r,to:e,from:t,progress:i,width:n.width,height:n.height,glContext:o,contextResources:s,returnPixels:!1}))}async function Ph({debug:r=!1,config:e,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s=Dh,drawTransition:o=py}){const a=new Map,l=await Promise.all(e.tracks.map(async c=>{if(cy(c))return{...await sy({debug:r,track:c,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}),config:c};if(ay(c))return{...await oy({debug:r,track:c,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}),config:c};if(ly(c))return{...await ny({debug:r,track:c,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}),config:c};if(Ay(c))return{...await iy({track:c}),config:c};throw new Error("Unknown track type")}));return{draw:async({canvas:c,currentTime:h})=>{const d=c.getContext("2d");if(d){d.globalAlpha=1,d.globalCompositeOperation="source-over",d.clearRect(0,0,c.width,c.height),d.save(),d.fillStyle="black",d.fillRect(0,0,c.width,c.height),d.restore();for await(const f of l){if(uy(f))continue;const{scenes:g,transitions:p,trackCanvas:v}=f;v.width=v.height=0,v.width=c.width,v.height=c.height;const B=v.getContext("2d"),C=g.filter(({start:x,duration:w})=>h>=x&&h<x+w);if(!B||C.length<=0)continue;const y=p.find(({start:x,duration:w})=>h>=x&&h<x+w);for await(const{sceneCanvas:x,draw:w}of C)await(w==null?void 0:w(h)),(!y||y&&(!y.to||!y.from))&&B.drawImage(x,0,0,x.width,x.height);if(y&&y.to&&y.from&&y.duration>0){const{name:x,to:w,from:D,duration:F,transitionCanvas:O}=y;O.width=O.height=0,O.width=v.width,O.height=v.height;const M=Math.min(1,Math.max(0,(h-w.start)/F));await o({name:x,progress:M,contextResources:a,to:w.sceneCanvas,from:D.sceneCanvas,canvas:O}),B.globalCompositeOperation="lighter",B.drawImage(O,0,0,O.width,O.height)}d.drawImage(v,0,0,v.width,v.height)}}},cleanup:()=>{gy(a)},tracks:l,aspectRatio:e.aspectRatio,duration:Math.max(...l.map(({duration:c})=>c))}}const my={version:"5.0.4"};function Ey(r){const{publicApiUrl:e}=_s(r),t=Ki();return navigator.sendBeacon(`${e}/api/visitor`,JSON.stringify({visitorId:t})),t}function Iy(r){var s,o,a,l,A,u,c,h,d,f,g,p;if(typeof window>"u")return{client:null,tab:null,request:Ki()};let e=(o=(s=window.localStorage)==null?void 0:s.getItem)==null?void 0:o.call(s,"vouch-uid-visitor"),t=(l=(a=window.localStorage)==null?void 0:a.getItem)==null?void 0:l.call(a,"vouch-uid-client"),i=(u=(A=window.sessionStorage)==null?void 0:A.getItem)==null?void 0:u.call(A,"vouch-uid-tab");const n=Ki();return e||(e=Ey(r),(h=(c=window.localStorage)==null?void 0:c.setItem)==null||h.call(c,"vouch-uid-visitor",e)),t||(t=Ki(),(f=(d=window.localStorage)==null?void 0:d.setItem)==null||f.call(d,"vouch-uid-client",t)),i||(i=Ki(),(p=(g=window.sessionStorage)==null?void 0:g.setItem)==null||p.call(g,"vouch-uid-tab",i)),{client:t,tab:i,request:n,visitor:e}}function vy(r,e){return r&&"vouchId"in r?r.vouchId:(e==null?void 0:e.id)??null}function yy(r="embedded_player"){var n,s;const[e,t]=((s=(n=Intl.DateTimeFormat().resolvedOptions().timeZone)==null?void 0:n.split)==null?void 0:s.call(n,"/"))??[],i={};return[...new URLSearchParams(location.search).entries()].forEach(([o,a])=>{if(/utm/.test(o)){const l=o.toLowerCase().replace(/[-_][a-z0-9]/g,A=>A.slice(-1).toUpperCase());i[l]=a}}),{source:r,time:new Date,region:t,country:e,screenHeight:window.screen.height,screenWidth:window.screen.width,referrer:document.referrer,currentUrl:location.href,embedType:"media-player-embed",embedVersion:my.version,templateVersion:ey,...i}}const Nh=1;class Cy{constructor(e){this._batchedEvents=[],this._hasPlayed=!1,this._hasLoaded={},this._answersViewed={},this._streamStartTime={},this._streamLatestTime={},this._currentlyPlayingVideo=null,this._createTrackingEvent=(t,i)=>{const n=vy(i,this.host.vouch);!n||this.host.disableTracking||this._batchedEvents.push({event:t,payload:{...i,vouchId:n,time:new Date().toISOString()}})},this._sendTrackingEvent=()=>{if(this._batchedEvents.length<=0)return;const{publicApiUrl:t}=_s(this.host.env),{client:i,tab:n,request:s,visitor:o}=Iy(this.host.env);navigator.sendBeacon(`${t}/api/batchevents`,JSON.stringify({payload:{events:this._batchedEvents},context:{"x-uid-client":i,"x-uid-tab":n,"x-uid-request":s,"x-uid-visitor":o,"x-reporting-metadata":yy(this.host.trackingSource)}})),this._batchedEvents=[]},this._streamEnded=()=>{if(this._currentlyPlayingVideo){const{id:t,key:i}=this._currentlyPlayingVideo;this._streamLatestTime[i]>this._streamStartTime[i]+Nh&&this._createTrackingEvent("VIDEO_STREAMED",{answerId:t,streamStart:this._streamStartTime[i],streamEnd:this._streamLatestTime[i]}),delete this._streamStartTime[i],delete this._streamLatestTime[i]}},this._handleVouchLoaded=({detail:t})=>{t&&(this._hasLoaded[t]||(this._createTrackingEvent("VOUCH_LOADED",{vouchId:t}),this._hasLoaded[t]=!0))},this._handlePlay=()=>{this._hasPlayed||(this._createTrackingEvent("VIDEO_PLAYED",{streamStart:this.host.currentTime}),this._hasPlayed=!0)},this._handleVideoPlay=({detail:{id:t,key:i}})=>{this._answersViewed[i]||(this._createTrackingEvent("VOUCH_RESPONSE_VIEWED",{answerId:t}),this._answersViewed[i]=!0)},this._handleVideoTimeUpdate=({detail:{id:t,key:i,node:n}})=>{this.host.paused||(this._currentlyPlayingVideo={id:t,key:i,node:n},this._streamLatestTime[i]=n.currentTime,this._streamStartTime[i]||(this._streamStartTime[i]=n.currentTime,this._streamLatestTime[i]=n.currentTime))},this._handleVideoPause=({detail:{id:t,key:i}})=>{this._streamLatestTime[i]>this._streamStartTime[i]+Nh&&this._createTrackingEvent("VIDEO_STREAMED",{answerId:t,streamStart:this._streamStartTime[i],streamEnd:this._streamLatestTime[i]}),delete this._streamStartTime[i],delete this._streamLatestTime[i]},this._pageUnloading=()=>{this._streamEnded(),this._sendTrackingEvent()},this._handleVisibilityChange=()=>{document.visibilityState==="hidden"&&this._pageUnloading()},this._handlePageHide=()=>{this._pageUnloading()},this.host=e,e.addController(this)}hostConnected(){requestAnimationFrame(()=>{var e,t,i,n;"onvisibilitychange"in document?document.addEventListener("visibilitychange",this._handleVisibilityChange):window.addEventListener("pagehide",this._handlePageHide),this.host.addEventListener("vouch:loaded",this._handleVouchLoaded),(e=this.host.mediaPlayer)==null||e.addEventListener("play",this._handlePlay),(t=this.host.mediaPlayer)==null||t.addEventListener("video:play",this._handleVideoPlay),(i=this.host.mediaPlayer)==null||i.addEventListener("video:pause",this._handleVideoPause),(n=this.host.mediaPlayer)==null||n.addEventListener("video:timeupdate",this._handleVideoTimeUpdate)})}hostDisconnected(){var e,t,i,n;this._pageUnloading(),"onvisibilitychange"in document?document.removeEventListener("visibilitychange",this._handleVisibilityChange):window.removeEventListener("pagehide",this._handlePageHide),this.host.removeEventListener("vouch:loaded",this._handleVouchLoaded),(e=this.host.mediaPlayer)==null||e.removeEventListener("play",this._handlePlay),(t=this.host.mediaPlayer)==null||t.removeEventListener("video:play",this._handleVideoPlay),(i=this.host.mediaPlayer)==null||i.removeEventListener("video:pause",this._handleVideoPause),(n=this.host.mediaPlayer)==null||n.removeEventListener("video:timeupdate",this._handleVideoTimeUpdate)}}var pl={exports:{}};(function(r,e){var t=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof qi<"u"&&qi,i=function(){function s(){this.fetch=!1,this.DOMException=t.DOMException}return s.prototype=t,new s}();(function(s){(function(o){var a=typeof s<"u"&&s||typeof self<"u"&&self||typeof qi<"u"&&qi||{},l={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function A(L){return L&&DataView.prototype.isPrototypeOf(L)}if(l.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(L){return L&&u.indexOf(Object.prototype.toString.call(L))>-1};function h(L){if(typeof L!="string"&&(L=String(L)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(L)||L==="")throw new TypeError('Invalid character in header field name: "'+L+'"');return L.toLowerCase()}function d(L){return typeof L!="string"&&(L=String(L)),L}function f(L){var U={next:function(){var q=L.shift();return{done:q===void 0,value:q}}};return l.iterable&&(U[Symbol.iterator]=function(){return U}),U}function g(L){this.map={},L instanceof g?L.forEach(function(U,q){this.append(q,U)},this):Array.isArray(L)?L.forEach(function(U){if(U.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+U.length);this.append(U[0],U[1])},this):L&&Object.getOwnPropertyNames(L).forEach(function(U){this.append(U,L[U])},this)}g.prototype.append=function(L,U){L=h(L),U=d(U);var q=this.map[L];this.map[L]=q?q+", "+U:U},g.prototype.delete=function(L){delete this.map[h(L)]},g.prototype.get=function(L){return L=h(L),this.has(L)?this.map[L]:null},g.prototype.has=function(L){return this.map.hasOwnProperty(h(L))},g.prototype.set=function(L,U){this.map[h(L)]=d(U)},g.prototype.forEach=function(L,U){for(var q in this.map)this.map.hasOwnProperty(q)&&L.call(U,this.map[q],q,this)},g.prototype.keys=function(){var L=[];return this.forEach(function(U,q){L.push(q)}),f(L)},g.prototype.values=function(){var L=[];return this.forEach(function(U){L.push(U)}),f(L)},g.prototype.entries=function(){var L=[];return this.forEach(function(U,q){L.push([q,U])}),f(L)},l.iterable&&(g.prototype[Symbol.iterator]=g.prototype.entries);function p(L){if(!L._noBody){if(L.bodyUsed)return Promise.reject(new TypeError("Already read"));L.bodyUsed=!0}}function v(L){return new Promise(function(U,q){L.onload=function(){U(L.result)},L.onerror=function(){q(L.error)}})}function B(L){var U=new FileReader,q=v(U);return U.readAsArrayBuffer(L),q}function C(L){var U=new FileReader,q=v(U),R=/charset=([A-Za-z0-9_-]+)/.exec(L.type),_=R?R[1]:"utf-8";return U.readAsText(L,_),q}function y(L){for(var U=new Uint8Array(L),q=new Array(U.length),R=0;R<U.length;R++)q[R]=String.fromCharCode(U[R]);return q.join("")}function x(L){if(L.slice)return L.slice(0);var U=new Uint8Array(L.byteLength);return U.set(new Uint8Array(L)),U.buffer}function w(){return this.bodyUsed=!1,this._initBody=function(L){this.bodyUsed=this.bodyUsed,this._bodyInit=L,L?typeof L=="string"?this._bodyText=L:l.blob&&Blob.prototype.isPrototypeOf(L)?this._bodyBlob=L:l.formData&&FormData.prototype.isPrototypeOf(L)?this._bodyFormData=L:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(L)?this._bodyText=L.toString():l.arrayBuffer&&l.blob&&A(L)?(this._bodyArrayBuffer=x(L.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(L)||c(L))?this._bodyArrayBuffer=x(L):this._bodyText=L=Object.prototype.toString.call(L):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof L=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):l.searchParams&&URLSearchParams.prototype.isPrototypeOf(L)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var L=p(this);if(L)return L;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var L=p(this);return L||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(l.blob)return this.blob().then(B);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var L=p(this);if(L)return L;if(this._bodyBlob)return C(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(y(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},l.formData&&(this.formData=function(){return this.text().then(M)}),this.json=function(){return this.text().then(JSON.parse)},this}var D=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function F(L){var U=L.toUpperCase();return D.indexOf(U)>-1?U:L}function O(L,U){if(!(this instanceof O))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');U=U||{};var q=U.body;if(L instanceof O){if(L.bodyUsed)throw new TypeError("Already read");this.url=L.url,this.credentials=L.credentials,U.headers||(this.headers=new g(L.headers)),this.method=L.method,this.mode=L.mode,this.signal=L.signal,!q&&L._bodyInit!=null&&(q=L._bodyInit,L.bodyUsed=!0)}else this.url=String(L);if(this.credentials=U.credentials||this.credentials||"same-origin",(U.headers||!this.headers)&&(this.headers=new g(U.headers)),this.method=F(U.method||this.method||"GET"),this.mode=U.mode||this.mode||null,this.signal=U.signal||this.signal||function(){if("AbortController"in a){var k=new AbortController;return k.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&q)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(q),(this.method==="GET"||this.method==="HEAD")&&(U.cache==="no-store"||U.cache==="no-cache")){var R=/([?&])_=[^&]*/;if(R.test(this.url))this.url=this.url.replace(R,"$1_="+new Date().getTime());else{var _=/\?/;this.url+=(_.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}O.prototype.clone=function(){return new O(this,{body:this._bodyInit})};function M(L){var U=new FormData;return L.trim().split("&").forEach(function(q){if(q){var R=q.split("="),_=R.shift().replace(/\+/g," "),k=R.join("=").replace(/\+/g," ");U.append(decodeURIComponent(_),decodeURIComponent(k))}}),U}function j(L){var U=new g,q=L.replace(/\r?\n[\t ]+/g," ");return q.split("\r").map(function(R){return R.indexOf(`
2476
+ `).flatMap(a=>{const l=a.split(" ").filter(Boolean);return l.length?l.slice(1).reduce((A,u,c)=>{const d=`${A[A.length-1].text} ${u}`.trim(),f=e.measureText(d);if(f.width>n)A=[...A,...Rh({context:e,word:u,maxW:n})];else{const g=t[c%t.length];e.font=r.replace(Nn,g.toString()),A[A.length-1]={text:d,metrics:f}}return A},Rh({context:e,word:l[0],maxW:n})):{text:"",metrics:e.measureText("")}})}finally{e.restore()}},{cacheKey:([{font:r,fontSizes:e,text:t,maxW:i,letterSpacing:n}])=>`${r}_${JSON.stringify(e)}_${t}_${i}_${n}`});ws(({font:r,text:e,scale:t,context:i,maxW:n,maxH:s,minSize:o,maxSize:a,letterSpacing:l=0})=>{var A,u;let c=0;if(a){c=(o??0)*t;let d=0;for(;a*t>c+1;){c+=1;const f=Jv({font:r,context:i,fontSizes:[c],text:e,maxW:n,letterSpacing:l});if(d=f.reduce((g,p)=>(p.metrics.width>g&&(g=p.metrics.width),g),0),d>n||f.length*c>s){c-=1;break}}}else c=parseFloat(((u=(A=r.match(Nn))==null?void 0:A.groups)==null?void 0:u.value)??"0")*t;return c},{cacheKey:([{font:r,text:e,scale:t,maxW:i,maxH:n,minSize:s,maxSize:o,letterSpacing:a}])=>`${r}_${e}_${s}_${o}_${t}_${i}_${n}_${a}`});const jv={type:"text"},Xv={type:"video"};function Dh(){return document.createElement("canvas")}function zv(r,e){return Object.keys(r).reduce((t,i)=>(e.includes(i)||(t[i]=r[i]),t),{})}function qt(r){let e=0;for(const t of r)Array.isArray(t)?e+=qt(t):e+=t;return e}function so(r){return r.map(({type:e,duration:t},i)=>{var n,s,o,a;if(e==="transition"){const l=((n=r[i-2])==null?void 0:n.type)==="transition"?r[i-2]:null,A=((s=r[i-1])==null?void 0:s.duration)??1/0,u=((o=r[i+1])==null?void 0:o.duration)??1/0,c=((a=r[i+2])==null?void 0:a.type)==="transition"?r[i+2]:null;return Math.min(l?A/2:A,t,c?u/2:u)*-1}return t})}function Lh(r){var e;return{...r,children:((e=r.children)==null?void 0:e.map(t=>{if(!t.renderer)return Lh(t)}).filter(Boolean))??[]}}function kh(r){const e={box:0,shape:0,image:0,video:0,text:0,audio:0,gradient:0,caption:0};r.renderer&&(e[r.renderer.type]+=1);for(const t of r.children??[]){const{box:i,shape:n,image:s,video:o,text:a,audio:l,gradient:A,caption:u}=kh(t);e.box+=i,e.shape+=n,e.image+=s,e.video+=o,e.text+=a,e.audio+=l,e.gradient+=A,e.caption+=u}return e}function Zv(r){return r.video>0?Xv.type:r.image>0?qv.type:r.audio>0?Hv.type:r.caption>0?Wv.type:jv.type}function Mh({node:r,duration:e,parentAnimations:t}){const i=[],n={...t,...r.element.animations};if(r.renderer){const s=Lh({...r.element,layout:{...r.element.layout?zv(r.element.layout,["maxWidth","maxHeight"]):{},width:"100%",height:"100%",margin:0}}),o=kh(s);i.push({type:Zv(o),id:yv(),x:r.x,y:r.y,width:r.width,height:r.height,duration:e,root:{element:s}})}for(const s of r.childNodes)i.push(...Mh({node:s,duration:e,parentAnimations:n}));return i}Om.filters.define("parse",r=>typeof r>"u"?null:typeof r=="string"?`"${Gv(r)}"`:Uv(r)||Array.isArray(r)?JSON.stringify(r):r);const ey="3";async function ty({scene:r,start:e=0}){const{id:t,root:i,duration:n}=r,s=await _h({id:t,root:i});return{type:r.type,start:e,duration:n,layout:s,id:r.id,config:r}}async function iy({track:r}){const e=so(r),t=await Promise.all(r.reduce((s,o,a)=>{if(o.type!=="audio")return s;const l=qt(e.slice(0,a));return s.push(ty({scene:o,start:l})),s},[])),i=r.reduce((s,o,a)=>{if(o.type!=="gap")return s;const l=qt(e.slice(0,a));return s.push({type:o.type,id:o.id,start:l,config:o,duration:o.duration}),s},[]),n=r.map(({id:s})=>t.find(({id:o})=>o===s)??i.find(({id:o})=>o===s)).filter(Boolean);return{type:"audio",scenes:t,gapScenes:i,mergedScenes:n,config:r,duration:Math.max(...n.map(({start:s,duration:o})=>s+o))}}async function Fh({node:r,canvases:e,sceneTime:t,parentOpacity:i=1,parentTransform:n,debug:s=!1}){var o,a;const l=e.sceneCanvas.getContext("2d");if(l){l.save(),l.setTransform(n);const A=mv({layout:r.element.layout,sceneTime:t,animations:r.element.animations}),{opacity:u,translation:c,scale:h,clip:d,dimensions:f,rotation:g}=A,p=r.width*f.widthRatio,v=r.height*f.heightRatio;if(l.globalAlpha=u*i,(c.x||c.y)&&l.translate(c.x,c.y),(h!==1||g!==0)&&(l.translate(r.x+p/2,r.y+v/2),l.scale(h,h),l.rotate(g*Math.PI/180),l.translate(-(r.x+p/2),-(r.y+v/2))),d){l.beginPath();const B={x:r.x+d.x*p,y:r.y+d.y*v,width:d.width*p,height:d.height*v};l.rect(B.x,B.y,B.width,B.height),l.clip()}if(s){const B=l.globalAlpha;l.globalAlpha=1,l.strokeStyle="red",l.strokeRect(r.x,r.y,p,v),l.globalAlpha=B}await((a=(o=r.renderer)==null?void 0:o.render)==null?void 0:a.call(o,{canvases:e,sceneTime:t,dx:r.x,dy:r.y,dw:p,dh:v,radius:r.radius,options:r.options,dependencies:r.dependencies}));for await(const B of r.childNodes)await Fh({debug:s,node:B,canvases:e,sceneTime:t,parentOpacity:l.globalAlpha,parentTransform:l.getTransform()});l.restore()}}async function ry({layout:r,canvases:e,sceneTime:t,debug:i=!1}){const{node:n}=r;await Fh({debug:i,node:n,canvases:e,sceneTime:t})}async function oo({debug:r=!1,scene:e,start:t=0,resolvers:i,rootWidth:n,rootHeight:s,canvasFactory:o=Dh}){var a,l;const{id:A,x:u,y:c,width:h,height:d,root:f,duration:g}=e,p=o(),v=o(),B=o(),C=o(),y=o(),x=await _h({id:A,root:{...f,layout:{...f.layout,width:n,height:s},element:{...f.element,layout:{...f.element.layout,...typeof u=="number"&&typeof c=="number"?{position:"absolute",inset:{top:c,left:u}}:{},width:h??((a=f.element.layout)==null?void 0:a.width),height:d??((l=f.element.layout)==null?void 0:l.height)}}},resolvers:i,measureCanvas:y}),w=async D=>{const F=Math.max(0,D-t);p.width=p.height=0,p.width=n,p.height=s,await ry({debug:r,layout:x,sceneTime:F,canvases:{sceneCanvas:p,cropCanvas:v,letterboxCanvas:B,posterCanvas:C}})};return{id:A,type:e.type,start:t,duration:g,layout:x,sceneCanvas:p,draw:w,config:e,childScenes:Mh({node:x.node,duration:g})}}async function ny({debug:r=!1,track:e,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}){const o=so(e),a=await Promise.all(e.reduce((c,h,d)=>{const f=qt(o.slice(0,d));return h.type==="caption"&&c.push(oo({debug:r,scene:h,start:f,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s})),c},[])),l=e.reduce((c,h,d)=>{if(h.type!=="gap")return c;const f=qt(o.slice(0,d));return c.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),c},[]),A=e.reduce((c,h,d)=>{if(h.type!=="transition")return c;const f=h.duration,g=qt(o.slice(0,d))-f;return c.push({type:h.type,id:h.id,name:h.name,start:g,duration:f,config:h,transitionCanvas:s(),to:a.find(({id:p})=>{var v;return p===((v=e[d+1])==null?void 0:v.id)}),from:a.find(({id:p})=>{var v;return p===((v=e[d-1])==null?void 0:v.id)})}),c},[]),u=e.map(({id:c})=>a.find(({id:h})=>h===c)??l.find(({id:h})=>h===c)??A.find(({id:h})=>h===c)).filter(Boolean);return{type:"caption",scenes:a,gapScenes:l,transitions:A,mergedScenes:u,duration:Math.max(...u.map(({start:c,duration:h})=>c+h)),trackCanvas:s()}}async function sy({debug:r=!1,track:e,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}){const o=so(e),a=await Promise.all(e.reduce((c,h,d)=>{const f=qt(o.slice(0,d));return h.type==="video"&&c.push(oo({debug:r,scene:h,start:f,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s})),h.type==="image"&&c.push(oo({debug:r,scene:h,start:f,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s})),c},[])),l=e.reduce((c,h,d)=>{if(h.type!=="gap")return c;const f=qt(o.slice(0,d));return c.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),c},[]),A=e.reduce((c,h,d)=>{if(h.type!=="transition")return c;const f=h.duration,g=qt(o.slice(0,d))-f;return c.push({type:h.type,id:h.id,name:h.name,start:g,duration:f,config:h,transitionCanvas:s(),to:a.find(({id:p})=>{var v;return p===((v=e[d+1])==null?void 0:v.id)}),from:a.find(({id:p})=>{var v;return p===((v=e[d-1])==null?void 0:v.id)})}),c},[]),u=e.map(({id:c})=>a.find(({id:h})=>h===c)??l.find(({id:h})=>h===c)??A.find(({id:h})=>h===c)).filter(Boolean);return{type:"picture",scenes:a,gapScenes:l,transitions:A,mergedScenes:u,duration:Math.max(0,...u.map(({start:c,duration:h})=>c+h)),trackCanvas:s()}}async function oy({debug:r=!1,track:e,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}){const o=so(e),a=await Promise.all(e.reduce((c,h,d)=>{const f=qt(o.slice(0,d));return h.type==="text"&&c.push(oo({debug:r,scene:h,start:f,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s})),c},[])),l=e.reduce((c,h,d)=>{if(h.type!=="gap")return c;const f=qt(o.slice(0,d));return c.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),c},[]),A=e.reduce((c,h,d)=>{if(h.type!=="transition")return c;const f=h.duration,g=qt(o.slice(0,d))-f;return c.push({type:h.type,id:h.id,name:h.name,start:g,duration:f,config:h,transitionCanvas:s(),to:a.find(({id:p})=>{var v;return p===((v=e[d+1])==null?void 0:v.id)}),from:a.find(({id:p})=>{var v;return p===((v=e[d-1])==null?void 0:v.id)})}),c},[]),u=e.map(({id:c})=>a.find(({id:h})=>h===c)??l.find(({id:h})=>h===c)??A.find(({id:h})=>h===c)).filter(Boolean);return{type:"text",scenes:a,gapScenes:l,transitions:A,mergedScenes:u,duration:Math.max(...u.map(({start:c,duration:h})=>c+h)),trackCanvas:s()}}function ay(r){return r.some(({type:e})=>e==="text")}function ly(r){return r.some(({type:e})=>e==="caption")}function Ay(r){return r.some(({type:e})=>e==="audio")}function cy(r){return r.some(({type:e})=>e==="video"||e==="image")}function uy(r){return r.type==="audio"}const hy=(((vh=Ih)==null?void 0:vh.default)??Ih).reduce((r,e)=>(r[e.name]=e,r),{});function dy(r,e){return r.has(e)||r.set(e,{buffer:null,transitions:{},fromTexture:null,toTexture:null}),r.get(e)}function fy({name:r,to:e,from:t,progress:i,width:n,height:s,glContext:o,contextResources:a,returnPixels:l=!0}){var A,u,c;const h=dy(a,o);if(o.disable(o.DEPTH_TEST),h.buffer?o.bindBuffer(o.ARRAY_BUFFER,h.buffer):(h.buffer=o.createBuffer(),o.bindBuffer(o.ARRAY_BUFFER,h.buffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array([-1,-1,-1,4,4,-1]),o.STATIC_DRAW)),o.viewport(0,0,n,s),h.fromTexture?h.fromTexture.setPixels(t):(h.fromTexture=(((A=zs)==null?void 0:A.default)??zs)(o,t),h.fromTexture.minFilter=o.LINEAR,h.fromTexture.magFilter=o.LINEAR),h.toTexture?h.toTexture.setPixels(e):(h.toTexture=(((u=zs)==null?void 0:u.default)??zs)(o,e),h.toTexture.minFilter=o.LINEAR,h.toTexture.magFilter=o.LINEAR),h.transitions[r]||(h.transitions[r]=(((c=Eh)==null?void 0:c.default)??Eh)(o,hy[r])),h.transitions[r].draw(i,h.fromTexture,h.toTexture,n,s),!l)return o.flush(),new Uint8Array(0);const f=new Uint8Array(n*s*4);return o.readPixels(0,0,n,s,o.RGBA,o.UNSIGNED_BYTE,f),o.flush(),f}function gy(r){for(const[e,t]of r.entries())t.buffer&&e.deleteBuffer(t.buffer),t.fromTexture&&t.fromTexture.dispose(),t.toTexture&&t.toTexture.dispose(),Object.values(t.transitions).forEach(i=>{i.dispose()}),r.delete(e)}function py({name:r,to:e,from:t,progress:i,canvas:n,contextResources:s}){const o=n.getContext("webgl",{alpha:!0,depth:!1,antialias:!1,preserveDrawingBuffer:!1});o&&(o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,!0),fy({name:r,to:e,from:t,progress:i,width:n.width,height:n.height,glContext:o,contextResources:s,returnPixels:!1}))}async function Ph({debug:r=!1,config:e,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s=Dh,drawTransition:o=py}){const a=new Map,l=await Promise.all(e.tracks.map(async c=>{if(cy(c))return{...await sy({debug:r,track:c,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}),config:c};if(ay(c))return{...await oy({debug:r,track:c,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}),config:c};if(ly(c))return{...await ny({debug:r,track:c,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}),config:c};if(Ay(c))return{...await iy({track:c}),config:c};throw new Error("Unknown track type")}));return{draw:async({canvas:c,currentTime:h})=>{const d=c.getContext("2d");if(d){d.globalAlpha=1,d.globalCompositeOperation="source-over",d.clearRect(0,0,c.width,c.height),d.save(),d.fillStyle="black",d.fillRect(0,0,c.width,c.height),d.restore();for await(const f of l){if(uy(f))continue;const{scenes:g,transitions:p,trackCanvas:v}=f;v.width=v.height=0,v.width=c.width,v.height=c.height;const B=v.getContext("2d"),C=g.filter(({start:x,duration:w})=>h>=x&&h<x+w);if(!B||C.length<=0)continue;const y=p.find(({start:x,duration:w})=>h>=x&&h<x+w);for await(const{sceneCanvas:x,draw:w}of C)await(w==null?void 0:w(h)),(!y||y&&(!y.to||!y.from))&&B.drawImage(x,0,0,x.width,x.height);if(y&&y.to&&y.from&&y.duration>0){const{name:x,to:w,from:D,duration:F,transitionCanvas:O}=y;O.width=O.height=0,O.width=v.width,O.height=v.height;const M=Math.min(1,Math.max(0,(h-w.start)/F));await o({name:x,progress:M,contextResources:a,to:w.sceneCanvas,from:D.sceneCanvas,canvas:O}),B.globalCompositeOperation="lighter",B.drawImage(O,0,0,O.width,O.height)}d.drawImage(v,0,0,v.width,v.height)}}},cleanup:()=>{gy(a)},tracks:l,aspectRatio:e.aspectRatio,duration:Math.max(...l.map(({duration:c})=>c))}}const my={version:"6.1.0"};function Ey(r){const{publicApiUrl:e}=_s(r),t=Ki();return navigator.sendBeacon(`${e}/api/visitor`,JSON.stringify({visitorId:t})),t}function Iy(r){var s,o,a,l,A,u,c,h,d,f,g,p;if(typeof window>"u")return{client:null,tab:null,request:Ki()};let e=(o=(s=window.localStorage)==null?void 0:s.getItem)==null?void 0:o.call(s,"vouch-uid-visitor"),t=(l=(a=window.localStorage)==null?void 0:a.getItem)==null?void 0:l.call(a,"vouch-uid-client"),i=(u=(A=window.sessionStorage)==null?void 0:A.getItem)==null?void 0:u.call(A,"vouch-uid-tab");const n=Ki();return e||(e=Ey(r),(h=(c=window.localStorage)==null?void 0:c.setItem)==null||h.call(c,"vouch-uid-visitor",e)),t||(t=Ki(),(f=(d=window.localStorage)==null?void 0:d.setItem)==null||f.call(d,"vouch-uid-client",t)),i||(i=Ki(),(p=(g=window.sessionStorage)==null?void 0:g.setItem)==null||p.call(g,"vouch-uid-tab",i)),{client:t,tab:i,request:n,visitor:e}}function vy(r,e){return r&&"vouchId"in r?r.vouchId:(e==null?void 0:e.id)??null}function yy(r="embedded_player"){var n,s;const[e,t]=((s=(n=Intl.DateTimeFormat().resolvedOptions().timeZone)==null?void 0:n.split)==null?void 0:s.call(n,"/"))??[],i={};return[...new URLSearchParams(location.search).entries()].forEach(([o,a])=>{if(/utm/.test(o)){const l=o.toLowerCase().replace(/[-_][a-z0-9]/g,A=>A.slice(-1).toUpperCase());i[l]=a}}),{source:r,time:new Date,region:t,country:e,screenHeight:window.screen.height,screenWidth:window.screen.width,referrer:document.referrer,currentUrl:location.href,embedType:"media-player-embed",embedVersion:my.version,templateVersion:ey,...i}}const Nh=1;class Cy{constructor(e){this._batchedEvents=[],this._hasPlayed=!1,this._hasLoaded={},this._answersViewed={},this._streamStartTime={},this._streamLatestTime={},this._currentlyPlayingVideo=null,this._createTrackingEvent=(t,i)=>{const n=vy(i,this.host.vouch);!n||this.host.disableTracking||this._batchedEvents.push({event:t,payload:{...i,senderId:this.host.senderId,vouchId:n,time:new Date().toISOString()}})},this._sendTrackingEvent=()=>{if(this._batchedEvents.length<=0)return;const{publicApiUrl:t}=_s(this.host.env),{client:i,tab:n,request:s,visitor:o}=Iy(this.host.env);navigator.sendBeacon(`${t}/api/batchevents`,JSON.stringify({payload:{events:this._batchedEvents},context:{"x-uid-client":i,"x-uid-tab":n,"x-uid-request":s,"x-uid-visitor":o,"x-reporting-metadata":yy(this.host.trackingSource)}})),this._batchedEvents=[]},this._streamEnded=()=>{if(this._currentlyPlayingVideo){const{id:t,key:i}=this._currentlyPlayingVideo;this._streamLatestTime[i]>this._streamStartTime[i]+Nh&&this._createTrackingEvent("VIDEO_STREAMED",{answerId:t,streamStart:this._streamStartTime[i],streamEnd:this._streamLatestTime[i]}),delete this._streamStartTime[i],delete this._streamLatestTime[i]}},this._handleVouchLoaded=({detail:t})=>{t&&(this._hasLoaded[t]||(this._createTrackingEvent("VOUCH_LOADED",{vouchId:t}),this._hasLoaded[t]=!0))},this._handlePlay=()=>{this._hasPlayed||(this._createTrackingEvent("VIDEO_PLAYED",{streamStart:this.host.currentTime}),this._hasPlayed=!0)},this._handleVideoPlay=({detail:{id:t,key:i}})=>{this._answersViewed[i]||(this._createTrackingEvent("VOUCH_RESPONSE_VIEWED",{answerId:t}),this._answersViewed[i]=!0)},this._handleVideoTimeUpdate=({detail:{id:t,key:i,node:n}})=>{this.host.paused||(this._currentlyPlayingVideo={id:t,key:i,node:n},this._streamLatestTime[i]=n.currentTime,this._streamStartTime[i]||(this._streamStartTime[i]=n.currentTime,this._streamLatestTime[i]=n.currentTime))},this._handleVideoPause=({detail:{id:t,key:i}})=>{this._streamLatestTime[i]>this._streamStartTime[i]+Nh&&this._createTrackingEvent("VIDEO_STREAMED",{answerId:t,streamStart:this._streamStartTime[i],streamEnd:this._streamLatestTime[i]}),delete this._streamStartTime[i],delete this._streamLatestTime[i]},this._pageUnloading=()=>{this._streamEnded(),this._sendTrackingEvent()},this._handleVisibilityChange=()=>{document.visibilityState==="hidden"&&this._pageUnloading()},this._handlePageHide=()=>{this._pageUnloading()},this.host=e,e.addController(this)}hostConnected(){requestAnimationFrame(()=>{var e,t,i,n;"onvisibilitychange"in document?document.addEventListener("visibilitychange",this._handleVisibilityChange):window.addEventListener("pagehide",this._handlePageHide),this.host.addEventListener("vouch:loaded",this._handleVouchLoaded),(e=this.host.mediaPlayer)==null||e.addEventListener("play",this._handlePlay),(t=this.host.mediaPlayer)==null||t.addEventListener("video:play",this._handleVideoPlay),(i=this.host.mediaPlayer)==null||i.addEventListener("video:pause",this._handleVideoPause),(n=this.host.mediaPlayer)==null||n.addEventListener("video:timeupdate",this._handleVideoTimeUpdate)})}hostDisconnected(){var e,t,i,n;this._pageUnloading(),"onvisibilitychange"in document?document.removeEventListener("visibilitychange",this._handleVisibilityChange):window.removeEventListener("pagehide",this._handlePageHide),this.host.removeEventListener("vouch:loaded",this._handleVouchLoaded),(e=this.host.mediaPlayer)==null||e.removeEventListener("play",this._handlePlay),(t=this.host.mediaPlayer)==null||t.removeEventListener("video:play",this._handleVideoPlay),(i=this.host.mediaPlayer)==null||i.removeEventListener("video:pause",this._handleVideoPause),(n=this.host.mediaPlayer)==null||n.removeEventListener("video:timeupdate",this._handleVideoTimeUpdate)}}var pl={exports:{}};(function(r,e){var t=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof qi<"u"&&qi,i=function(){function s(){this.fetch=!1,this.DOMException=t.DOMException}return s.prototype=t,new s}();(function(s){(function(o){var a=typeof s<"u"&&s||typeof self<"u"&&self||typeof qi<"u"&&qi||{},l={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function A(L){return L&&DataView.prototype.isPrototypeOf(L)}if(l.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(L){return L&&u.indexOf(Object.prototype.toString.call(L))>-1};function h(L){if(typeof L!="string"&&(L=String(L)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(L)||L==="")throw new TypeError('Invalid character in header field name: "'+L+'"');return L.toLowerCase()}function d(L){return typeof L!="string"&&(L=String(L)),L}function f(L){var U={next:function(){var q=L.shift();return{done:q===void 0,value:q}}};return l.iterable&&(U[Symbol.iterator]=function(){return U}),U}function g(L){this.map={},L instanceof g?L.forEach(function(U,q){this.append(q,U)},this):Array.isArray(L)?L.forEach(function(U){if(U.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+U.length);this.append(U[0],U[1])},this):L&&Object.getOwnPropertyNames(L).forEach(function(U){this.append(U,L[U])},this)}g.prototype.append=function(L,U){L=h(L),U=d(U);var q=this.map[L];this.map[L]=q?q+", "+U:U},g.prototype.delete=function(L){delete this.map[h(L)]},g.prototype.get=function(L){return L=h(L),this.has(L)?this.map[L]:null},g.prototype.has=function(L){return this.map.hasOwnProperty(h(L))},g.prototype.set=function(L,U){this.map[h(L)]=d(U)},g.prototype.forEach=function(L,U){for(var q in this.map)this.map.hasOwnProperty(q)&&L.call(U,this.map[q],q,this)},g.prototype.keys=function(){var L=[];return this.forEach(function(U,q){L.push(q)}),f(L)},g.prototype.values=function(){var L=[];return this.forEach(function(U){L.push(U)}),f(L)},g.prototype.entries=function(){var L=[];return this.forEach(function(U,q){L.push([q,U])}),f(L)},l.iterable&&(g.prototype[Symbol.iterator]=g.prototype.entries);function p(L){if(!L._noBody){if(L.bodyUsed)return Promise.reject(new TypeError("Already read"));L.bodyUsed=!0}}function v(L){return new Promise(function(U,q){L.onload=function(){U(L.result)},L.onerror=function(){q(L.error)}})}function B(L){var U=new FileReader,q=v(U);return U.readAsArrayBuffer(L),q}function C(L){var U=new FileReader,q=v(U),R=/charset=([A-Za-z0-9_-]+)/.exec(L.type),_=R?R[1]:"utf-8";return U.readAsText(L,_),q}function y(L){for(var U=new Uint8Array(L),q=new Array(U.length),R=0;R<U.length;R++)q[R]=String.fromCharCode(U[R]);return q.join("")}function x(L){if(L.slice)return L.slice(0);var U=new Uint8Array(L.byteLength);return U.set(new Uint8Array(L)),U.buffer}function w(){return this.bodyUsed=!1,this._initBody=function(L){this.bodyUsed=this.bodyUsed,this._bodyInit=L,L?typeof L=="string"?this._bodyText=L:l.blob&&Blob.prototype.isPrototypeOf(L)?this._bodyBlob=L:l.formData&&FormData.prototype.isPrototypeOf(L)?this._bodyFormData=L:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(L)?this._bodyText=L.toString():l.arrayBuffer&&l.blob&&A(L)?(this._bodyArrayBuffer=x(L.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(L)||c(L))?this._bodyArrayBuffer=x(L):this._bodyText=L=Object.prototype.toString.call(L):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof L=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):l.searchParams&&URLSearchParams.prototype.isPrototypeOf(L)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var L=p(this);if(L)return L;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var L=p(this);return L||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(l.blob)return this.blob().then(B);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var L=p(this);if(L)return L;if(this._bodyBlob)return C(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(y(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},l.formData&&(this.formData=function(){return this.text().then(M)}),this.json=function(){return this.text().then(JSON.parse)},this}var D=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function F(L){var U=L.toUpperCase();return D.indexOf(U)>-1?U:L}function O(L,U){if(!(this instanceof O))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');U=U||{};var q=U.body;if(L instanceof O){if(L.bodyUsed)throw new TypeError("Already read");this.url=L.url,this.credentials=L.credentials,U.headers||(this.headers=new g(L.headers)),this.method=L.method,this.mode=L.mode,this.signal=L.signal,!q&&L._bodyInit!=null&&(q=L._bodyInit,L.bodyUsed=!0)}else this.url=String(L);if(this.credentials=U.credentials||this.credentials||"same-origin",(U.headers||!this.headers)&&(this.headers=new g(U.headers)),this.method=F(U.method||this.method||"GET"),this.mode=U.mode||this.mode||null,this.signal=U.signal||this.signal||function(){if("AbortController"in a){var k=new AbortController;return k.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&q)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(q),(this.method==="GET"||this.method==="HEAD")&&(U.cache==="no-store"||U.cache==="no-cache")){var R=/([?&])_=[^&]*/;if(R.test(this.url))this.url=this.url.replace(R,"$1_="+new Date().getTime());else{var _=/\?/;this.url+=(_.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}O.prototype.clone=function(){return new O(this,{body:this._bodyInit})};function M(L){var U=new FormData;return L.trim().split("&").forEach(function(q){if(q){var R=q.split("="),_=R.shift().replace(/\+/g," "),k=R.join("=").replace(/\+/g," ");U.append(decodeURIComponent(_),decodeURIComponent(k))}}),U}function j(L){var U=new g,q=L.replace(/\r?\n[\t ]+/g," ");return q.split("\r").map(function(R){return R.indexOf(`
2477
2477
  `)===0?R.substr(1,R.length):R}).forEach(function(R){var _=R.split(":"),k=_.shift().trim();if(k){var K=_.join(":").trim();try{U.append(k,K)}catch(Y){console.warn("Response "+Y.message)}}}),U}w.call(O.prototype);function X(L,U){if(!(this instanceof X))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(U||(U={}),this.type="default",this.status=U.status===void 0?200:U.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=U.statusText===void 0?"":""+U.statusText,this.headers=new g(U.headers),this.url=U.url||"",this._initBody(L)}w.call(X.prototype),X.prototype.clone=function(){return new X(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new g(this.headers),url:this.url})},X.error=function(){var L=new X(null,{status:200,statusText:""});return L.ok=!1,L.status=0,L.type="error",L};var le=[301,302,303,307,308];X.redirect=function(L,U){if(le.indexOf(U)===-1)throw new RangeError("Invalid status code");return new X(null,{status:U,headers:{location:L}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(U,q){this.message=U,this.name=q;var R=Error(U);this.stack=R.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function oe(L,U){return new Promise(function(q,R){var _=new O(L,U);if(_.signal&&_.signal.aborted)return R(new o.DOMException("Aborted","AbortError"));var k=new XMLHttpRequest;function K(){k.abort()}k.onload=function(){var re={statusText:k.statusText,headers:j(k.getAllResponseHeaders()||"")};_.url.indexOf("file://")===0&&(k.status<200||k.status>599)?re.status=200:re.status=k.status,re.url="responseURL"in k?k.responseURL:re.headers.get("X-Request-URL");var he="response"in k?k.response:k.responseText;setTimeout(function(){q(new X(he,re))},0)},k.onerror=function(){setTimeout(function(){R(new TypeError("Network request failed"))},0)},k.ontimeout=function(){setTimeout(function(){R(new TypeError("Network request timed out"))},0)},k.onabort=function(){setTimeout(function(){R(new o.DOMException("Aborted","AbortError"))},0)};function Y(re){try{return re===""&&a.location.href?a.location.href:re}catch{return re}}if(k.open(_.method,Y(_.url),!0),_.credentials==="include"?k.withCredentials=!0:_.credentials==="omit"&&(k.withCredentials=!1),"responseType"in k&&(l.blob?k.responseType="blob":l.arrayBuffer&&(k.responseType="arraybuffer")),U&&typeof U.headers=="object"&&!(U.headers instanceof g||a.Headers&&U.headers instanceof a.Headers)){var ie=[];Object.getOwnPropertyNames(U.headers).forEach(function(re){ie.push(h(re)),k.setRequestHeader(re,d(U.headers[re]))}),_.headers.forEach(function(re,he){ie.indexOf(he)===-1&&k.setRequestHeader(he,re)})}else _.headers.forEach(function(re,he){k.setRequestHeader(he,re)});_.signal&&(_.signal.addEventListener("abort",K),k.onreadystatechange=function(){k.readyState===4&&_.signal.removeEventListener("abort",K)}),k.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return oe.polyfill=!0,a.fetch||(a.fetch=oe,a.Headers=g,a.Request=O,a.Response=X),o.Headers=g,o.Request=O,o.Response=X,o.fetch=oe,o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var n=t.fetch?t:i;e=n.fetch,e.default=n.fetch,e.fetch=n.fetch,e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response,r.exports=e})(pl,pl.exports);var By=pl.exports;const Oh=Fa(By);async function Ty(r){var e;try{if((e=await Oh(r,{method:"HEAD"}))!=null&&e.ok)return r}catch{return}}async function ml({sources:r}){let e=null;const t=r==null?void 0:r.filter(Boolean),i=t==null?void 0:t.find(s=>s.startsWith("blob:")),n=t==null?void 0:t.find(s=>!s.startsWith("http")&&!s.startsWith("blob:"));if(i||n)return i??n;if(t.length>0){const s=t.map(o=>Ty(o));e=(await Promise.all(s)).find(Boolean)}return e}async function by(r){try{return(await Oh(r)).text()}catch{return null}}async function Sy(r){return r=r.trim(),r.startsWith("http")||r.startsWith("blob:")?by(r):r}const xy=Ji(async({original:r,translation:e,originalLanguage:t="",translationLanguage:i=""},{language:n})=>{var s,o;const a={[(s=i==null?void 0:i.split("-"))==null?void 0:s[0]]:e,[(o=t==null?void 0:t.split("-"))==null?void 0:o[0]]:r},l=(n&&a[n])??r;return l?Sy(l):null},{cacheKey:([r,{language:e}])=>JSON.stringify({...r,language:e})});function Qy(r){var e;return((e=r==null?void 0:r.items)==null?void 0:e.map(t=>{var i;return{text:(i=t.alternatives[0])==null?void 0:i.content,start:t.start_time,end:t.end_time}}))??[]}const _y=Ji(async r=>{var e,t,i,n,s,o,a,l,A,u,c;const[h,d,f]=await Promise.all([ml({sources:[(t=(e=r==null?void 0:r.answer)==null?void 0:e.media)==null?void 0:t.video,(n=(i=r==null?void 0:r.answer)==null?void 0:i.media)==null?void 0:n.input]}),ml({sources:[(o=(s=r==null?void 0:r.answer)==null?void 0:s.media)==null?void 0:o.playlist]}),ml({sources:[((l=(a=r==null?void 0:r.answer)==null?void 0:a.media)==null?void 0:l.reducedQuality)??((c=(u=(A=r==null?void 0:r.answer)==null?void 0:A.media)==null?void 0:u.videos)==null?void 0:c.xs)]})]);return{src:h,playlist:d,preview:f}},{cacheKey:([r])=>{var e,t,i,n,s,o,a,l,A,u,c;return JSON.stringify({video:(t=(e=r==null?void 0:r.answer)==null?void 0:e.media)==null?void 0:t.video,input:(n=(i=r==null?void 0:r.answer)==null?void 0:i.media)==null?void 0:n.input,playlist:(o=(s=r==null?void 0:r.answer)==null?void 0:s.media)==null?void 0:o.playlist,preview:((l=(a=r==null?void 0:r.answer)==null?void 0:a.media)==null?void 0:l.reducedQuality)??((c=(u=(A=r==null?void 0:r.answer)==null?void 0:A.media)==null?void 0:u.videos)==null?void 0:c.xs)})}});function Uh(r){var e,t,i,n,s,o,a,l,A,u,c,h;const d=((t=(e=r==null?void 0:r.answer)==null?void 0:e.contact)==null?void 0:t.name)==="Anonymous"?"":((s=(n=(i=r==null?void 0:r.answer)==null?void 0:i.contact)==null?void 0:n.name)==null?void 0:s.trim())??"",f=((l=(a=(o=r==null?void 0:r.answer)==null?void 0:o.contact)==null?void 0:a.client)==null?void 0:l.name)==="Not Supplied"?"":((h=(c=(u=(A=r==null?void 0:r.answer)==null?void 0:A.contact)==null?void 0:u.client)==null?void 0:c.name)==null?void 0:h.trim())??"",[g,p]=d.split(" ");return{name:d,firstName:g,lastName:p,companyName:f}}function wy(r){var e,t;const i=(t=(e=r==null?void 0:r.answer)==null?void 0:e.contact)==null?void 0:t.roleTitle,n=i==null?void 0:i.split(" ");return{roleTitle:i,roleWords:n,firstRoleWord:n==null?void 0:n[0],remainingRoleWords:n==null?void 0:n.slice(1).join(" ")}}const Ry=Ji(async(r,e,t)=>{var i,n,s;const o=(i=e==null?void 0:e.answer)==null?void 0:i.id;return((s=(n=r==null?void 0:r.questions)==null?void 0:n.items)==null?void 0:s.reduce((l,A)=>{var u;return((u=A==null?void 0:A.answer)==null?void 0:u.id)===o?(l??0)+1:l},0))<=1?o:`${o}-${t}`},{cacheKey:([r,e,t])=>{var i;return JSON.stringify({index:t,rootData:e,allQuestions:(i=r==null?void 0:r.questions)==null?void 0:i.items})}});async function El({data:r,rootData:e,index:t},i){var n,s,o,a,l,A,u,c,h,d,f,g,p,v,B,C,y,x,w,D,F,O,M,j;const[X,le,oe]=await Promise.all([Ry(r,e,t),_y(e),xy({original:((s=(n=e==null?void 0:e.answer)==null?void 0:n.media)==null?void 0:s.captions)??((a=(o=e==null?void 0:e.answer)==null?void 0:o.captions)==null?void 0:a.current),translation:((A=(l=e==null?void 0:e.answer)==null?void 0:l.media)==null?void 0:A.translation)??((c=(u=e==null?void 0:e.answer)==null?void 0:u.captions)==null?void 0:c.translation),originalLanguage:(d=(h=e==null?void 0:e.answer)==null?void 0:h.transcription)==null?void 0:d.language,translationLanguage:(p=(g=(f=e==null?void 0:e.answer)==null?void 0:f.transcription)==null?void 0:g.translation)==null?void 0:p.language},i)]),L=Uh(e),U=wy(e);return{...le,...L,...U,key:X,captions:oe,wordTimings:Qy((v=e==null?void 0:e.answer)==null?void 0:v.transcription),answerLabel:((B=e==null?void 0:e.answer)==null?void 0:B.label)??(e==null?void 0:e.title),prevAnswerLabel:t?((w=(x=(y=(C=r==null?void 0:r.questions)==null?void 0:C.items)==null?void 0:y[t-1])==null?void 0:x.answer)==null?void 0:w.label)??((O=(F=(D=r==null?void 0:r.questions)==null?void 0:D.items)==null?void 0:F[t-1])==null?void 0:O.title)??null:null,isFirstInstanceOfName:t?((j=(M=r==null?void 0:r.questions)==null?void 0:M.items)==null?void 0:j.findIndex(q=>Uh(q).name===L.name))===t:!0}}const ao={af:"Afrikaans",sq:"Albanian",am:"Amharic",ar:"Arabic",hy:"Armenian",az:"Azerbaijani",eu:"Basque",be:"Belarusian",bn:"Bengali",bs:"Bosnian",bg:"Bulgarian",ca:"Catalan",zh:"Chinese (Simplified)",zh_TW:"Chinese (Traditional)",hr:"Croatian",cs:"Czech",da:"Danish",nl:"Dutch",en:"English",et:"Estonian",fi:"Finnish",fr:"French",fa:"Farsi",tl:"Filipino",ka:"Georgian",de:"German",el:"Greek",gu:"Gujarati",ht:"Haitian Creole",ha:"Hausa",he:"Hebrew",hi:"Hindi",hu:"Hungarian",is:"Icelandic",id:"Indonesian",ga:"Irish",it:"Italian",ja:"Japanese",kn:"Kannada",kk:"Kazakh",ko:"Korean",lv:"Latvian",lt:"Lithuanian",mk:"Macedonian",ms:"Malay",ml:"Malayalam",mt:"Maltese",mr:"Marathi",mn:"Mongolian",no:"Norwegian",ps:"Pashto",pl:"Polish",pt:"Portuguese",pa:"Punjabi",ro:"Romanian",ru:"Russian",sr:"Serbian",si:"Sinhala",sk:"Slovak",sl:"Slovenian",so:"Somali",es:"Spanish",sw:"Swahili",sv:"Swedish",ta:"Tamil",te:"Telugu",th:"Thai",tr:"Turkish",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",vi:"Vietnamese",cy:"Welsh"};function Dy({data:r}){var e,t;return((t=(e=r==null?void 0:r.questions)==null?void 0:e.items)==null?void 0:t.reduce((i,n)=>{var s,o,a,l,A,u,c;const h=(a=(o=(s=n==null?void 0:n.answer)==null?void 0:s.transcription)==null?void 0:o.language)==null?void 0:a.split("-")[0],d=(c=(u=(A=(l=n==null?void 0:n.answer)==null?void 0:l.transcription)==null?void 0:A.translation)==null?void 0:u.language)==null?void 0:c.split("-")[0];return h&&ao[h]&&!i.find(f=>f.value===h)&&i.push({value:h,label:ao[h]}),d&&ao[d]&&!i.find(f=>f.value===d)&&i.push({value:d,label:ao[d]}),i},[]))??[]}/**
2478
2478
  * @license
2479
2479
  * Copyright 2018 Google LLC
@@ -2492,23 +2492,23 @@ vec4 transition(vec2 uv) {
2492
2492
  New BW estimate: ${this.getBwEstimate()|0} bps
2493
2493
  Switching to level ${k} @ ${K|0} bps`),o.nextLoadLevel=o.nextAutoLevel=k,this.clearTimer();const ie=()=>{if(this.clearTimer(),this.fragCurrent===n&&this.hls.loadLevel===k&&k>0){const re=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${k>0?"and switching down":""}
2494
2494
  Fragment duration: ${n.duration.toFixed(3)} s
2495
- Time to underbuffer: ${re.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,k>d){let he=this.findBestLevel(this.hls.levels[d].bitrate,d,k,0,re,1,1);he===-1&&(he=d),this.hls.nextLoadLevel=this.hls.nextAutoLevel=he,this.resetEstimator(this.hls.levels[he].bitrate)}}};p||L>_*2?ie():this.timer=self.setInterval(ie,_*1e3),o.trigger(I.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:s,stats:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new Fy(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.FRAG_LOADING,this.onFragLoading,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.FRAG_LOADING,this.onFragLoading,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(I.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var n;this.fragCurrent=i,this.partCurrent=(n=t.part)!=null?n:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case V.BUFFER_ADD_CODEC_ERROR:case V.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case V.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:n,partCurrent:s}=this;if(i&&n&&i.sn===n.sn&&i.level===n.level){const o=performance.now(),a=s?s.stats:i.stats,l=o-a.loading.start,A=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&A>-1){const c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(c,A),a.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,n){const s=e+i/t,o=n?e+this.lastLevelLoadSec:0;return s+o}onLevelLoaded(e,t){const i=this.hls.config,{loading:n}=t.stats,s=n.end-n.first;de(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const n=i?i.stats:t.stats;if(t.type===Ee.MAIN&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const s=i?i.duration:t.duration,o=this.hls.levels[t.level],a=(o.loaded?o.loaded.bytes:0)+n.loaded,l=(o.loaded?o.loaded.duration:0)+s;o.loaded={bytes:a,duration:l},o.realBitrate=Math.round(8*a/l)}if(t.bitrateTest){const s={stats:n,frag:t,part:i,id:t.type};this.onFragBuffered(I.FRAG_BUFFERED,s),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:n}=t,s=n!=null&&n.stats.loaded?n.stats:i.stats;if(s.aborted||this.ignoreFragment(i))return;const o=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Ee.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,s=this.findBestLevel(i,t,e,0,n,1,1);if(s>-1)return s;const o=this.hls.firstLevel,a=Math.min(Math.max(o,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const s=i&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const o=this.hls.levels;if(o.length>Math.max(e,s)&&o[e].loadError<=o[s].loadError)return e}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:n,config:s,minAutoLevel:o}=i,a=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),A=this.getStarvationDelay();let u=s.abrBandWidthFactor,c=s.abrBandWidthUpFactor;if(A){const p=this.findBestLevel(l,o,n,A,0,u,c);if(p>=0)return this.rebufferNotice=-1,p}let h=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!A){const p=this.bitrateTestDelay;p&&(h=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-p,this.info(`bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),u=c=1)}const d=this.findBestLevel(l,o,n,A,h,u,c);if(this.rebufferNotice!==d&&(this.rebufferNotice=d,this.info(`${A?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`)),d>-1)return d;const f=i.levels[o],g=i.loadLevelObj;return g&&(f==null?void 0:f.bitrate)<g.bitrate?o:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,n,s,o,a){var l;const A=n+s,u=this.lastLoadedFragLevel,c=u===-1?this.hls.firstLevel:u,{fragCurrent:h,partCurrent:d}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:v}=this.hls;if(f.length===1)return 0;const B=f[c],C=!!((l=this.hls.latestLevelDetails)!=null&&l.live),y=p===-1||u===-1;let x,w="SDR",D=(B==null?void 0:B.frameRate)||0;const{audioPreference:F,videoPreference:O}=v,M=this.audioTracksByGroup||(this.audioTracksByGroup=gd(g));let j=-1;if(y){if(this.firstSelection!==-1)return this.firstSelection;const U=this.codecTiers||(this.codecTiers=BC(f,M,t,i)),q=CC(U,w,e,F,O),{codecSet:R,videoRanges:_,minFramerate:k,minBitrate:K,minIndex:Y,preferHDR:ie}=q;j=Y,x=R,w=ie?_[_.length-1]:_[0],D=k,e=Math.max(e,K),this.log(`picked start tier ${rt(q)}`)}else x=B==null?void 0:B.codecSet,w=B==null?void 0:B.videoRange;const X=d?d.duration:h?h.duration:0,le=this.bwEstimator.getEstimateTTFB()/1e3,oe=[];for(let U=i;U>=t;U--){var L;const q=f[U],R=U>c;if(!q)continue;if(v.useMediaCapabilities&&!q.supportedResult&&!q.supportedPromise){const he=navigator.mediaCapabilities;typeof(he==null?void 0:he.decodingInfo)=="function"&&(gC(q,M,w,D,e,F)||uo(q.videoCodec))?(q.supportedPromise=ud(q,M,he),q.supportedPromise.then(fe=>{if(!this.hls)return;q.supportedResult=fe;const _e=this.hls.levels,be=_e.indexOf(q);fe.error?this.warn(`MediaCapabilities decodingInfo error: "${fe.error}" for level ${be} ${rt(fe)}`):fe.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${be} ${rt(fe)}`),be>-1&&_e.length>1&&(this.log(`Removing unsupported level ${be}`),this.hls.removeLevel(be),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))})):q.supportedResult=ld}if((x&&q.codecSet!==x||w&&q.videoRange!==w||R&&D>q.frameRate||!R&&D>0&&D<q.frameRate||q.supportedResult&&!((L=q.supportedResult.decodingInfoResults)!=null&&L[0].smooth))&&(!y||U!==j)){oe.push(U);continue}const _=q.details,k=(d?_==null?void 0:_.partTarget:_==null?void 0:_.averagetargetduration)||X;let K;R?K=a*e:K=o*e;const Y=X&&n>=X*2&&s===0?q.averageBitrate:q.maxBitrate,ie=this.getTimeToLoadFrag(le,K,Y*k,_===void 0);if(K>=Y&&(U===u||q.loadError===0&&q.fragmentError===0)&&(ie<=le||!de(ie)||C&&!this.bitrateTestDelay||ie<A)){const he=this.forcedAutoLevel;return U!==p&&(he===-1||he!==p)&&(oe.length&&this.trace(`Skipped level(s) ${oe.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[oe[0]].codecs}" ${f[oe[0]].videoRange}; not compatible with "${x}" ${w}`),this.info(`switch candidate:${c}->${U} adjustedbw(${Math.round(K)})-bitrate=${Math.round(K-Y)} ttfb:${le.toFixed(1)} avgDuration:${k.toFixed(1)} maxFetchDuration:${A.toFixed(1)} fetchDuration:${ie.toFixed(1)} firstSelection:${y} codecSet:${q.codecSet} videoRange:${q.videoRange} hls.loadLevel:${p}`)),y&&(this.firstSelection=U),U}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}}const Rl={search:function(r,e){let t=0,i=r.length-1,n=null,s=null;for(;t<=i;){n=(t+i)/2|0,s=r[n];const o=e(s);if(o>0)t=n+1;else if(o<0)i=n-1;else return s}return null}};function QC(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!de(e))return null;const i=r[0].programDateTime;if(e<(i||0))return null;const n=r[r.length-1].endProgramDateTime;if(e>=(n||0))return null;t=t||0;for(let s=0;s<r.length;++s){const o=r[s];if(wC(e,t,o))return o}return null}function Br(r,e,t=0,i=0,n=.005){let s=null;if(r){s=e[1+r.sn-e[0].sn]||null;const a=r.endDTS-t;a>0&&a<15e-7&&(t+=15e-7),s&&r.level!==s.level&&s.end<=r.end&&(s=e[2+r.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(s=e[0]);if(s&&((!r||r.level===s.level)&&Ed(t,i,s)===0||_C(s,r,Math.min(n,i))))return s;const o=Rl.search(e,Ed.bind(null,t,i));return o&&(o!==r||!s)?o:s}function _C(r,e,t){if(e&&e.start===0&&e.level<r.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((n,s)=>(s[0]==="INF"&&(n+=parseFloat(s[1])),n),t);return r.start<=i}return!1}function Ed(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 wC(r,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>r}function Id(r,e){return Rl.search(r,t=>t.cc<e?1:t.cc>e?-1:0)}function RC(r,e,t){if(r&&r.startCC<=e&&r.endCC>=e){const i=t.start,n=t.end;let s=r.fragments;if(!t.relurl){const{fragmentHint:o}=r;o&&(s=s.concat(o))}return Rl.search(s,o=>o.cc<e||o.end<=i?1:o.cc>e||o.start>=n?-1:0)}return null}function Io(r){switch(r.details){case V.FRAG_LOAD_TIMEOUT:case V.KEY_LOAD_TIMEOUT:case V.LEVEL_LOAD_TIMEOUT:case V.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function vd(r,e){const t=Io(e);return r.default[`${t?"timeout":"error"}Retry`]}function Dl(r,e){const t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function yd(r){return Ve(Ve({},r),{errorRetry:null,timeoutRetry:null})}function vo(r,e,t,i){if(!r)return!1;const n=i==null?void 0:i.code,s=e<r.maxNumRetry&&(DC(n)||!!t);return r.shouldRetry?r.shouldRetry(r,e,t,i,s):s}function DC(r){return r===0&&navigator.onLine===!1||!!r&&(r<400||r>499)}var wt={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},ni={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2};class LC extends _i{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(I.ERROR,this.onError,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(I.ERROR,this.onError,this),e.off(I.ERROR,this.onErrorOut,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===Ee.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 n=this.hls,s=t.context;switch(t.details){case V.FRAG_LOAD_ERROR:case V.FRAG_LOAD_TIMEOUT:case V.KEY_LOAD_ERROR:case V.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case V.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=$n();return}case V.FRAG_GAP:case V.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=wt.SendAlternateToPenaltyBox;return}case V.LEVEL_EMPTY_ERROR:case V.LEVEL_PARSING_ERROR:{var o,a;const A=t.parent===Ee.MAIN?t.level:n.loadLevel;t.details===V.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(a=o.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,A):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,A))}return;case V.LEVEL_LOAD_ERROR:case V.LEVEL_LOAD_TIMEOUT:typeof(s==null?void 0:s.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.level));return;case V.AUDIO_TRACK_LOAD_ERROR:case V.AUDIO_TRACK_LOAD_TIMEOUT:case V.SUBTITLE_LOAD_ERROR:case V.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){const A=n.loadLevelObj;if(A&&(s.type===Me.AUDIO_TRACK&&A.hasAudioGroup(s.groupId)||s.type===Me.SUBTITLE_TRACK&&A.hasSubtitleGroup(s.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=wt.SendAlternateToPenaltyBox,t.errorAction.flags=ni.MoveAllAlternatesMatchingHost;return}}return;case V.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const A=n.loadLevelObj,u=A==null?void 0:A.attrs["HDCP-LEVEL"];u?t.errorAction={action:wt.SendAlternateToPenaltyBox,flags:ni.MoveAllAlternatesMatchingHDCP,hdcpLevel:u}:this.keySystemError(t)}return;case V.BUFFER_ADD_CODEC_ERROR:case V.REMUX_ALLOC_ERROR:case V.BUFFER_APPEND_ERROR:if(!t.errorAction){var l;t.errorAction=this.getLevelSwitchAction(t,(l=t.level)!=null?l:n.loadLevel)}return;case V.INTERNAL_EXCEPTION:case V.BUFFER_APPENDING_ERROR:case V.BUFFER_FULL_ERROR:case V.LEVEL_SWITCH_ERROR:case V.BUFFER_STALLED_ERROR:case V.BUFFER_SEEK_OVER_HOLE:case V.BUFFER_NUDGE_ON_STALL:t.errorAction=$n();return}t.type===Ie.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,n=vd(i.config.playlistLoadPolicy,e),s=this.playlistError++;if(vo(n,s,Io(e),e.response))return{action:wt.RetryRequest,flags:ni.None,retryConfig:n,retryCount:s};const a=this.getLevelSwitchAction(e,t);return n&&(a.retryConfig=n,a.retryCount=s),a}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),n=t.levels[i],{fragLoadPolicy:s,keyLoadPolicy:o}=t.config,a=vd(e.details.startsWith("key")?o:s,e),l=t.levels.reduce((u,c)=>u+c.fragmentError,0);if(n&&(e.details!==V.FRAG_GAP&&n.fragmentError++,vo(a,l,Io(e),e.response)))return{action:wt.RetryRequest,flags:ni.None,retryConfig:a,retryCount:l};const A=this.getLevelSwitchAction(e,i);return a&&(A.retryConfig=a,A.retryCount=l),A}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const n=this.hls.levels[t];if(n){var s,o;const A=e.details;n.loadError++,A===V.BUFFER_APPEND_ERROR&&n.fragmentError++;let u=-1;const{levels:c,loadLevel:h,minAutoLevel:d,maxAutoLevel:f}=i;i.autoLevelEnabled||(i.loadLevel=-1);const g=(s=e.frag)==null?void 0:s.type,v=(g===Ee.AUDIO&&A===V.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(A===V.BUFFER_ADD_CODEC_ERROR||A===V.BUFFER_APPEND_ERROR))&&c.some(({audioCodec:w})=>n.audioCodec!==w),C=e.sourceBufferName==="video"&&(A===V.BUFFER_ADD_CODEC_ERROR||A===V.BUFFER_APPEND_ERROR)&&c.some(({codecSet:w,audioCodec:D})=>n.codecSet!==w&&n.audioCodec===D),{type:y,groupId:x}=(o=e.context)!=null?o:{};for(let w=c.length;w--;){const D=(w+h)%c.length;if(D!==h&&D>=d&&D<=f&&c[D].loadError===0){var a,l;const F=c[D];if(A===V.FRAG_GAP&&g===Ee.MAIN&&e.frag){const O=c[D].details;if(O){const M=Br(e.frag,O.fragments,e.frag.start);if(M!=null&&M.gap)continue}}else{if(y===Me.AUDIO_TRACK&&F.hasAudioGroup(x)||y===Me.SUBTITLE_TRACK&&F.hasSubtitleGroup(x))continue;if(g===Ee.AUDIO&&(a=n.audioGroups)!=null&&a.some(O=>F.hasAudioGroup(O))||g===Ee.SUBTITLE&&(l=n.subtitleGroups)!=null&&l.some(O=>F.hasSubtitleGroup(O))||v&&n.audioCodec===F.audioCodec||!v&&n.audioCodec!==F.audioCodec||C&&n.codecSet===F.codecSet)continue}u=D;break}}if(u>-1&&i.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:wt.SendAlternateToPenaltyBox,flags:ni.None,nextAutoLevel:u}}return{action:wt.SendAlternateToPenaltyBox,flags:ni.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case wt.DoNothing:break;case wt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==V.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:n,hdcpLevel:s,nextAutoLevel:o}=i;switch(n){case ni.None:this.switchLevel(e,o);break;case ni.MoveAllAlternatesMatchingHDCP:s&&(t.maxHdcpLevel=wl[wl.indexOf(s)-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){if(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,e.details===V.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const i=ad(e.mimeType),n=this.hls.levels;for(let s=n.length;s--;)n[s][`${e.sourceBufferName}Codec`]===i&&this.hls.removeLevel(s)}}}function $n(r){const e={action:wt.DoNothing,flags:ni.None};return r&&(e.resolved=!0),e}var vt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class kC{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(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.BUFFER_APPENDED,this.onBufferAppended,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.BUFFER_APPENDED,this.onBufferAppended,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.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 n=i.length;n--;){const s=i[n];if(!s)break;const o=s.end;if(s.start<=e&&o!==null&&e<=o)return s}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){const{fragments:n}=this,s=Object.keys(n);for(let o=s.length;o--;){const a=n[s[o]];if((a==null?void 0:a.body.type)===t&&(!i||a.buffered)){const l=a.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,i,n,s){this.timeRanges&&(this.timeRanges[e]=t);const o=(n==null?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(a=>{const l=this.fragments[a];if(!l||o>=l.body.sn)return;if(!l.buffered&&(!l.loaded||s)){l.body.type===i&&this.removeFragment(l.body);return}const A=l.range[e];if(A){if(A.time.length===0){this.removeFragment(l.body);return}A.time.some(u=>{const c=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return c&&this.removeFragment(l.body),c})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const i=e.frag,n=$r(i),s=this.fragments[n];if(!s||s.buffered&&i.gap)return;const o=!i.relurl;Object.keys(t).forEach(a=>{const l=i.elementaryStreams[a];if(!l)return;const A=t[a],u=o||l.partial===!0;s.range[a]=this.getBufferedTimes(i,e.part,u,A)}),s.loaded=null,Object.keys(s.range).length?(s.buffered=!0,(s.body.endList=i.endList||s.body.endList)&&(this.endListFragments[s.body.type]=s),yo(s)||this.removeParts(i.sn-1,i.type)):this.removeFragment(s.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=Cd(i,n=>n.fragment.sn>=e))}fragBuffered(e,t){const i=$r(e);let n=this.fragments[i];!n&&t&&(n=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,n.buffered=!0)}getBufferedTimes(e,t,i,n){const s={time:[],partial:i},o=e.start,a=e.end,l=e.minEndPTS||a,A=e.maxStartPTS||o;for(let u=0;u<n.length;u++){const c=n.start(u)-this.bufferPadding,h=n.end(u)+this.bufferPadding;if(A>=c&&l<=h){s.time.push({startPTS:Math.max(o,n.start(u)),endPTS:Math.min(a,n.end(u))});break}else if(o<h&&a>c){const d=Math.max(o,n.start(u)),f=Math.min(a,n.end(u));f>d&&(s.partial=!0,s.time.push({startPTS:d,endPTS:f}))}else if(a<=c)break}return s}getPartialFragment(e){let t=null,i,n,s,o=0;const{bufferPadding:a,fragments:l}=this;return Object.keys(l).forEach(A=>{const u=l[A];u&&yo(u)&&(n=u.body.start-a,s=u.body.end+a,e>=n&&e<=s&&(i=Math.min(e-n,s-e),o<=i&&(t=u.body,o=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||yo(t))}getState(e){const t=$r(e),i=this.fragments[t];return i?i.buffered?yo(i)?vt.PARTIAL:vt.OK:vt.APPENDING:vt.NOT_LOADED}isTimeBuffered(e,t,i){let n,s;for(let o=0;o<i.length;o++){if(n=i.start(o)-this.bufferPadding,s=i.end(o)+this.bufferPadding,e>=n&&t<=s)return!0;if(t<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const i=t.frag,n=t.part?null:t,s=$r(i);this.fragments[s]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:n,timeRanges:s,type:o}=t;if(i.sn==="initSegment")return;const a=i.type;if(n){let A=this.activePartLists[a];A||(this.activePartLists[a]=A=[]),A.push(n)}this.timeRanges=s;const l=s[o];this.detectEvictedFragments(o,l,a,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=$r(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let n=i.length;n--;){const s=t[i[n]];if((s==null?void 0:s.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,n,s){n&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const a=this.fragments[o];if(!a)return;const l=a.body;l.type!==i||n&&!l.gap||l.start<t&&l.end>e&&(a.buffered||s)&&this.removeFragment(l)})}removeFragment(e){const t=$r(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const n=e.sn;this.activePartLists[e.type]=Cd(i,s=>s.fragment.sn!==n)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e,t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const i=(e=this.hls)==null||(t=e.latestLevelDetails)==null?void 0:t.partList;i&&i.forEach(n=>n.clearElementaryStreamInfo())}}function yo(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 $r(r){return`${r.type}_${r.level}_${r.sn}`}function Cd(r,e){return r.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var er={cbc:0,ctr:1};class MC{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case er.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case er.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function FC(r){const e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?r.slice(0,e-t):r}class PC{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 n=0;n<4;n++)i[n]=t.getUint32(n*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,n=i[0],s=i[1],o=i[2],a=i[3],l=this.invSubMix,A=l[0],u=l[1],c=l[2],h=l[3],d=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)p<128?d[p]=p<<1:d[p]=p<<1^283;for(p=0;p<256;p++){let v=g^g<<1^g<<2^g<<3^g<<4;v=v>>>8^v&255^99,e[f]=v,t[v]=f;const B=d[f],C=d[B],y=d[C];let x=d[v]*257^v*16843008;n[f]=x<<24|x>>>8,s[f]=x<<16|x>>>16,o[f]=x<<8|x>>>24,a[f]=x,x=y*16843009^C*65537^B*257^f*16843008,A[v]=x<<24|x>>>8,u[v]=x<<16|x>>>16,c[v]=x<<8|x>>>24,h[v]=x,f?(f=B^d[d[d[y^B]]],g^=d[d[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,n=0;for(;n<t.length&&i;)i=t[n]===this.key[n],n++;if(i)return;this.key=t;const s=this.keySize=t.length;if(s!==4&&s!==6&&s!==8)throw new Error("Invalid aes key size="+s);const o=this.ksRows=(s+6+1)*4;let a,l;const A=this.keySchedule=new Uint32Array(o),u=this.invKeySchedule=new Uint32Array(o),c=this.sBox,h=this.rcon,d=this.invSubMix,f=d[0],g=d[1],p=d[2],v=d[3];let B,C;for(a=0;a<o;a++){if(a<s){B=A[a]=t[a];continue}C=B,a%s===0?(C=C<<8|C>>>24,C=c[C>>>24]<<24|c[C>>>16&255]<<16|c[C>>>8&255]<<8|c[C&255],C^=h[a/s|0]<<24):s>6&&a%s===4&&(C=c[C>>>24]<<24|c[C>>>16&255]<<16|c[C>>>8&255]<<8|c[C&255]),A[a]=B=(A[a-s]^C)>>>0}for(l=0;l<o;l++)a=o-l,l&3?C=A[a]:C=A[a-4],l<4||a<=4?u[l]=C:u[l]=f[c[C>>>24]]^g[c[C>>>16&255]]^p[c[C>>>8&255]]^v[c[C&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const n=this.keySize+6,s=this.invKeySchedule,o=this.invSBox,a=this.invSubMix,l=a[0],A=a[1],u=a[2],c=a[3],h=this.uint8ArrayToUint32Array_(i);let d=h[0],f=h[1],g=h[2],p=h[3];const v=new Int32Array(e),B=new Int32Array(v.length);let C,y,x,w,D,F,O,M,j,X,le,oe,L,U;const q=this.networkToHostOrderSwap;for(;t<v.length;){for(j=q(v[t]),X=q(v[t+1]),le=q(v[t+2]),oe=q(v[t+3]),D=j^s[0],F=oe^s[1],O=le^s[2],M=X^s[3],L=4,U=1;U<n;U++)C=l[D>>>24]^A[F>>16&255]^u[O>>8&255]^c[M&255]^s[L],y=l[F>>>24]^A[O>>16&255]^u[M>>8&255]^c[D&255]^s[L+1],x=l[O>>>24]^A[M>>16&255]^u[D>>8&255]^c[F&255]^s[L+2],w=l[M>>>24]^A[D>>16&255]^u[F>>8&255]^c[O&255]^s[L+3],D=C,F=y,O=x,M=w,L=L+4;C=o[D>>>24]<<24^o[F>>16&255]<<16^o[O>>8&255]<<8^o[M&255]^s[L],y=o[F>>>24]<<24^o[O>>16&255]<<16^o[M>>8&255]<<8^o[D&255]^s[L+1],x=o[O>>>24]<<24^o[M>>16&255]<<16^o[D>>8&255]<<8^o[F&255]^s[L+2],w=o[M>>>24]<<24^o[D>>16&255]<<16^o[F>>8&255]<<8^o[O&255]^s[L+3],B[t]=q(C^d),B[t+1]=q(w^f),B[t+2]=q(x^g),B[t+3]=q(y^p),d=j,f=X,g=le,p=oe,t=t+4}return B.buffer}}class NC{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){const e=OC(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function OC(r){switch(r){case er.cbc:return"AES-CBC";case er.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${r}`)}}const UC=16;class Ll{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.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?FC(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,n){return this.useSoftware?new Promise((s,o)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,i,n);const l=this.flush();l?s(l.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,n)}softwareDecrypt(e,t,i,n){const{currentIV:s,currentResult:o,remainderData:a}=this;if(n!==er.cbc||t.byteLength!==16)return Ue.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=Jt(a,e),this.remainderData=null);const l=this.getValidChunk(e);if(!l.length)return null;s&&(i=s);let A=this.softwareDecrypter;A||(A=this.softwareDecrypter=new PC),A.expandKey(t);const u=o;return this.currentResult=A.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,i,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,n));this.key=t,this.fastAesKey=new NC(this.subtle,t,n)}return this.fastAesKey.expandKey().then(s=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new MC(this.subtle,new Uint8Array(i),n).decrypt(e.buffer,s)):Promise.reject(new Error("web crypto not initialized"))).catch(s=>(Ue.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(e,t,i,n)))}onWebCryptoError(e,t,i,n){const s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,n);const o=this.flush();if(o)return o.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%UC;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(Ue.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Bd=Math.pow(2,17);class GC{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 wi({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,s=n.fLoader,o=n.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){l(bd(e));return}else e.gap=!1;const A=this.loader=s?new s(n):new o(n),u=Td(e);e.loader=A;const c=yd(n.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Bd};e.stats=A.stats;const d={onSuccess:(f,g,p,v)=>{this.resetLoader(e,A);let B=f.data;p.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(B.slice(0,16)),B=B.slice(16)),a({frag:e,part:null,payload:B,networkDetails:v})},onError:(f,g,p,v)=>{this.resetLoader(e,A),l(new wi({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Ve({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:v}))},onAbort:(f,g,p)=>{this.resetLoader(e,A),l(new wi({type:Ie.NETWORK_ERROR,details:V.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,A),l(new wi({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:p,stats:f}))}};t&&(d.onProgress=(f,g,p,v)=>t({frag:e,part:null,payload:p,networkDetails:v})),A.load(u,h,d)})}loadPart(e,t,i){this.abort();const n=this.config,s=n.fLoader,o=n.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(bd(e,t));return}const A=this.loader=s?new s(n):new o(n),u=Td(e,t);e.loader=A;const c=yd(n.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Bd};t.stats=A.stats,A.load(u,h,{onSuccess:(d,f,g,p)=>{this.resetLoader(e,A),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:d.data,networkDetails:p};i(v),a(v)},onError:(d,f,g,p)=>{this.resetLoader(e,A),l(new wi({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Ve({url:u.url,data:void 0},d),error:new Error(`HTTP Error ${d.code} ${d.text}`),networkDetails:g,stats:p}))},onAbort:(d,f,g)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,A),l(new wi({type:Ie.NETWORK_ERROR,details:V.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:g,stats:d}))},onTimeout:(d,f,g)=>{this.resetLoader(e,A),l(new wi({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:d}))}})})}updateStatsFromPart(e,t){const i=e.stats,n=t.stats,s=n.total;if(i.loaded+=n.loaded,s){const l=Math.round(e.duration/t.duration),A=Math.min(Math.round(i.loaded/s),l),c=(l-A)*Math.round(i.loaded/A);i.total=i.loaded+c}else i.total=Math.max(i.loaded,i.total);const o=i.loading,a=n.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 Td(r,e=null){const t=e||r,i={frag:r,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},n=t.byteRangeStartOffset,s=t.byteRangeEndOffset;if(de(n)&&de(s)){var o;let a=n,l=s;if(r.sn==="initSegment"&&$C((o=r.decryptdata)==null?void 0:o.method)){const A=s-n;A%16&&(l=s+(16-A%16)),n!==0&&(i.resetIV=!0,a=n-16)}i.rangeStart=a,i.rangeEnd=l}return i}function bd(r,e){const t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),i={type:Ie.MEDIA_ERROR,details:V.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(i.part=e),(e||r).stats.aborted=!0,new wi(i)}function $C(r){return r==="AES-128"||r==="AES-256"}class wi extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Sd extends _i{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!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(){}}class kl{constructor(e,t,i,n=0,s=-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=Co(),this.buffering={audio:Co(),video:Co(),audiovideo:Co()},this.level=e,this.sn=t,this.id=i,this.size=n,this.part=s,this.partial=o}}function Co(){return{start:0,executeStart:0,executeEnd:0,end:0}}const xd={length:0,start:()=>0,end:()=>0};class Le{static isBuffered(e,t){if(e){const i=Le.getBuffered(e);for(let n=i.length;n--;)if(t>=i.start(n)&&t<=i.end(n))return!0}return!1}static bufferedRanges(e){if(e){const t=Le.getBuffered(e);return Le.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){const n=Le.bufferedRanges(e);if(n.length)return Le.bufferedInfo(n,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((u,c)=>u.start-c.start||c.end-u.end);let n=-1,s=[];if(i)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(n=u);const c=s.length;if(c){const h=s[c-1].end;e[u].start-h<i?e[u].end>h&&(s[c-1].end=e[u].end):s.push(e[u])}else s.push(e[u])}else s=e;let o=0,a,l=t,A=t;for(let u=0;u<s.length;u++){const c=s[u].start,h=s[u].end;if(n===-1&&t>=c&&t<=h&&(n=u),t+i>=c&&t<h)l=c,A=h,o=A-t;else if(t+i<c){a=c;break}}return{len:o,start:l||0,end:A||0,nextStart:a,buffered:e,bufferedIndex:n}}static getBuffered(e){try{return e.buffered||xd}catch(t){return Ue.log("failed to get media.buffered",t),xd}}}const Qd=/\{\$([a-zA-Z0-9-_]+)\}/g;function _d(r){return Qd.test(r)}function Ml(r,e){if(r.variableList!==null||r.hasVariableRefs){const t=r.variableList;return e.replace(Qd,i=>{const n=i.substring(2,i.length-1),s=t==null?void 0:t[n];return s===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),i):s})}return e}function wd(r,e,t){let i=r.variableList;i||(r.variableList=i={});let n,s;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const o=new self.URL(t).searchParams;if(o.has(n))s=o.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(o){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else n=e.NAME,s=e.VALUE;n in i?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):i[n]=s||""}function HC(r,e,t){const i=e.IMPORT;if(t&&i in t){let n=r.variableList;n||(r.variableList=n={}),n[i]=t[i]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const YC=/^(\d+)x(\d+)$/,Rd=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ot{constructor(e,t){typeof e=="string"&&(e=ot.parseAttrList(e,t)),qe(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}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 n=0;n<t.length/2;n++)i[n]=parseInt(t.slice(n*2,n*2+2),16);return i}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]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((n,s)=>(n[s.toLowerCase()]=!0,n),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=YC.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const n={},s='"';for(Rd.lastIndex=0;(i=Rd.exec(e))!==null;){const o=i[1].trim();let a=i[2];const l=a.indexOf(s)===0&&a.lastIndexOf(s)===a.length-1;let A=!1;if(l)a=a.slice(1,-1);else switch(o){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":A=!0}if(t&&(l||A))a=Ml(t,a);else if(!A&&!l)switch(o){case"CLOSED-CAPTIONS":if(a==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Ue.warn(`${e}: attribute ${o} is missing quotes`)}n[o]=a}return n}}const VC="com.apple.hls.interstitial";function KC(r){return r!=="ID"&&r!=="CLASS"&&r!=="CUE"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function WC(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"||r==="SCTE35-CMD"}class Dd{constructor(e,t,i=0){var n;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(n=t==null?void 0:t.tagOrder)!=null?n:i,t){const s=t.attr;for(const o in s)if(Object.prototype.hasOwnProperty.call(e,o)&&e[o]!==s[o]){Ue.warn(`DATERANGE tag attribute: "${o}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=o;break}e=qe(new ot({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const s=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);de(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(Ue.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(de(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===VC}get isValid(){return!!this.id&&!this._badValueForSameId&&de(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const qC=10;class JC{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.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!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.appliedTimelineOffset=void 0,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.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}get hasProgramDateTime(){return this.fragments.length?de(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||qC}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 fragmentStart(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Hr(r){return r==="AES-128"||r==="AES-256"||r==="AES-256-CTR"}function Fl(r){switch(r){case"AES-128":case"AES-256":return er.cbc;case"AES-256-CTR":return er.ctr;default:throw new Error(`invalid full segment method ${r}`)}}function Pl(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function Nl(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}function jC(r){const e=Nl(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function XC(r){const e=function(i,n,s){const o=i[n];i[n]=i[s],i[s]=o};e(r,0,3),e(r,1,2),e(r,4,5),e(r,6,7)}function zC(r){const e=r.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),n=i[i.length-1].split(",");if(n.length===2){const s=n[0]==="base64",o=n[1];s?(i.splice(-1,1),t=Pl(o)):t=jC(o)}}return t}const Bo=typeof self<"u"?self:void 0;var Ke={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Pt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ol(r){switch(r){case Pt.FAIRPLAY:return Ke.FAIRPLAY;case Pt.PLAYREADY:return Ke.PLAYREADY;case Pt.WIDEVINE:return Ke.WIDEVINE;case Pt.CLEARKEY:return Ke.CLEARKEY}}var To={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Ul(r){if(r===To.WIDEVINE)return Ke.WIDEVINE;if(r===To.PLAYREADY)return Ke.PLAYREADY;if(r===To.CENC||r===To.CLEARKEY)return Ke.CLEARKEY}function Gl(r){switch(r){case Ke.FAIRPLAY:return Pt.FAIRPLAY;case Ke.PLAYREADY:return Pt.PLAYREADY;case Ke.WIDEVINE:return Pt.WIDEVINE;case Ke.CLEARKEY:return Pt.CLEARKEY}}function bo(r){const{drmSystems:e,widevineLicenseUrl:t}=r,i=e?[Ke.FAIRPLAY,Ke.WIDEVINE,Ke.PLAYREADY,Ke.CLEARKEY].filter(n=>!!e[n]):[];return!i[Ke.WIDEVINE]&&t&&i.push(Ke.WIDEVINE),i}const Ld=function(r){return Bo!=null&&(r=Bo.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function ZC(r,e,t,i){let n;switch(r){case Ke.FAIRPLAY:n=["cenc","sinf"];break;case Ke.WIDEVINE:case Ke.PLAYREADY:n=["cenc"];break;case Ke.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return eB(n,e,t,i)}function eB(r,e,t,i){return[{initDataTypes:r,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(s=>({contentType:`audio/mp4; codecs=${s}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(s=>({contentType:`video/mp4; codecs=${s}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function tB(r){var e;return r.sessionType==="persistent-license"||!!((e=r.sessionTypes)!=null&&e.some(t=>t==="persistent-license"))}function kd(r){const e=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.length),o=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(o){const a=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(a){const l=Pl(a).subarray(0,16);return XC(l),l}}return null}let So={};class Hn{static clearKeyUriToKeyIdMap(){So={}}constructor(e,t,i,n=[1],s=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=n,this.iv=s,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Hr(e)}isSupported(){if(this.method){if(Hr(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Pt.FAIRPLAY:case Pt.WIDEVINE:case Pt.PLAYREADY:case Pt.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(Hr(this.method)&&this.uri&&!this.iv){typeof e!="number"&&(Ue.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const i=iB(e);return new Hn(this.method,this.uri,"identity",this.keyFormatVersions,i)}const t=zC(this.uri);if(t)switch(this.keyFormat){case Pt.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Pt.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=aC(i,null,t),this.keyId=kd(t);break}default:{let i=t.subarray(0,16);if(i.length!==16){const n=new Uint8Array(16);n.set(i,16-i.length),i=n}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=So[this.uri];if(!i){const n=Object.keys(So).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,n),So[this.uri]=i}this.keyId=i}return this}}function iB(r){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}const Md=/#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,Fd=/#EXT-X-MEDIA:(.*)/g,rB=/^#EXT(?:INF|-X-TARGETDURATION):/m,$l=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),nB=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class gi{static findGroup(e,t){for(let i=0;i<e.length;i++){const n=e[i];if(n.id===t)return n}}static resolve(e,t){return Cl.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return rB.test(e)}static parseMasterPlaylist(e,t){const i=_d(e),n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},s=[];Md.lastIndex=0;let o;for(;(o=Md.exec(e))!=null;)if(o[1]){var a;const A=new ot(o[1],n),u=Ml(n,o[2]),c={attrs:A,bitrate:A.decimalInteger("BANDWIDTH")||A.decimalInteger("AVERAGE-BANDWIDTH"),name:A.NAME,url:gi.resolve(u,t)},h=A.decimalResolution("RESOLUTION");h&&(c.width=h.width,c.height=h.height),Ud(A.CODECS,c);const d=A["SUPPLEMENTAL-CODECS"];d&&(c.supplemental={},Ud(d,c.supplemental)),(a=c.unknownCodecs)!=null&&a.length||s.push(c),n.levels.push(c)}else if(o[3]){const A=o[3],u=o[4];switch(A){case"SESSION-DATA":{const c=new ot(u,n),h=c["DATA-ID"];h&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[h]=c);break}case"SESSION-KEY":{const c=Nd(u,t,n);c.encrypted&&c.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(c)):Ue.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const c=new ot(u,n);wd(n,c,t)}break}case"CONTENT-STEERING":{const c=new ot(u,n);n.contentSteering={uri:gi.resolve(c["SERVER-URI"],t),pathwayId:c["PATHWAY-ID"]||"."};break}case"START":{n.startTimeOffset=Od(u);break}}}const l=s.length>0&&s.length<n.levels.length;return n.levels=l?s:n.levels,n.levels.length===0&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(e,t,i){let n;const s={},o=i.levels,a={AUDIO:o.map(A=>({id:A.attrs.AUDIO,audioCodec:A.audioCodec})),SUBTITLES:o.map(A=>({id:A.attrs.SUBTITLES,textCodec:A.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Fd.lastIndex=0;(n=Fd.exec(e))!==null;){const A=new ot(n[1],i),u=A.TYPE;if(u){const c=a[u],h=s[u]||[];s[u]=h;const d=A.LANGUAGE,f=A["ASSOC-LANGUAGE"],g=A.CHANNELS,p=A.CHARACTERISTICS,v=A["INSTREAM-ID"],B={attrs:A,bitrate:0,id:l++,groupId:A["GROUP-ID"]||"",name:A.NAME||d||"",type:u,default:A.bool("DEFAULT"),autoselect:A.bool("AUTOSELECT"),forced:A.bool("FORCED"),lang:d,url:A.URI?gi.resolve(A.URI,t):""};if(f&&(B.assocLang=f),g&&(B.channels=g),p&&(B.characteristics=p),v&&(B.instreamId=v),c!=null&&c.length){const C=gi.findGroup(c,B.groupId)||c[0];Gd(B,C,"audioCodec"),Gd(B,C,"textCodec")}h.push(B)}}return s}static parseLevelPlaylist(e,t,i,n,s,o){var a;const l={url:t},A=new JC(t),u=A.fragments,c=[];let h=null,d=0,f=0,g=0,p=0,v=0,B=null,C=new Tl(n,l),y,x,w,D=-1,F=!1,O=null,M;if($l.lastIndex=0,A.m3u8=e,A.hasVariableRefs=_d(e),((a=$l.exec(e))==null?void 0:a[0])!=="#EXTM3U")return A.playlistParsingError=new Error("Missing format identifier #EXTM3U"),A;for(;(y=$l.exec(e))!==null;){F&&(F=!1,C=new Tl(n,l),C.playlistOffset=g,C.start=g,C.sn=d,C.cc=p,v&&(C.bitrate=v),C.level=i,h&&(C.initSegment=h,h.rawProgramDateTime&&(C.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),O&&(C.setByteRange(O),O=null)));const oe=y[1];if(oe){C.duration=parseFloat(oe);const L=(" "+y[2]).slice(1);C.title=L||null,C.tagList.push(L?["INF",oe,L]:["INF",oe])}else if(y[3]){if(de(C.duration)){C.playlistOffset=g,C.start=g,w&&Hd(C,w,A),C.sn=d,C.level=i,C.cc=p,u.push(C);const L=(" "+y[3]).slice(1);C.relurl=Ml(A,L),Hl(C,B,c),B=C,g+=C.duration,d++,f=0,F=!0}}else{if(y=y[0].match(nB),!y){Ue.warn("No matches on slow regex match for level playlist!");continue}for(x=1;x<y.length&&y[x]===void 0;x++);const L=(" "+y[x]).slice(1),U=(" "+y[x+1]).slice(1),q=y[x+2]?(" "+y[x+2]).slice(1):null;switch(L){case"BYTERANGE":B?C.setByteRange(U,B):C.setByteRange(U);break;case"PROGRAM-DATE-TIME":C.rawProgramDateTime=U,C.tagList.push(["PROGRAM-DATE-TIME",U]),D===-1&&(D=u.length);break;case"PLAYLIST-TYPE":A.type&&Ri(A,L,y),A.type=U.toUpperCase();break;case"MEDIA-SEQUENCE":A.startSN!==0?Ri(A,L,y):u.length>0&&Yd(A,L,y),d=A.startSN=parseInt(U);break;case"SKIP":{A.skippedSegments&&Ri(A,L,y);const R=new ot(U,A),_=R.decimalInteger("SKIPPED-SEGMENTS");if(de(_)){A.skippedSegments+=_;for(let K=_;K--;)u.push(null);d+=_}const k=R.enumeratedString("RECENTLY-REMOVED-DATERANGES");k&&(A.recentlyRemovedDateranges=(A.recentlyRemovedDateranges||[]).concat(k.split(" ")));break}case"TARGETDURATION":A.targetduration!==0&&Ri(A,L,y),A.targetduration=Math.max(parseInt(U),1);break;case"VERSION":A.version!==null&&Ri(A,L,y),A.version=parseInt(U);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":A.live||Ri(A,L,y),A.live=!1;break;case"#":(U||q)&&C.tagList.push(q?[U,q]:[U]);break;case"DISCONTINUITY":p++,C.tagList.push(["DIS"]);break;case"GAP":C.gap=!0,C.tagList.push([L]);break;case"BITRATE":C.tagList.push([L,U]),v=parseInt(U)*1e3,de(v)?C.bitrate=v:v=0;break;case"DATERANGE":{const R=new ot(U,A),_=new Dd(R,A.dateRanges[R.ID],A.dateRangeTagCount);A.dateRangeTagCount++,_.isValid||A.skippedSegments?A.dateRanges[_.id]=_:Ue.warn(`Ignoring invalid DATERANGE tag: "${U}"`),C.tagList.push(["EXT-X-DATERANGE",U]);break}case"DEFINE":{{const R=new ot(U,A);"IMPORT"in R?HC(A,R,o):wd(A,R,t)}break}case"DISCONTINUITY-SEQUENCE":A.startCC!==0?Ri(A,L,y):u.length>0&&Yd(A,L,y),A.startCC=p=parseInt(U);break;case"KEY":{const R=Nd(U,t,A);if(R.isSupported()){if(R.method==="NONE"){w=void 0;break}w||(w={}),w[R.keyFormat]&&(w=qe({},w)),w[R.keyFormat]=R}else Ue.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${U}"`);break}case"START":A.startTimeOffset=Od(U);break;case"MAP":{const R=new ot(U,A);if(C.duration){const _=new Tl(n,l);$d(_,R,i,w),h=_,C.initSegment=h,h.rawProgramDateTime&&!C.rawProgramDateTime&&(C.rawProgramDateTime=h.rawProgramDateTime)}else{const _=C.byteRangeEndOffset;if(_){const k=C.byteRangeStartOffset;O=`${_-k}@${k}`}else O=null;$d(C,R,i,w),h=C,F=!0}h.cc=p;break}case"SERVER-CONTROL":{M&&Ri(A,L,y),M=new ot(U),A.canBlockReload=M.bool("CAN-BLOCK-RELOAD"),A.canSkipUntil=M.optionalFloat("CAN-SKIP-UNTIL",0),A.canSkipDateRanges=A.canSkipUntil>0&&M.bool("CAN-SKIP-DATERANGES"),A.partHoldBack=M.optionalFloat("PART-HOLD-BACK",0),A.holdBack=M.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{A.partTarget&&Ri(A,L,y);const R=new ot(U);A.partTarget=R.decimalFloatingPoint("PART-TARGET");break}case"PART":{let R=A.partList;R||(R=A.partList=[]);const _=f>0?R[R.length-1]:void 0,k=f++,K=new ot(U,A),Y=new Ky(K,C,l,k,_);R.push(Y),C.duration+=Y.duration;break}case"PRELOAD-HINT":{const R=new ot(U,A);A.preloadHint=R;break}case"RENDITION-REPORT":{const R=new ot(U,A);A.renditionReports=A.renditionReports||[],A.renditionReports.push(R);break}default:Ue.warn(`line parsed but not handled: ${y}`);break}}}B&&!B.relurl?(u.pop(),g-=B.duration,A.partList&&(A.fragmentHint=B)):A.partList&&(Hl(C,B,c),C.cc=p,A.fragmentHint=C,w&&Hd(C,w,A)),A.targetduration||(A.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const j=u.length,X=u[0],le=u[j-1];if(g+=A.skippedSegments*A.targetduration,g>0&&j&&le){A.averagetargetduration=g/j;const oe=le.sn;A.endSN=oe!=="initSegment"?oe:0,A.live||(le.endList=!0),X&&A.startCC===void 0&&(A.startCC=X.cc),D>0&&(oB(u,D),X&&c.unshift(X))}else A.endSN=0,A.startCC=0;return A.fragmentHint&&(g+=A.fragmentHint.duration),A.totalduration=g,c.length&&A.dateRangeTagCount&&X&&Pd(c,A),A.endCC=p,A}}function Pd(r,e){const t=r.length,i=r[t-1],n=e.live?1/0:e.totalduration,s=Object.keys(e.dateRanges);for(let o=s.length;o--;){const a=e.dateRanges[s[o]],l=a.startDate.getTime();a.tagAnchor=i.ref;for(let A=t;A--;){const u=sB(e,l,r,A,n);if(u!==-1){a.tagAnchor=e.fragments[u].ref;break}}}}function sB(r,e,t,i,n){const s=t[i];if(s){const a=s.programDateTime;if(e>=a||i===0){var o;const l=(((o=t[i+1])==null?void 0:o.start)||n)-s.start;if(e<=a+l*1e3){const A=t[i].sn-r.startSN,u=r.fragments;if(u.length>t.length){const h=(t[i+1]||u[u.length-1]).sn-r.startSN;for(let d=h;d>A;d--){const f=u[d].programDateTime;if(e>=f&&e<f+u[d].duration*1e3)return d}}return A}}}return-1}function Nd(r,e,t){var i,n;const s=new ot(r,t),o=(i=s.METHOD)!=null?i:"",a=s.URI,l=s.hexadecimalInteger("IV"),A=s.KEYFORMATVERSIONS,u=(n=s.KEYFORMAT)!=null?n:"identity";a&&s.IV&&!l&&Ue.error(`Invalid IV: ${s.IV}`);const c=a?gi.resolve(a,e):"",h=(A||"1").split("/").map(Number).filter(Number.isFinite);return new Hn(o,c,u,h,l)}function Od(r){const t=new ot(r).decimalFloatingPoint("TIME-OFFSET");return de(t)?t:null}function Ud(r,e){let t=(r||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const n=t.filter(s=>rd(s,i));n.length&&(e[`${i}Codec`]=n.map(s=>s.split("/")[0]).join(","),t=t.filter(s=>n.indexOf(s)===-1))}),e.unknownCodecs=t}function Gd(r,e,t){const i=e[t];i&&(r[t]=i)}function oB(r,e){let t=r[e];for(let i=e;i--;){const n=r[i];if(!n)return;n.programDateTime=t.programDateTime-n.duration*1e3,t=n}}function Hl(r,e,t){r.rawProgramDateTime?t.push(r):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime)}function $d(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 Hd(r,e,t){r.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(n=>e[n].isCommonEncryption)&&i.push(r)}function Ri(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function Yd(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Yl(r,e){const t=e.startPTS;if(de(t)){let i=0,n;e.sn>r.sn?(i=t-r.start,n=r):(i=r.start-t,n=e),n.duration!==i&&n.setDuration(i)}else e.sn>r.sn?r.cc===e.cc&&r.minEndPTS?e.setStart(r.start+(r.minEndPTS-r.start)):e.setStart(r.start+r.duration):e.setStart(Math.max(r.start-e.duration,0))}function Vd(r,e,t,i,n,s){i-t<=0&&(Ue.warn("Fragment should have a positive duration",e),i=t+e.duration,s=n+e.duration);let a=t,l=i;const A=e.startPTS,u=e.endPTS;if(de(A)){const p=Math.abs(A-t);de(e.deltaPTS)?e.deltaPTS=Math.max(p,e.deltaPTS):e.deltaPTS=p,a=Math.max(t,A),t=Math.min(t,A),n=Math.min(n,e.startDTS),l=Math.min(i,u),i=Math.max(i,u),s=Math.max(s,e.endDTS)}const c=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=a,e.startDTS=n,e.endPTS=i,e.minEndPTS=l,e.endDTS=s;const h=e.sn;if(!r||h<r.startSN||h>r.endSN)return 0;let d;const f=h-r.startSN,g=r.fragments;for(g[f]=e,d=f;d>0;d--)Yl(g[d],g[d-1]);for(d=f;d<g.length-1;d++)Yl(g[d],g[d+1]);return r.fragmentHint&&Yl(g[g.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,c}function aB(r,e){if(r===e)return;let t=null;const i=r.fragments;for(let l=i.length-1;l>=0;l--){const A=i[l].initSegment;if(A){t=A;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let n;cB(r,e,(l,A,u,c)=>{if(!e.startCC&&A.cc!==l.cc){var h,d;const f=l.cc-A.cc;for(let g=u;g<c.length;g++)c[g].cc+=f;e.startCC=(h=(d=Jd(r,e.startSN-1))==null?void 0:d.cc)!=null?h:c[0].cc,e.endCC=c[c.length-1].cc}de(l.startPTS)&&de(l.endPTS)&&(A.setStart(A.startPTS=l.startPTS),A.startDTS=l.startDTS,A.maxStartPTS=l.maxStartPTS,A.endPTS=l.endPTS,A.endDTS=l.endDTS,A.minEndPTS=l.minEndPTS,A.setDuration(l.endPTS-l.startPTS),A.duration&&(n=A),e.PTSKnown=e.alignedSliding=!0),l.hasStreams&&(A.elementaryStreams=l.elementaryStreams),A.loader=l.loader,l.hasStats&&(A.stats=l.stats),l.initSegment&&(A.initSegment=l.initSegment,t=l.initSegment)});const s=e.fragments,o=e.fragmentHint?s.concat(e.fragmentHint):s;if(t&&o.forEach(l=>{var A;l&&(!l.initSegment||l.initSegment.relurl===((A=t)==null?void 0:A.relurl))&&(l.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=s.some(l=>!l),e.deltaUpdateFailed){Ue.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)s.shift();e.startSN=s[0].sn}else{e.endCC=s[s.length-1].cc,e.canSkipDateRanges&&(e.dateRanges=lB(r.dateRanges,e));const l=r.fragments.filter(A=>A.rawProgramDateTime);if(r.hasProgramDateTime&&!e.hasProgramDateTime)for(let A=1;A<o.length;A++)o[A].programDateTime===null&&Hl(o[A],o[A-1],l);Pd(l,e)}AB(r.partList,e.partList,(l,A)=>{A.elementaryStreams=l.elementaryStreams,A.stats=l.stats}),n?Vd(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):Wd(r,e),s.length&&(e.totalduration=e.edge-s[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;e.requestScheduled===-1&&(e.requestScheduled=r.requestScheduled)}function lB(r,e){const{dateRanges:t,recentlyRemovedDateranges:i}=e,n=qe({},r);i&&i.forEach(a=>{delete n[a]});const o=Object.keys(n).length;return o&&Object.keys(t).forEach(a=>{const l=n[a],A=new Dd(t[a].attr,l);A.isValid?(n[a]=A,l||(A.tagOrder+=o)):Ue.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${rt(t[a].attr)}"`)}),n}function AB(r,e,t){if(r&&e){let i=0;for(let n=0,s=r.length;n<=s;n++){const o=r[n],a=e[n+i];o&&a&&o.index===a.index&&o.fragment.sn===a.fragment.sn?t(o,a):i--}}}function cB(r,e,t){const i=e.skippedSegments,n=Math.max(r.startSN,e.startSN)-e.startSN,s=(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 A=n;A<=s;A++){const u=l[o+A];let c=a[A];if(i&&!c&&u&&(c=e.fragments[A]=u),u&&c){if(t(u,c,A,a),u.url&&u.url!==c.url){e.playlistParsingError=Kd(`media sequence mismatch ${c.sn}:`,r,e,u,c);return}else if(u.cc!==c.cc){e.playlistParsingError=Kd(`discontinuity sequence mismatch (${u.cc}!=${c.cc})`,r,e,u,c);return}}}}function Kd(r,e,t,i,n){return new Error(`${r} ${n.url}
2495
+ Time to underbuffer: ${re.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,k>d){let he=this.findBestLevel(this.hls.levels[d].bitrate,d,k,0,re,1,1);he===-1&&(he=d),this.hls.nextLoadLevel=this.hls.nextAutoLevel=he,this.resetEstimator(this.hls.levels[he].bitrate)}}};p||L>_*2?ie():this.timer=self.setInterval(ie,_*1e3),o.trigger(I.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:s,stats:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new Fy(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.FRAG_LOADING,this.onFragLoading,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.FRAG_LOADING,this.onFragLoading,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(I.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var n;this.fragCurrent=i,this.partCurrent=(n=t.part)!=null?n:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case V.BUFFER_ADD_CODEC_ERROR:case V.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case V.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:n,partCurrent:s}=this;if(i&&n&&i.sn===n.sn&&i.level===n.level){const o=performance.now(),a=s?s.stats:i.stats,l=o-a.loading.start,A=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&A>-1){const c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(c,A),a.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,n){const s=e+i/t,o=n?e+this.lastLevelLoadSec:0;return s+o}onLevelLoaded(e,t){const i=this.hls.config,{loading:n}=t.stats,s=n.end-n.first;de(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const n=i?i.stats:t.stats;if(t.type===Ee.MAIN&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const s=i?i.duration:t.duration,o=this.hls.levels[t.level],a=(o.loaded?o.loaded.bytes:0)+n.loaded,l=(o.loaded?o.loaded.duration:0)+s;o.loaded={bytes:a,duration:l},o.realBitrate=Math.round(8*a/l)}if(t.bitrateTest){const s={stats:n,frag:t,part:i,id:t.type};this.onFragBuffered(I.FRAG_BUFFERED,s),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:n}=t,s=n!=null&&n.stats.loaded?n.stats:i.stats;if(s.aborted||this.ignoreFragment(i))return;const o=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Ee.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,s=this.findBestLevel(i,t,e,0,n,1,1);if(s>-1)return s;const o=this.hls.firstLevel,a=Math.min(Math.max(o,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const s=i&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const o=this.hls.levels;if(o.length>Math.max(e,s)&&o[e].loadError<=o[s].loadError)return e}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:n,config:s,minAutoLevel:o}=i,a=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),A=this.getStarvationDelay();let u=s.abrBandWidthFactor,c=s.abrBandWidthUpFactor;if(A){const p=this.findBestLevel(l,o,n,A,0,u,c);if(p>=0)return this.rebufferNotice=-1,p}let h=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!A){const p=this.bitrateTestDelay;p&&(h=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-p,this.info(`bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),u=c=1)}const d=this.findBestLevel(l,o,n,A,h,u,c);if(this.rebufferNotice!==d&&(this.rebufferNotice=d,this.info(`${A?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`)),d>-1)return d;const f=i.levels[o],g=i.loadLevelObj;return g&&(f==null?void 0:f.bitrate)<g.bitrate?o:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,n,s,o,a){var l;const A=n+s,u=this.lastLoadedFragLevel,c=u===-1?this.hls.firstLevel:u,{fragCurrent:h,partCurrent:d}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:v}=this.hls;if(f.length===1)return 0;const B=f[c],C=!!((l=this.hls.latestLevelDetails)!=null&&l.live),y=p===-1||u===-1;let x,w="SDR",D=(B==null?void 0:B.frameRate)||0;const{audioPreference:F,videoPreference:O}=v,M=this.audioTracksByGroup||(this.audioTracksByGroup=gd(g));let j=-1;if(y){if(this.firstSelection!==-1)return this.firstSelection;const U=this.codecTiers||(this.codecTiers=BC(f,M,t,i)),q=CC(U,w,e,F,O),{codecSet:R,videoRanges:_,minFramerate:k,minBitrate:K,minIndex:Y,preferHDR:ie}=q;j=Y,x=R,w=ie?_[_.length-1]:_[0],D=k,e=Math.max(e,K),this.log(`picked start tier ${rt(q)}`)}else x=B==null?void 0:B.codecSet,w=B==null?void 0:B.videoRange;const X=d?d.duration:h?h.duration:0,le=this.bwEstimator.getEstimateTTFB()/1e3,oe=[];for(let U=i;U>=t;U--){var L;const q=f[U],R=U>c;if(!q)continue;if(v.useMediaCapabilities&&!q.supportedResult&&!q.supportedPromise){const he=navigator.mediaCapabilities;typeof(he==null?void 0:he.decodingInfo)=="function"&&(gC(q,M,w,D,e,F)||uo(q.videoCodec))?(q.supportedPromise=ud(q,M,he),q.supportedPromise.then(fe=>{if(!this.hls)return;q.supportedResult=fe;const _e=this.hls.levels,be=_e.indexOf(q);fe.error?this.warn(`MediaCapabilities decodingInfo error: "${fe.error}" for level ${be} ${rt(fe)}`):fe.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${be} ${rt(fe)}`),be>-1&&_e.length>1&&(this.log(`Removing unsupported level ${be}`),this.hls.removeLevel(be),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))})):q.supportedResult=ld}if((x&&q.codecSet!==x||w&&q.videoRange!==w||R&&D>q.frameRate||!R&&D>0&&D<q.frameRate||q.supportedResult&&!((L=q.supportedResult.decodingInfoResults)!=null&&L[0].smooth))&&(!y||U!==j)){oe.push(U);continue}const _=q.details,k=(d?_==null?void 0:_.partTarget:_==null?void 0:_.averagetargetduration)||X;let K;R?K=a*e:K=o*e;const Y=X&&n>=X*2&&s===0?q.averageBitrate:q.maxBitrate,ie=this.getTimeToLoadFrag(le,K,Y*k,_===void 0);if(K>=Y&&(U===u||q.loadError===0&&q.fragmentError===0)&&(ie<=le||!de(ie)||C&&!this.bitrateTestDelay||ie<A)){const he=this.forcedAutoLevel;return U!==p&&(he===-1||he!==p)&&(oe.length&&this.trace(`Skipped level(s) ${oe.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[oe[0]].codecs}" ${f[oe[0]].videoRange}; not compatible with "${x}" ${w}`),this.info(`switch candidate:${c}->${U} adjustedbw(${Math.round(K)})-bitrate=${Math.round(K-Y)} ttfb:${le.toFixed(1)} avgDuration:${k.toFixed(1)} maxFetchDuration:${A.toFixed(1)} fetchDuration:${ie.toFixed(1)} firstSelection:${y} codecSet:${q.codecSet} videoRange:${q.videoRange} hls.loadLevel:${p}`)),y&&(this.firstSelection=U),U}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}}const Rl={search:function(r,e){let t=0,i=r.length-1,n=null,s=null;for(;t<=i;){n=(t+i)/2|0,s=r[n];const o=e(s);if(o>0)t=n+1;else if(o<0)i=n-1;else return s}return null}};function QC(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!de(e))return null;const i=r[0].programDateTime;if(e<(i||0))return null;const n=r[r.length-1].endProgramDateTime;if(e>=(n||0))return null;t=t||0;for(let s=0;s<r.length;++s){const o=r[s];if(wC(e,t,o))return o}return null}function Br(r,e,t=0,i=0,n=.005){let s=null;if(r){s=e[1+r.sn-e[0].sn]||null;const a=r.endDTS-t;a>0&&a<15e-7&&(t+=15e-7),s&&r.level!==s.level&&s.end<=r.end&&(s=e[2+r.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(s=e[0]);if(s&&((!r||r.level===s.level)&&Ed(t,i,s)===0||_C(s,r,Math.min(n,i))))return s;const o=Rl.search(e,Ed.bind(null,t,i));return o&&(o!==r||!s)?o:s}function _C(r,e,t){if(e&&e.start===0&&e.level<r.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((n,s)=>(s[0]==="INF"&&(n+=parseFloat(s[1])),n),t);return r.start<=i}return!1}function Ed(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 wC(r,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>r}function Id(r,e){return Rl.search(r,t=>t.cc<e?1:t.cc>e?-1:0)}function RC(r,e,t){if(r&&r.startCC<=e&&r.endCC>=e){const i=t.start,n=t.end;let s=r.fragments;if(!t.relurl){const{fragmentHint:o}=r;o&&(s=s.concat(o))}return Rl.search(s,o=>o.cc<e||o.end<=i?1:o.cc>e||o.start>=n?-1:0)}return null}function Io(r){switch(r.details){case V.FRAG_LOAD_TIMEOUT:case V.KEY_LOAD_TIMEOUT:case V.LEVEL_LOAD_TIMEOUT:case V.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function vd(r,e){const t=Io(e);return r.default[`${t?"timeout":"error"}Retry`]}function Dl(r,e){const t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function yd(r){return Ve(Ve({},r),{errorRetry:null,timeoutRetry:null})}function vo(r,e,t,i){if(!r)return!1;const n=i==null?void 0:i.code,s=e<r.maxNumRetry&&(DC(n)||!!t);return r.shouldRetry?r.shouldRetry(r,e,t,i,s):s}function DC(r){return r===0&&navigator.onLine===!1||!!r&&(r<400||r>499)}var Rt={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},ni={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2};class LC extends _i{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(I.ERROR,this.onError,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(I.ERROR,this.onError,this),e.off(I.ERROR,this.onErrorOut,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===Ee.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 n=this.hls,s=t.context;switch(t.details){case V.FRAG_LOAD_ERROR:case V.FRAG_LOAD_TIMEOUT:case V.KEY_LOAD_ERROR:case V.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case V.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=$n();return}case V.FRAG_GAP:case V.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Rt.SendAlternateToPenaltyBox;return}case V.LEVEL_EMPTY_ERROR:case V.LEVEL_PARSING_ERROR:{var o,a;const A=t.parent===Ee.MAIN?t.level:n.loadLevel;t.details===V.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(a=o.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,A):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,A))}return;case V.LEVEL_LOAD_ERROR:case V.LEVEL_LOAD_TIMEOUT:typeof(s==null?void 0:s.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.level));return;case V.AUDIO_TRACK_LOAD_ERROR:case V.AUDIO_TRACK_LOAD_TIMEOUT:case V.SUBTITLE_LOAD_ERROR:case V.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){const A=n.loadLevelObj;if(A&&(s.type===Me.AUDIO_TRACK&&A.hasAudioGroup(s.groupId)||s.type===Me.SUBTITLE_TRACK&&A.hasSubtitleGroup(s.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=Rt.SendAlternateToPenaltyBox,t.errorAction.flags=ni.MoveAllAlternatesMatchingHost;return}}return;case V.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const A=n.loadLevelObj,u=A==null?void 0:A.attrs["HDCP-LEVEL"];u?t.errorAction={action:Rt.SendAlternateToPenaltyBox,flags:ni.MoveAllAlternatesMatchingHDCP,hdcpLevel:u}:this.keySystemError(t)}return;case V.BUFFER_ADD_CODEC_ERROR:case V.REMUX_ALLOC_ERROR:case V.BUFFER_APPEND_ERROR:if(!t.errorAction){var l;t.errorAction=this.getLevelSwitchAction(t,(l=t.level)!=null?l:n.loadLevel)}return;case V.INTERNAL_EXCEPTION:case V.BUFFER_APPENDING_ERROR:case V.BUFFER_FULL_ERROR:case V.LEVEL_SWITCH_ERROR:case V.BUFFER_STALLED_ERROR:case V.BUFFER_SEEK_OVER_HOLE:case V.BUFFER_NUDGE_ON_STALL:t.errorAction=$n();return}t.type===Ie.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,n=vd(i.config.playlistLoadPolicy,e),s=this.playlistError++;if(vo(n,s,Io(e),e.response))return{action:Rt.RetryRequest,flags:ni.None,retryConfig:n,retryCount:s};const a=this.getLevelSwitchAction(e,t);return n&&(a.retryConfig=n,a.retryCount=s),a}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),n=t.levels[i],{fragLoadPolicy:s,keyLoadPolicy:o}=t.config,a=vd(e.details.startsWith("key")?o:s,e),l=t.levels.reduce((u,c)=>u+c.fragmentError,0);if(n&&(e.details!==V.FRAG_GAP&&n.fragmentError++,vo(a,l,Io(e),e.response)))return{action:Rt.RetryRequest,flags:ni.None,retryConfig:a,retryCount:l};const A=this.getLevelSwitchAction(e,i);return a&&(A.retryConfig=a,A.retryCount=l),A}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const n=this.hls.levels[t];if(n){var s,o;const A=e.details;n.loadError++,A===V.BUFFER_APPEND_ERROR&&n.fragmentError++;let u=-1;const{levels:c,loadLevel:h,minAutoLevel:d,maxAutoLevel:f}=i;i.autoLevelEnabled||(i.loadLevel=-1);const g=(s=e.frag)==null?void 0:s.type,v=(g===Ee.AUDIO&&A===V.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(A===V.BUFFER_ADD_CODEC_ERROR||A===V.BUFFER_APPEND_ERROR))&&c.some(({audioCodec:w})=>n.audioCodec!==w),C=e.sourceBufferName==="video"&&(A===V.BUFFER_ADD_CODEC_ERROR||A===V.BUFFER_APPEND_ERROR)&&c.some(({codecSet:w,audioCodec:D})=>n.codecSet!==w&&n.audioCodec===D),{type:y,groupId:x}=(o=e.context)!=null?o:{};for(let w=c.length;w--;){const D=(w+h)%c.length;if(D!==h&&D>=d&&D<=f&&c[D].loadError===0){var a,l;const F=c[D];if(A===V.FRAG_GAP&&g===Ee.MAIN&&e.frag){const O=c[D].details;if(O){const M=Br(e.frag,O.fragments,e.frag.start);if(M!=null&&M.gap)continue}}else{if(y===Me.AUDIO_TRACK&&F.hasAudioGroup(x)||y===Me.SUBTITLE_TRACK&&F.hasSubtitleGroup(x))continue;if(g===Ee.AUDIO&&(a=n.audioGroups)!=null&&a.some(O=>F.hasAudioGroup(O))||g===Ee.SUBTITLE&&(l=n.subtitleGroups)!=null&&l.some(O=>F.hasSubtitleGroup(O))||v&&n.audioCodec===F.audioCodec||!v&&n.audioCodec!==F.audioCodec||C&&n.codecSet===F.codecSet)continue}u=D;break}}if(u>-1&&i.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:Rt.SendAlternateToPenaltyBox,flags:ni.None,nextAutoLevel:u}}return{action:Rt.SendAlternateToPenaltyBox,flags:ni.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case Rt.DoNothing:break;case Rt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==V.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:n,hdcpLevel:s,nextAutoLevel:o}=i;switch(n){case ni.None:this.switchLevel(e,o);break;case ni.MoveAllAlternatesMatchingHDCP:s&&(t.maxHdcpLevel=wl[wl.indexOf(s)-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){if(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,e.details===V.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const i=ad(e.mimeType),n=this.hls.levels;for(let s=n.length;s--;)n[s][`${e.sourceBufferName}Codec`]===i&&this.hls.removeLevel(s)}}}function $n(r){const e={action:Rt.DoNothing,flags:ni.None};return r&&(e.resolved=!0),e}var vt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class kC{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(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.BUFFER_APPENDED,this.onBufferAppended,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.BUFFER_APPENDED,this.onBufferAppended,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.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 n=i.length;n--;){const s=i[n];if(!s)break;const o=s.end;if(s.start<=e&&o!==null&&e<=o)return s}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){const{fragments:n}=this,s=Object.keys(n);for(let o=s.length;o--;){const a=n[s[o]];if((a==null?void 0:a.body.type)===t&&(!i||a.buffered)){const l=a.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,i,n,s){this.timeRanges&&(this.timeRanges[e]=t);const o=(n==null?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(a=>{const l=this.fragments[a];if(!l||o>=l.body.sn)return;if(!l.buffered&&(!l.loaded||s)){l.body.type===i&&this.removeFragment(l.body);return}const A=l.range[e];if(A){if(A.time.length===0){this.removeFragment(l.body);return}A.time.some(u=>{const c=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return c&&this.removeFragment(l.body),c})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const i=e.frag,n=$r(i),s=this.fragments[n];if(!s||s.buffered&&i.gap)return;const o=!i.relurl;Object.keys(t).forEach(a=>{const l=i.elementaryStreams[a];if(!l)return;const A=t[a],u=o||l.partial===!0;s.range[a]=this.getBufferedTimes(i,e.part,u,A)}),s.loaded=null,Object.keys(s.range).length?(s.buffered=!0,(s.body.endList=i.endList||s.body.endList)&&(this.endListFragments[s.body.type]=s),yo(s)||this.removeParts(i.sn-1,i.type)):this.removeFragment(s.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=Cd(i,n=>n.fragment.sn>=e))}fragBuffered(e,t){const i=$r(e);let n=this.fragments[i];!n&&t&&(n=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,n.buffered=!0)}getBufferedTimes(e,t,i,n){const s={time:[],partial:i},o=e.start,a=e.end,l=e.minEndPTS||a,A=e.maxStartPTS||o;for(let u=0;u<n.length;u++){const c=n.start(u)-this.bufferPadding,h=n.end(u)+this.bufferPadding;if(A>=c&&l<=h){s.time.push({startPTS:Math.max(o,n.start(u)),endPTS:Math.min(a,n.end(u))});break}else if(o<h&&a>c){const d=Math.max(o,n.start(u)),f=Math.min(a,n.end(u));f>d&&(s.partial=!0,s.time.push({startPTS:d,endPTS:f}))}else if(a<=c)break}return s}getPartialFragment(e){let t=null,i,n,s,o=0;const{bufferPadding:a,fragments:l}=this;return Object.keys(l).forEach(A=>{const u=l[A];u&&yo(u)&&(n=u.body.start-a,s=u.body.end+a,e>=n&&e<=s&&(i=Math.min(e-n,s-e),o<=i&&(t=u.body,o=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||yo(t))}getState(e){const t=$r(e),i=this.fragments[t];return i?i.buffered?yo(i)?vt.PARTIAL:vt.OK:vt.APPENDING:vt.NOT_LOADED}isTimeBuffered(e,t,i){let n,s;for(let o=0;o<i.length;o++){if(n=i.start(o)-this.bufferPadding,s=i.end(o)+this.bufferPadding,e>=n&&t<=s)return!0;if(t<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const i=t.frag,n=t.part?null:t,s=$r(i);this.fragments[s]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:n,timeRanges:s,type:o}=t;if(i.sn==="initSegment")return;const a=i.type;if(n){let A=this.activePartLists[a];A||(this.activePartLists[a]=A=[]),A.push(n)}this.timeRanges=s;const l=s[o];this.detectEvictedFragments(o,l,a,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=$r(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let n=i.length;n--;){const s=t[i[n]];if((s==null?void 0:s.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,n,s){n&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const a=this.fragments[o];if(!a)return;const l=a.body;l.type!==i||n&&!l.gap||l.start<t&&l.end>e&&(a.buffered||s)&&this.removeFragment(l)})}removeFragment(e){const t=$r(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const n=e.sn;this.activePartLists[e.type]=Cd(i,s=>s.fragment.sn!==n)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e,t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const i=(e=this.hls)==null||(t=e.latestLevelDetails)==null?void 0:t.partList;i&&i.forEach(n=>n.clearElementaryStreamInfo())}}function yo(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 $r(r){return`${r.type}_${r.level}_${r.sn}`}function Cd(r,e){return r.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var er={cbc:0,ctr:1};class MC{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case er.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case er.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function FC(r){const e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?r.slice(0,e-t):r}class PC{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 n=0;n<4;n++)i[n]=t.getUint32(n*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,n=i[0],s=i[1],o=i[2],a=i[3],l=this.invSubMix,A=l[0],u=l[1],c=l[2],h=l[3],d=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)p<128?d[p]=p<<1:d[p]=p<<1^283;for(p=0;p<256;p++){let v=g^g<<1^g<<2^g<<3^g<<4;v=v>>>8^v&255^99,e[f]=v,t[v]=f;const B=d[f],C=d[B],y=d[C];let x=d[v]*257^v*16843008;n[f]=x<<24|x>>>8,s[f]=x<<16|x>>>16,o[f]=x<<8|x>>>24,a[f]=x,x=y*16843009^C*65537^B*257^f*16843008,A[v]=x<<24|x>>>8,u[v]=x<<16|x>>>16,c[v]=x<<8|x>>>24,h[v]=x,f?(f=B^d[d[d[y^B]]],g^=d[d[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,n=0;for(;n<t.length&&i;)i=t[n]===this.key[n],n++;if(i)return;this.key=t;const s=this.keySize=t.length;if(s!==4&&s!==6&&s!==8)throw new Error("Invalid aes key size="+s);const o=this.ksRows=(s+6+1)*4;let a,l;const A=this.keySchedule=new Uint32Array(o),u=this.invKeySchedule=new Uint32Array(o),c=this.sBox,h=this.rcon,d=this.invSubMix,f=d[0],g=d[1],p=d[2],v=d[3];let B,C;for(a=0;a<o;a++){if(a<s){B=A[a]=t[a];continue}C=B,a%s===0?(C=C<<8|C>>>24,C=c[C>>>24]<<24|c[C>>>16&255]<<16|c[C>>>8&255]<<8|c[C&255],C^=h[a/s|0]<<24):s>6&&a%s===4&&(C=c[C>>>24]<<24|c[C>>>16&255]<<16|c[C>>>8&255]<<8|c[C&255]),A[a]=B=(A[a-s]^C)>>>0}for(l=0;l<o;l++)a=o-l,l&3?C=A[a]:C=A[a-4],l<4||a<=4?u[l]=C:u[l]=f[c[C>>>24]]^g[c[C>>>16&255]]^p[c[C>>>8&255]]^v[c[C&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const n=this.keySize+6,s=this.invKeySchedule,o=this.invSBox,a=this.invSubMix,l=a[0],A=a[1],u=a[2],c=a[3],h=this.uint8ArrayToUint32Array_(i);let d=h[0],f=h[1],g=h[2],p=h[3];const v=new Int32Array(e),B=new Int32Array(v.length);let C,y,x,w,D,F,O,M,j,X,le,oe,L,U;const q=this.networkToHostOrderSwap;for(;t<v.length;){for(j=q(v[t]),X=q(v[t+1]),le=q(v[t+2]),oe=q(v[t+3]),D=j^s[0],F=oe^s[1],O=le^s[2],M=X^s[3],L=4,U=1;U<n;U++)C=l[D>>>24]^A[F>>16&255]^u[O>>8&255]^c[M&255]^s[L],y=l[F>>>24]^A[O>>16&255]^u[M>>8&255]^c[D&255]^s[L+1],x=l[O>>>24]^A[M>>16&255]^u[D>>8&255]^c[F&255]^s[L+2],w=l[M>>>24]^A[D>>16&255]^u[F>>8&255]^c[O&255]^s[L+3],D=C,F=y,O=x,M=w,L=L+4;C=o[D>>>24]<<24^o[F>>16&255]<<16^o[O>>8&255]<<8^o[M&255]^s[L],y=o[F>>>24]<<24^o[O>>16&255]<<16^o[M>>8&255]<<8^o[D&255]^s[L+1],x=o[O>>>24]<<24^o[M>>16&255]<<16^o[D>>8&255]<<8^o[F&255]^s[L+2],w=o[M>>>24]<<24^o[D>>16&255]<<16^o[F>>8&255]<<8^o[O&255]^s[L+3],B[t]=q(C^d),B[t+1]=q(w^f),B[t+2]=q(x^g),B[t+3]=q(y^p),d=j,f=X,g=le,p=oe,t=t+4}return B.buffer}}class NC{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){const e=OC(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function OC(r){switch(r){case er.cbc:return"AES-CBC";case er.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${r}`)}}const UC=16;class Ll{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.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?FC(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,n){return this.useSoftware?new Promise((s,o)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,i,n);const l=this.flush();l?s(l.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,n)}softwareDecrypt(e,t,i,n){const{currentIV:s,currentResult:o,remainderData:a}=this;if(n!==er.cbc||t.byteLength!==16)return Ue.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=Jt(a,e),this.remainderData=null);const l=this.getValidChunk(e);if(!l.length)return null;s&&(i=s);let A=this.softwareDecrypter;A||(A=this.softwareDecrypter=new PC),A.expandKey(t);const u=o;return this.currentResult=A.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,i,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,n));this.key=t,this.fastAesKey=new NC(this.subtle,t,n)}return this.fastAesKey.expandKey().then(s=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new MC(this.subtle,new Uint8Array(i),n).decrypt(e.buffer,s)):Promise.reject(new Error("web crypto not initialized"))).catch(s=>(Ue.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(e,t,i,n)))}onWebCryptoError(e,t,i,n){const s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,n);const o=this.flush();if(o)return o.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%UC;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(Ue.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Bd=Math.pow(2,17);class GC{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 wi({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,s=n.fLoader,o=n.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){l(bd(e));return}else e.gap=!1;const A=this.loader=s?new s(n):new o(n),u=Td(e);e.loader=A;const c=yd(n.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Bd};e.stats=A.stats;const d={onSuccess:(f,g,p,v)=>{this.resetLoader(e,A);let B=f.data;p.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(B.slice(0,16)),B=B.slice(16)),a({frag:e,part:null,payload:B,networkDetails:v})},onError:(f,g,p,v)=>{this.resetLoader(e,A),l(new wi({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Ve({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:v}))},onAbort:(f,g,p)=>{this.resetLoader(e,A),l(new wi({type:Ie.NETWORK_ERROR,details:V.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,A),l(new wi({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:p,stats:f}))}};t&&(d.onProgress=(f,g,p,v)=>t({frag:e,part:null,payload:p,networkDetails:v})),A.load(u,h,d)})}loadPart(e,t,i){this.abort();const n=this.config,s=n.fLoader,o=n.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(bd(e,t));return}const A=this.loader=s?new s(n):new o(n),u=Td(e,t);e.loader=A;const c=yd(n.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Bd};t.stats=A.stats,A.load(u,h,{onSuccess:(d,f,g,p)=>{this.resetLoader(e,A),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:d.data,networkDetails:p};i(v),a(v)},onError:(d,f,g,p)=>{this.resetLoader(e,A),l(new wi({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Ve({url:u.url,data:void 0},d),error:new Error(`HTTP Error ${d.code} ${d.text}`),networkDetails:g,stats:p}))},onAbort:(d,f,g)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,A),l(new wi({type:Ie.NETWORK_ERROR,details:V.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:g,stats:d}))},onTimeout:(d,f,g)=>{this.resetLoader(e,A),l(new wi({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:d}))}})})}updateStatsFromPart(e,t){const i=e.stats,n=t.stats,s=n.total;if(i.loaded+=n.loaded,s){const l=Math.round(e.duration/t.duration),A=Math.min(Math.round(i.loaded/s),l),c=(l-A)*Math.round(i.loaded/A);i.total=i.loaded+c}else i.total=Math.max(i.loaded,i.total);const o=i.loading,a=n.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 Td(r,e=null){const t=e||r,i={frag:r,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},n=t.byteRangeStartOffset,s=t.byteRangeEndOffset;if(de(n)&&de(s)){var o;let a=n,l=s;if(r.sn==="initSegment"&&$C((o=r.decryptdata)==null?void 0:o.method)){const A=s-n;A%16&&(l=s+(16-A%16)),n!==0&&(i.resetIV=!0,a=n-16)}i.rangeStart=a,i.rangeEnd=l}return i}function bd(r,e){const t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),i={type:Ie.MEDIA_ERROR,details:V.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(i.part=e),(e||r).stats.aborted=!0,new wi(i)}function $C(r){return r==="AES-128"||r==="AES-256"}class wi extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Sd extends _i{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!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(){}}class kl{constructor(e,t,i,n=0,s=-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=Co(),this.buffering={audio:Co(),video:Co(),audiovideo:Co()},this.level=e,this.sn=t,this.id=i,this.size=n,this.part=s,this.partial=o}}function Co(){return{start:0,executeStart:0,executeEnd:0,end:0}}const xd={length:0,start:()=>0,end:()=>0};class Le{static isBuffered(e,t){if(e){const i=Le.getBuffered(e);for(let n=i.length;n--;)if(t>=i.start(n)&&t<=i.end(n))return!0}return!1}static bufferedRanges(e){if(e){const t=Le.getBuffered(e);return Le.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){const n=Le.bufferedRanges(e);if(n.length)return Le.bufferedInfo(n,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((u,c)=>u.start-c.start||c.end-u.end);let n=-1,s=[];if(i)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(n=u);const c=s.length;if(c){const h=s[c-1].end;e[u].start-h<i?e[u].end>h&&(s[c-1].end=e[u].end):s.push(e[u])}else s.push(e[u])}else s=e;let o=0,a,l=t,A=t;for(let u=0;u<s.length;u++){const c=s[u].start,h=s[u].end;if(n===-1&&t>=c&&t<=h&&(n=u),t+i>=c&&t<h)l=c,A=h,o=A-t;else if(t+i<c){a=c;break}}return{len:o,start:l||0,end:A||0,nextStart:a,buffered:e,bufferedIndex:n}}static getBuffered(e){try{return e.buffered||xd}catch(t){return Ue.log("failed to get media.buffered",t),xd}}}const Qd=/\{\$([a-zA-Z0-9-_]+)\}/g;function _d(r){return Qd.test(r)}function Ml(r,e){if(r.variableList!==null||r.hasVariableRefs){const t=r.variableList;return e.replace(Qd,i=>{const n=i.substring(2,i.length-1),s=t==null?void 0:t[n];return s===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),i):s})}return e}function wd(r,e,t){let i=r.variableList;i||(r.variableList=i={});let n,s;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const o=new self.URL(t).searchParams;if(o.has(n))s=o.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(o){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else n=e.NAME,s=e.VALUE;n in i?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):i[n]=s||""}function HC(r,e,t){const i=e.IMPORT;if(t&&i in t){let n=r.variableList;n||(r.variableList=n={}),n[i]=t[i]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const YC=/^(\d+)x(\d+)$/,Rd=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ot{constructor(e,t){typeof e=="string"&&(e=ot.parseAttrList(e,t)),qe(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}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 n=0;n<t.length/2;n++)i[n]=parseInt(t.slice(n*2,n*2+2),16);return i}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]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((n,s)=>(n[s.toLowerCase()]=!0,n),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=YC.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const n={},s='"';for(Rd.lastIndex=0;(i=Rd.exec(e))!==null;){const o=i[1].trim();let a=i[2];const l=a.indexOf(s)===0&&a.lastIndexOf(s)===a.length-1;let A=!1;if(l)a=a.slice(1,-1);else switch(o){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":A=!0}if(t&&(l||A))a=Ml(t,a);else if(!A&&!l)switch(o){case"CLOSED-CAPTIONS":if(a==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Ue.warn(`${e}: attribute ${o} is missing quotes`)}n[o]=a}return n}}const VC="com.apple.hls.interstitial";function KC(r){return r!=="ID"&&r!=="CLASS"&&r!=="CUE"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function WC(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"||r==="SCTE35-CMD"}class Dd{constructor(e,t,i=0){var n;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(n=t==null?void 0:t.tagOrder)!=null?n:i,t){const s=t.attr;for(const o in s)if(Object.prototype.hasOwnProperty.call(e,o)&&e[o]!==s[o]){Ue.warn(`DATERANGE tag attribute: "${o}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=o;break}e=qe(new ot({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const s=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);de(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(Ue.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(de(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===VC}get isValid(){return!!this.id&&!this._badValueForSameId&&de(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const qC=10;class JC{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.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!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.appliedTimelineOffset=void 0,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.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}get hasProgramDateTime(){return this.fragments.length?de(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||qC}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 fragmentStart(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Hr(r){return r==="AES-128"||r==="AES-256"||r==="AES-256-CTR"}function Fl(r){switch(r){case"AES-128":case"AES-256":return er.cbc;case"AES-256-CTR":return er.ctr;default:throw new Error(`invalid full segment method ${r}`)}}function Pl(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function Nl(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}function jC(r){const e=Nl(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function XC(r){const e=function(i,n,s){const o=i[n];i[n]=i[s],i[s]=o};e(r,0,3),e(r,1,2),e(r,4,5),e(r,6,7)}function zC(r){const e=r.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),n=i[i.length-1].split(",");if(n.length===2){const s=n[0]==="base64",o=n[1];s?(i.splice(-1,1),t=Pl(o)):t=jC(o)}}return t}const Bo=typeof self<"u"?self:void 0;var Ke={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Pt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ol(r){switch(r){case Pt.FAIRPLAY:return Ke.FAIRPLAY;case Pt.PLAYREADY:return Ke.PLAYREADY;case Pt.WIDEVINE:return Ke.WIDEVINE;case Pt.CLEARKEY:return Ke.CLEARKEY}}var To={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Ul(r){if(r===To.WIDEVINE)return Ke.WIDEVINE;if(r===To.PLAYREADY)return Ke.PLAYREADY;if(r===To.CENC||r===To.CLEARKEY)return Ke.CLEARKEY}function Gl(r){switch(r){case Ke.FAIRPLAY:return Pt.FAIRPLAY;case Ke.PLAYREADY:return Pt.PLAYREADY;case Ke.WIDEVINE:return Pt.WIDEVINE;case Ke.CLEARKEY:return Pt.CLEARKEY}}function bo(r){const{drmSystems:e,widevineLicenseUrl:t}=r,i=e?[Ke.FAIRPLAY,Ke.WIDEVINE,Ke.PLAYREADY,Ke.CLEARKEY].filter(n=>!!e[n]):[];return!i[Ke.WIDEVINE]&&t&&i.push(Ke.WIDEVINE),i}const Ld=function(r){return Bo!=null&&(r=Bo.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function ZC(r,e,t,i){let n;switch(r){case Ke.FAIRPLAY:n=["cenc","sinf"];break;case Ke.WIDEVINE:case Ke.PLAYREADY:n=["cenc"];break;case Ke.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return eB(n,e,t,i)}function eB(r,e,t,i){return[{initDataTypes:r,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(s=>({contentType:`audio/mp4; codecs=${s}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(s=>({contentType:`video/mp4; codecs=${s}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function tB(r){var e;return r.sessionType==="persistent-license"||!!((e=r.sessionTypes)!=null&&e.some(t=>t==="persistent-license"))}function kd(r){const e=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.length),o=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(o){const a=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(a){const l=Pl(a).subarray(0,16);return XC(l),l}}return null}let So={};class Hn{static clearKeyUriToKeyIdMap(){So={}}constructor(e,t,i,n=[1],s=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=n,this.iv=s,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Hr(e)}isSupported(){if(this.method){if(Hr(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Pt.FAIRPLAY:case Pt.WIDEVINE:case Pt.PLAYREADY:case Pt.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(Hr(this.method)&&this.uri&&!this.iv){typeof e!="number"&&(Ue.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const i=iB(e);return new Hn(this.method,this.uri,"identity",this.keyFormatVersions,i)}const t=zC(this.uri);if(t)switch(this.keyFormat){case Pt.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Pt.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=aC(i,null,t),this.keyId=kd(t);break}default:{let i=t.subarray(0,16);if(i.length!==16){const n=new Uint8Array(16);n.set(i,16-i.length),i=n}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=So[this.uri];if(!i){const n=Object.keys(So).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,n),So[this.uri]=i}this.keyId=i}return this}}function iB(r){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}const Md=/#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,Fd=/#EXT-X-MEDIA:(.*)/g,rB=/^#EXT(?:INF|-X-TARGETDURATION):/m,$l=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),nB=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class gi{static findGroup(e,t){for(let i=0;i<e.length;i++){const n=e[i];if(n.id===t)return n}}static resolve(e,t){return Cl.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return rB.test(e)}static parseMasterPlaylist(e,t){const i=_d(e),n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},s=[];Md.lastIndex=0;let o;for(;(o=Md.exec(e))!=null;)if(o[1]){var a;const A=new ot(o[1],n),u=Ml(n,o[2]),c={attrs:A,bitrate:A.decimalInteger("BANDWIDTH")||A.decimalInteger("AVERAGE-BANDWIDTH"),name:A.NAME,url:gi.resolve(u,t)},h=A.decimalResolution("RESOLUTION");h&&(c.width=h.width,c.height=h.height),Ud(A.CODECS,c);const d=A["SUPPLEMENTAL-CODECS"];d&&(c.supplemental={},Ud(d,c.supplemental)),(a=c.unknownCodecs)!=null&&a.length||s.push(c),n.levels.push(c)}else if(o[3]){const A=o[3],u=o[4];switch(A){case"SESSION-DATA":{const c=new ot(u,n),h=c["DATA-ID"];h&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[h]=c);break}case"SESSION-KEY":{const c=Nd(u,t,n);c.encrypted&&c.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(c)):Ue.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const c=new ot(u,n);wd(n,c,t)}break}case"CONTENT-STEERING":{const c=new ot(u,n);n.contentSteering={uri:gi.resolve(c["SERVER-URI"],t),pathwayId:c["PATHWAY-ID"]||"."};break}case"START":{n.startTimeOffset=Od(u);break}}}const l=s.length>0&&s.length<n.levels.length;return n.levels=l?s:n.levels,n.levels.length===0&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(e,t,i){let n;const s={},o=i.levels,a={AUDIO:o.map(A=>({id:A.attrs.AUDIO,audioCodec:A.audioCodec})),SUBTITLES:o.map(A=>({id:A.attrs.SUBTITLES,textCodec:A.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Fd.lastIndex=0;(n=Fd.exec(e))!==null;){const A=new ot(n[1],i),u=A.TYPE;if(u){const c=a[u],h=s[u]||[];s[u]=h;const d=A.LANGUAGE,f=A["ASSOC-LANGUAGE"],g=A.CHANNELS,p=A.CHARACTERISTICS,v=A["INSTREAM-ID"],B={attrs:A,bitrate:0,id:l++,groupId:A["GROUP-ID"]||"",name:A.NAME||d||"",type:u,default:A.bool("DEFAULT"),autoselect:A.bool("AUTOSELECT"),forced:A.bool("FORCED"),lang:d,url:A.URI?gi.resolve(A.URI,t):""};if(f&&(B.assocLang=f),g&&(B.channels=g),p&&(B.characteristics=p),v&&(B.instreamId=v),c!=null&&c.length){const C=gi.findGroup(c,B.groupId)||c[0];Gd(B,C,"audioCodec"),Gd(B,C,"textCodec")}h.push(B)}}return s}static parseLevelPlaylist(e,t,i,n,s,o){var a;const l={url:t},A=new JC(t),u=A.fragments,c=[];let h=null,d=0,f=0,g=0,p=0,v=0,B=null,C=new Tl(n,l),y,x,w,D=-1,F=!1,O=null,M;if($l.lastIndex=0,A.m3u8=e,A.hasVariableRefs=_d(e),((a=$l.exec(e))==null?void 0:a[0])!=="#EXTM3U")return A.playlistParsingError=new Error("Missing format identifier #EXTM3U"),A;for(;(y=$l.exec(e))!==null;){F&&(F=!1,C=new Tl(n,l),C.playlistOffset=g,C.start=g,C.sn=d,C.cc=p,v&&(C.bitrate=v),C.level=i,h&&(C.initSegment=h,h.rawProgramDateTime&&(C.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),O&&(C.setByteRange(O),O=null)));const oe=y[1];if(oe){C.duration=parseFloat(oe);const L=(" "+y[2]).slice(1);C.title=L||null,C.tagList.push(L?["INF",oe,L]:["INF",oe])}else if(y[3]){if(de(C.duration)){C.playlistOffset=g,C.start=g,w&&Hd(C,w,A),C.sn=d,C.level=i,C.cc=p,u.push(C);const L=(" "+y[3]).slice(1);C.relurl=Ml(A,L),Hl(C,B,c),B=C,g+=C.duration,d++,f=0,F=!0}}else{if(y=y[0].match(nB),!y){Ue.warn("No matches on slow regex match for level playlist!");continue}for(x=1;x<y.length&&y[x]===void 0;x++);const L=(" "+y[x]).slice(1),U=(" "+y[x+1]).slice(1),q=y[x+2]?(" "+y[x+2]).slice(1):null;switch(L){case"BYTERANGE":B?C.setByteRange(U,B):C.setByteRange(U);break;case"PROGRAM-DATE-TIME":C.rawProgramDateTime=U,C.tagList.push(["PROGRAM-DATE-TIME",U]),D===-1&&(D=u.length);break;case"PLAYLIST-TYPE":A.type&&Ri(A,L,y),A.type=U.toUpperCase();break;case"MEDIA-SEQUENCE":A.startSN!==0?Ri(A,L,y):u.length>0&&Yd(A,L,y),d=A.startSN=parseInt(U);break;case"SKIP":{A.skippedSegments&&Ri(A,L,y);const R=new ot(U,A),_=R.decimalInteger("SKIPPED-SEGMENTS");if(de(_)){A.skippedSegments+=_;for(let K=_;K--;)u.push(null);d+=_}const k=R.enumeratedString("RECENTLY-REMOVED-DATERANGES");k&&(A.recentlyRemovedDateranges=(A.recentlyRemovedDateranges||[]).concat(k.split(" ")));break}case"TARGETDURATION":A.targetduration!==0&&Ri(A,L,y),A.targetduration=Math.max(parseInt(U),1);break;case"VERSION":A.version!==null&&Ri(A,L,y),A.version=parseInt(U);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":A.live||Ri(A,L,y),A.live=!1;break;case"#":(U||q)&&C.tagList.push(q?[U,q]:[U]);break;case"DISCONTINUITY":p++,C.tagList.push(["DIS"]);break;case"GAP":C.gap=!0,C.tagList.push([L]);break;case"BITRATE":C.tagList.push([L,U]),v=parseInt(U)*1e3,de(v)?C.bitrate=v:v=0;break;case"DATERANGE":{const R=new ot(U,A),_=new Dd(R,A.dateRanges[R.ID],A.dateRangeTagCount);A.dateRangeTagCount++,_.isValid||A.skippedSegments?A.dateRanges[_.id]=_:Ue.warn(`Ignoring invalid DATERANGE tag: "${U}"`),C.tagList.push(["EXT-X-DATERANGE",U]);break}case"DEFINE":{{const R=new ot(U,A);"IMPORT"in R?HC(A,R,o):wd(A,R,t)}break}case"DISCONTINUITY-SEQUENCE":A.startCC!==0?Ri(A,L,y):u.length>0&&Yd(A,L,y),A.startCC=p=parseInt(U);break;case"KEY":{const R=Nd(U,t,A);if(R.isSupported()){if(R.method==="NONE"){w=void 0;break}w||(w={}),w[R.keyFormat]&&(w=qe({},w)),w[R.keyFormat]=R}else Ue.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${U}"`);break}case"START":A.startTimeOffset=Od(U);break;case"MAP":{const R=new ot(U,A);if(C.duration){const _=new Tl(n,l);$d(_,R,i,w),h=_,C.initSegment=h,h.rawProgramDateTime&&!C.rawProgramDateTime&&(C.rawProgramDateTime=h.rawProgramDateTime)}else{const _=C.byteRangeEndOffset;if(_){const k=C.byteRangeStartOffset;O=`${_-k}@${k}`}else O=null;$d(C,R,i,w),h=C,F=!0}h.cc=p;break}case"SERVER-CONTROL":{M&&Ri(A,L,y),M=new ot(U),A.canBlockReload=M.bool("CAN-BLOCK-RELOAD"),A.canSkipUntil=M.optionalFloat("CAN-SKIP-UNTIL",0),A.canSkipDateRanges=A.canSkipUntil>0&&M.bool("CAN-SKIP-DATERANGES"),A.partHoldBack=M.optionalFloat("PART-HOLD-BACK",0),A.holdBack=M.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{A.partTarget&&Ri(A,L,y);const R=new ot(U);A.partTarget=R.decimalFloatingPoint("PART-TARGET");break}case"PART":{let R=A.partList;R||(R=A.partList=[]);const _=f>0?R[R.length-1]:void 0,k=f++,K=new ot(U,A),Y=new Ky(K,C,l,k,_);R.push(Y),C.duration+=Y.duration;break}case"PRELOAD-HINT":{const R=new ot(U,A);A.preloadHint=R;break}case"RENDITION-REPORT":{const R=new ot(U,A);A.renditionReports=A.renditionReports||[],A.renditionReports.push(R);break}default:Ue.warn(`line parsed but not handled: ${y}`);break}}}B&&!B.relurl?(u.pop(),g-=B.duration,A.partList&&(A.fragmentHint=B)):A.partList&&(Hl(C,B,c),C.cc=p,A.fragmentHint=C,w&&Hd(C,w,A)),A.targetduration||(A.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const j=u.length,X=u[0],le=u[j-1];if(g+=A.skippedSegments*A.targetduration,g>0&&j&&le){A.averagetargetduration=g/j;const oe=le.sn;A.endSN=oe!=="initSegment"?oe:0,A.live||(le.endList=!0),X&&A.startCC===void 0&&(A.startCC=X.cc),D>0&&(oB(u,D),X&&c.unshift(X))}else A.endSN=0,A.startCC=0;return A.fragmentHint&&(g+=A.fragmentHint.duration),A.totalduration=g,c.length&&A.dateRangeTagCount&&X&&Pd(c,A),A.endCC=p,A}}function Pd(r,e){const t=r.length,i=r[t-1],n=e.live?1/0:e.totalduration,s=Object.keys(e.dateRanges);for(let o=s.length;o--;){const a=e.dateRanges[s[o]],l=a.startDate.getTime();a.tagAnchor=i.ref;for(let A=t;A--;){const u=sB(e,l,r,A,n);if(u!==-1){a.tagAnchor=e.fragments[u].ref;break}}}}function sB(r,e,t,i,n){const s=t[i];if(s){const a=s.programDateTime;if(e>=a||i===0){var o;const l=(((o=t[i+1])==null?void 0:o.start)||n)-s.start;if(e<=a+l*1e3){const A=t[i].sn-r.startSN,u=r.fragments;if(u.length>t.length){const h=(t[i+1]||u[u.length-1]).sn-r.startSN;for(let d=h;d>A;d--){const f=u[d].programDateTime;if(e>=f&&e<f+u[d].duration*1e3)return d}}return A}}}return-1}function Nd(r,e,t){var i,n;const s=new ot(r,t),o=(i=s.METHOD)!=null?i:"",a=s.URI,l=s.hexadecimalInteger("IV"),A=s.KEYFORMATVERSIONS,u=(n=s.KEYFORMAT)!=null?n:"identity";a&&s.IV&&!l&&Ue.error(`Invalid IV: ${s.IV}`);const c=a?gi.resolve(a,e):"",h=(A||"1").split("/").map(Number).filter(Number.isFinite);return new Hn(o,c,u,h,l)}function Od(r){const t=new ot(r).decimalFloatingPoint("TIME-OFFSET");return de(t)?t:null}function Ud(r,e){let t=(r||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const n=t.filter(s=>rd(s,i));n.length&&(e[`${i}Codec`]=n.map(s=>s.split("/")[0]).join(","),t=t.filter(s=>n.indexOf(s)===-1))}),e.unknownCodecs=t}function Gd(r,e,t){const i=e[t];i&&(r[t]=i)}function oB(r,e){let t=r[e];for(let i=e;i--;){const n=r[i];if(!n)return;n.programDateTime=t.programDateTime-n.duration*1e3,t=n}}function Hl(r,e,t){r.rawProgramDateTime?t.push(r):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime)}function $d(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 Hd(r,e,t){r.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(n=>e[n].isCommonEncryption)&&i.push(r)}function Ri(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function Yd(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Yl(r,e){const t=e.startPTS;if(de(t)){let i=0,n;e.sn>r.sn?(i=t-r.start,n=r):(i=r.start-t,n=e),n.duration!==i&&n.setDuration(i)}else e.sn>r.sn?r.cc===e.cc&&r.minEndPTS?e.setStart(r.start+(r.minEndPTS-r.start)):e.setStart(r.start+r.duration):e.setStart(Math.max(r.start-e.duration,0))}function Vd(r,e,t,i,n,s){i-t<=0&&(Ue.warn("Fragment should have a positive duration",e),i=t+e.duration,s=n+e.duration);let a=t,l=i;const A=e.startPTS,u=e.endPTS;if(de(A)){const p=Math.abs(A-t);de(e.deltaPTS)?e.deltaPTS=Math.max(p,e.deltaPTS):e.deltaPTS=p,a=Math.max(t,A),t=Math.min(t,A),n=Math.min(n,e.startDTS),l=Math.min(i,u),i=Math.max(i,u),s=Math.max(s,e.endDTS)}const c=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=a,e.startDTS=n,e.endPTS=i,e.minEndPTS=l,e.endDTS=s;const h=e.sn;if(!r||h<r.startSN||h>r.endSN)return 0;let d;const f=h-r.startSN,g=r.fragments;for(g[f]=e,d=f;d>0;d--)Yl(g[d],g[d-1]);for(d=f;d<g.length-1;d++)Yl(g[d],g[d+1]);return r.fragmentHint&&Yl(g[g.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,c}function aB(r,e){if(r===e)return;let t=null;const i=r.fragments;for(let l=i.length-1;l>=0;l--){const A=i[l].initSegment;if(A){t=A;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let n;cB(r,e,(l,A,u,c)=>{if(!e.startCC&&A.cc!==l.cc){var h,d;const f=l.cc-A.cc;for(let g=u;g<c.length;g++)c[g].cc+=f;e.startCC=(h=(d=Jd(r,e.startSN-1))==null?void 0:d.cc)!=null?h:c[0].cc,e.endCC=c[c.length-1].cc}de(l.startPTS)&&de(l.endPTS)&&(A.setStart(A.startPTS=l.startPTS),A.startDTS=l.startDTS,A.maxStartPTS=l.maxStartPTS,A.endPTS=l.endPTS,A.endDTS=l.endDTS,A.minEndPTS=l.minEndPTS,A.setDuration(l.endPTS-l.startPTS),A.duration&&(n=A),e.PTSKnown=e.alignedSliding=!0),l.hasStreams&&(A.elementaryStreams=l.elementaryStreams),A.loader=l.loader,l.hasStats&&(A.stats=l.stats),l.initSegment&&(A.initSegment=l.initSegment,t=l.initSegment)});const s=e.fragments,o=e.fragmentHint?s.concat(e.fragmentHint):s;if(t&&o.forEach(l=>{var A;l&&(!l.initSegment||l.initSegment.relurl===((A=t)==null?void 0:A.relurl))&&(l.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=s.some(l=>!l),e.deltaUpdateFailed){Ue.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)s.shift();e.startSN=s[0].sn}else{e.endCC=s[s.length-1].cc,e.canSkipDateRanges&&(e.dateRanges=lB(r.dateRanges,e));const l=r.fragments.filter(A=>A.rawProgramDateTime);if(r.hasProgramDateTime&&!e.hasProgramDateTime)for(let A=1;A<o.length;A++)o[A].programDateTime===null&&Hl(o[A],o[A-1],l);Pd(l,e)}AB(r.partList,e.partList,(l,A)=>{A.elementaryStreams=l.elementaryStreams,A.stats=l.stats}),n?Vd(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):Wd(r,e),s.length&&(e.totalduration=e.edge-s[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;e.requestScheduled===-1&&(e.requestScheduled=r.requestScheduled)}function lB(r,e){const{dateRanges:t,recentlyRemovedDateranges:i}=e,n=qe({},r);i&&i.forEach(a=>{delete n[a]});const o=Object.keys(n).length;return o&&Object.keys(t).forEach(a=>{const l=n[a],A=new Dd(t[a].attr,l);A.isValid?(n[a]=A,l||(A.tagOrder+=o)):Ue.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${rt(t[a].attr)}"`)}),n}function AB(r,e,t){if(r&&e){let i=0;for(let n=0,s=r.length;n<=s;n++){const o=r[n],a=e[n+i];o&&a&&o.index===a.index&&o.fragment.sn===a.fragment.sn?t(o,a):i--}}}function cB(r,e,t){const i=e.skippedSegments,n=Math.max(r.startSN,e.startSN)-e.startSN,s=(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 A=n;A<=s;A++){const u=l[o+A];let c=a[A];if(i&&!c&&u&&(c=e.fragments[A]=u),u&&c){if(t(u,c,A,a),u.url&&u.url!==c.url){e.playlistParsingError=Kd(`media sequence mismatch ${c.sn}:`,r,e,u,c);return}else if(u.cc!==c.cc){e.playlistParsingError=Kd(`discontinuity sequence mismatch (${u.cc}!=${c.cc})`,r,e,u,c);return}}}}function Kd(r,e,t,i,n){return new Error(`${r} ${n.url}
2496
2496
  Playlist starting @${e.startSN}
2497
2497
  ${e.m3u8}
2498
2498
 
2499
2499
  Playlist starting @${t.startSN}
2500
- ${t.m3u8}`)}function Wd(r,e,t=!0){const i=e.startSN+e.skippedSegments-r.startSN,n=r.fragments,s=i>=0;let o=0;if(s&&i<n.length)o=n[i].start;else if(s&&e.startSN===r.endSN+1)o=r.fragmentEnd;else if(s&&t)o=r.fragmentStart+i*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=r.fragmentStart;else return;Vl(e,o)}function Vl(r,e){if(e){const t=r.fragments;for(let i=r.skippedSegments;i<t.length;i++)t[i].addStart(e);r.fragmentHint&&r.fragmentHint.addStart(e)}}function qd(r,e=1/0){let t=1e3*r.targetduration;if(r.updated){const i=r.fragments;if(i.length&&t*4>e){const s=i[i.length-1].duration*1e3;s<t&&(t=s)}}else t/=2;return Math.round(t)}function Jd(r,e,t){if(!r)return null;let i=r.fragments[e-r.startSN];return i||(i=r.fragmentHint,i&&i.sn===e)?i:e<r.startSN&&t&&t.sn===e?t:null}function jd(r,e,t){return r?Xd(r.partList,e,t):null}function Xd(r,e,t){if(r)for(let i=r.length;i--;){const n=r[i];if(n.index===t&&n.fragment.sn===e)return n}return null}function zd(r){r.forEach((e,t)=>{var i;(i=e.details)==null||i.fragments.forEach(n=>{n.level=t,n.initSegment&&(n.initSegment.level=t)})})}function Yn(r,e){for(let i=0,n=r.length;i<n;i++){var t;if(((t=r[i])==null?void 0:t.cc)===e)return r[i]}return null}function uB(r,e){return!!(r&&e.startCC<r.endCC&&e.endCC>r.startCC)}function Zd(r,e){if(r){const t=r.start+e;r.start=r.startPTS=t,r.endPTS=t+r.duration}}function ef(r,e){const t=e.fragments;for(let i=0,n=t.length;i<n;i++)Zd(t[i],r);e.fragmentHint&&Zd(e.fragmentHint,r),e.alignedSliding=!0}function hB(r,e){r&&(tf(e,r),!e.alignedSliding&&r&&xo(e,r),!e.alignedSliding&&r&&!e.skippedSegments&&Wd(r,e,!1))}function tf(r,e){if(!uB(e,r))return;const t=Math.min(e.endCC,r.endCC),i=Yn(e.fragments,t),n=Yn(r.fragments,t);if(!i||!n)return;Ue.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const s=i.start-n.start;ef(s,r)}function xo(r,e){if(!r.hasProgramDateTime||!e.hasProgramDateTime)return;const t=r.fragments,i=e.fragments;if(!t.length||!i.length)return;let n,s;const o=Math.min(e.endCC,r.endCC);e.startCC<o&&r.startCC<o&&(n=Yn(i,o),s=Yn(t,o)),(!n||!s)&&(n=i[Math.floor(i.length/2)],s=Yn(t,n.cc)||t[Math.floor(t.length/2)]);const a=n.programDateTime,l=s.programDateTime;if(!a||!l)return;const A=(l-a)/1e3-(s.start-n.start);ef(A,r)}const dB={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}},Z={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 Kl extends Sd{constructor(e,t,i,n,s){super(n,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Z.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.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.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:o,fragCurrent:a,media:l,mediaBuffer:A,state:u}=this,c=l?l.currentTime:0,h=Le.bufferInfo(A||l,c,o.maxBufferHole);if(this.log(`media seeking to ${de(c)?c.toFixed(3):c}, state: ${u}`),this.state===Z.ENDED)this.resetLoadingState();else if(a){const d=o.maxFragLookUpTolerance,f=a.start-d,g=a.start+a.duration+d;if(!h.len||g<h.start||f>h.end){const p=c>g;(c<f||p)&&(p&&a.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),a.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0);const d=this.lastCurrentTime;if(c>d&&(this.lastCurrentTime=c),!this.loadingParts){const f=Math.max(h.end,c),g=this.shouldLoadParts(this.getLevelDetails(),f);g&&(this.log(`LL-Part loading ON after seeking to ${c.toFixed(2)} with buffer @${f.toFixed(2)}`),this.loadingParts=g)}}!this.hls.hasEnoughToStart&&!h.len&&(this.log(`setting startPosition to ${c} because of seek before start`),this.nextLoadPosition=this.startPosition=c),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=s,this.hls=e,this.fragmentLoader=new GC(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ll(e.config)}registerListeners(){const{hls:e}=this;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Z.STOPPED)return;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=Z.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,n=this.config.timelineOffset||0;if(i<=n)return!1;const s=e.nextStart;if(s&&s>n&&s<t.edge||this.media.currentTime<e.start)return!1;const a=t.partList;if(a!=null&&a.length){const A=a[a.length-1];return Le.isBuffered(this.media,A.start+A.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levelLastLoaded)==null?void 0:e.details}}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("ended",this.onMediaEnded),i.addEventListener("seeking",this.onMediaSeeking),i.addEventListener("ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===Z.STOPPED&&this.startLoad(n.startPosition)}onMediaDetaching(e,t){const i=!!t.transferMedia,n=this.media;if(n!==null){if(n.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),n.removeEventListener("seeking",this.onMediaSeeking),n.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Z.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const n=s=>{const o=s.frag;if(this.fragContextChanged(o)){this.warn(`${o.type} sn: ${o.sn}${s.part?" part: "+s.part.index:""} of ${this.fragInfo(o,!1,s.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(o);return}o.stats.chunkCount++,this._handleFragmentLoadProgress(s)};this._doFragLoad(e,t,i,n).then(s=>{if(!s)return;const o=this.state,a=s.frag;if(this.fragContextChanged(a)){(o===Z.FRAG_LOADING||!this.fragCurrent&&o===Z.PARSING)&&(this.fragmentTracker.removeFragment(a),this.state=Z.IDLE);return}"payload"in s&&(this.log(`Loaded ${a.type} sn: ${a.sn} of ${this.playlistLabel()} ${a.level}`),this.hls.trigger(I.FRAG_LOADED,s)),this._handleFragmentLoadComplete(s)}).catch(s=>{this.state===Z.STOPPED||this.state===Z.ERROR||(this.warn(`Frag error: ${(s==null?void 0:s.message)||s}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===vt.APPENDING){const s=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,s),a=Math.max(e.duration,o?o.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(a,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===vt.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:i};this.hls.trigger(I.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{const n=i==null?void 0:i.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:n}=this,{frag:s,payload:o}=i,a=s.decryptdata;if(o&&o.byteLength>0&&a!=null&&a.key&&a.iv&&Hr(a.method)){const l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(o),a.key.buffer,a.iv.buffer,Fl(a.method)).catch(A=>{throw n.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_DECRYPT_ERROR,fatal:!1,error:A,reason:A.message,frag:s}),A}).then(A=>{const u=self.performance.now();return n.trigger(I.FRAG_DECRYPTED,{frag:s,payload:A,stats:{tstart:l,tdecrypt:u}}),i.payload=A,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===Z.STOPPED||this.state===Z.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==Z.STOPPED&&(this.state=Z.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?dB.toString(Le.getBuffered(i)):"(detached)"})`),Ct(e)){var n;if(e.type!==Ee.SUBTITLE){const o=e.elementaryStreams;if(!Object.keys(o).some(a=>!!o[a])){this.state=Z.IDLE;return}}const s=(n=this.levels)==null?void 0:n[e.level];s!=null&&s.fragmentError&&(this.log(`Resetting level fragment error count of ${s.fragmentError} on frag buffered`),s.fragmentError=0)}this.state=Z.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:n,partsLoaded:s}=e,o=!s||s.length===0||s.some(l=>!l),a=new kl(i.level,i.sn,i.stats.chunkCount+1,0,n?n.index:-1,!o);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,n){var s;this.fragCurrent=e;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;e.encrypted&&!((s=e.decryptdata)!=null&&s.key)?(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Z.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then(c=>{if(!this.fragContextChanged(c.frag))return this.hls.trigger(I.KEY_LOADED,c),this.state===Z.KEY_LOADING&&(this.state=Z.IDLE),c}),this.hls.trigger(I.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);const l=this.fragPrevious;if(Ct(e)&&(!l||e.sn!==l.sn)){const c=this.shouldLoadParts(t.details,e.end);c!==this.loadingParts&&(this.log(`LL-Part loading ${c?"ON":"OFF"} loading sn ${l==null?void 0:l.sn}->${e.sn}`),this.loadingParts=c)}if(i=Math.max(e.start,i||0),this.loadingParts&&Ct(e)){const c=o.partList;if(c&&n){i>e.end&&o.fragmentHint&&(e=o.fragmentHint);const h=this.getNextPart(c,e,i);if(h>-1){const d=c[h];e=this.fragCurrent=d.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${d.index} (${h}/${c.length-1}) of ${this.fragInfo(e,!1,d)}) cc: ${e.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=d.start+d.duration,this.state=Z.FRAG_LOADING;let f;return a?f=a.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,d,t,n)).catch(g=>this.handleFragLoadError(g)):f=this.doFragPartsLoad(e,d,t,n).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(I.FRAG_LOADING,{frag:e,part:d,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(c,i))return Promise.resolve(null)}}if(Ct(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${o?"["+o.startSN+"-"+o.endSN+"]":""}, target: ${parseFloat(i.toFixed(3))}`),de(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Z.FRAG_LOADING;const A=this.config.progressive;let u;return A&&a?u=a.then(c=>!c||this.fragContextChanged(c==null?void 0:c.frag)?null:this.fragmentLoader.load(e,n)).catch(c=>this.handleFragLoadError(c)):u=Promise.all([this.fragmentLoader.load(e,A?n:void 0),a]).then(([c])=>(!A&&c&&n&&n(c),c)).catch(c=>this.handleFragLoadError(c)),this.hls.trigger(I.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,i,n){return new Promise((s,o)=>{var a;const l=[],A=(a=i.details)==null?void 0:a.partList,u=c=>{this.fragmentLoader.loadPart(e,c,n).then(h=>{l[c.index]=h;const d=h.part;this.hls.trigger(I.FRAG_LOADED,h);const f=jd(i.details,e.sn,c.index+1)||Xd(A,e.sn,c.index+1);if(f)u(f);else return s({frag:e,part:d,partsLoaded:l})}).catch(o)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===V.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(I.ERROR,t)}else this.hls.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Z.PARSING){!this.fragCurrent&&this.state!==Z.STOPPED&&this.state!==Z.ERROR&&(this.state=Z.IDLE);return}const{frag:i,part:n,level:s}=t,o=self.performance.now();i.stats.parsing.end=o,n&&(n.stats.parsing.end=o);const a=this.getLevelDetails(),A=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);A!==this.loadingParts&&(this.log(`LL-Part loading ${A?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=A),this.updateLevelTiming(i,n,s,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e!=null&&e.partList){var i;const s=e.partList[0],o=s.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=o){var n;if((this.hls.hasEnoughToStart?((n=this.media)==null?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:n,sn:s,part:o}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const a=t[n],l=a.details,A=o>-1?jd(l,s,o):null,u=A?A.fragment:Jd(l,s,i);return u?(i&&i!==u&&(u.stats=i.stats),{frag:u,part:A,level:a}):null}bufferFragmentData(e,t,i,n,s){var o;if(!e||this.state!==Z.PARSING)return;const{data1:a,data2:l}=e;let A=a;if(a&&l&&(A=Jt(a,l)),!((o=A)!=null&&o.length))return;const u={type:e.type,frag:t,part:i,chunkMeta:n,parent:t.type,data:A};if(this.hls.trigger(I.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Le.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,n=Le.bufferInfo(t,i,0),s=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,s*.25),a=Math.max(Math.min(e.start-o,n.end-o),i+o);e.start-a>o&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var i;const n=this.getLoadPosition();if(!de(n))return null;const o=this.lastCurrentTime>n||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,o)}getFwdBufferInfoAtPos(e,t,i,n){const s=Le.bufferInfo(e,t,n);if(s.len===0&&s.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(t,i);if(o&&(s.nextStart<=o.end||o.gap)){const a=Math.max(Math.min(s.nextStart,o.end)-t,n);return Le.bufferInfo(e,t,a)}}return s}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,t){const i=this.config,n=Math.max(Math.min(e-t,i.maxBufferLength),t),s=Math.max(e-t*3,i.maxMaxBufferLength/2,n);return s>=n?(i.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0):!1}getAppendedFrag(e,t=Ee.MAIN){var i;const n=(i=this.fragmentTracker)==null?void 0:i.getAppendedFrag(e,t);return n&&"fragment"in n?n.fragment:n}getNextFragment(e,t){const i=t.fragments,n=i.length;if(!n)return null;const{config:s}=this,o=i[0].start,a=s.lowLatencyMode&&!!t.partList;let l=null;if(t.live){const c=s.initialLiveManifestSize;if(n<c)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${c})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<o){var A;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(t,i);const h=this.hls.startPosition,d=this.hls.liveSyncPosition,f=l?(h!==-1&&h>=o?h:d)||l.start:e;this.log(`Setting startPosition to ${f} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${d} frag.start: ${(A=l)==null?void 0:A.start}`),this.startPosition=this.nextLoadPosition=f}}else e<=o&&(l=i[0]);if(!l){const c=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,c,t)}let u=this.filterReplacedPrimary(l,t);if(!u&&l){const c=l.sn-t.startSN;u=this.filterReplacedPrimary(i[c+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===vt.OK||i===vt.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,n,s){let o=null;if(e.gap&&(o=this.getNextFragment(this.nextLoadPosition,t),o&&!o.gap&&i.nextStart)){const a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,n,0);if(a!==null&&i.len+a.len>=s){const l=o.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,o}get primaryPrefetch(){if(rf(this.hls.config)){var e,t;if((e=this.hls.interstitialsManager)==null||(t=e.playingItem)==null?void 0:t.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(rf(this.hls.config)&&e.type!==Ee.SUBTITLE){const i=this.hls.interstitialsManager,n=i==null?void 0:i.bufferingItem;if(n){const o=n.event;if(o){if(o.appendInPlace||Math.abs(e.start-n.start)>1||n.start===0)return null}else if(e.end<=n.start&&(t==null?void 0:t.live)===!1||e.start>n.end&&n.nextEvent&&(n.nextEvent.appendInPlace||e.start-n.end>1))return null}const s=i==null?void 0:i.playerQueue;if(s)for(let o=s.length;o--;){const a=s[o].interstitial;if(a.appendInPlace&&e.start>=a.startTime&&e.end<=a.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let n=-1,s=!1,o=!0;for(let a=0,l=e.length;a<l;a++){const A=e[a];if(o=o&&!A.independent,n>-1&&i<A.start)break;const u=A.loaded;u?n=-1:(s||A.independent||o)&&A.fragment===t&&(n=a),s=u}return n}loadedEndOfParts(e,t){const i=e[e.length-1];return i&&t>i.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let n=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),n=QC(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const s=i.sn+1;if(s>=e.startSN&&s<=e.endSN){const o=t[s-e.startSN];i.cc===o.cc&&(n=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=Id(t,i.cc),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const s=this.hls.liveSyncPosition;s!==null&&(n=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,i){const{config:n}=this;let{fragPrevious:s}=this,{fragments:o,endSN:a}=i;const{fragmentHint:l}=i,{maxFragLookUpTolerance:A}=n,u=i.partList,c=!!(this.loadingParts&&u!=null&&u.length&&l);c&&l&&!this.bitrateTest&&u[u.length-1].fragment.sn===l.sn&&(o=o.concat(l),a=l.sn);let h;if(e<t){var d;const g=e<this.lastCurrentTime||e>t-A||(d=this.media)!=null&&d.paused||!this.startFragRequested?0:A;h=Br(s,o,e,g)}else h=o[o.length-1];if(h){const f=h.sn-i.startSN,g=this.fragmentTracker.getState(h);if((g===vt.OK||g===vt.PARTIAL&&h.gap)&&(s=h),s&&h.sn===s.sn&&(!c||u[0].fragment.sn>h.sn||!i.live&&!c)&&s&&h.level===s.level){const v=o[f+1];h.sn<a&&this.fragmentTracker.getState(v)!==vt.OK?h=v:h=null}}return h}alignPlaylists(e,t,i){const n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const s=e.fragmentStart,o=!t,a=e.alignedSliding&&de(s);if(o||!a&&!s){hB(i,e);const l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${n}`),l}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);const n=this.timelineOffset;if(i===-1){const s=this.startTimeOffset!==null,o=s?this.startTimeOffset:e.startTimeOffset;o!==null&&de(o)?(i=t+o,o<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${o} found in ${s?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+n}this.nextLoadPosition=i+n}getLoadPosition(){var e;const{media:t}=this;let i=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ct(e)&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==Z.FRAG_LOADING_WAITING_RETRY)&&(this.state=Z.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const f=this.getCurrentContext(t.chunkMeta);f&&(t.frag=f.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var n;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}const s=t.details===V.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction,{action:a,flags:l,retryCount:A=0,retryConfig:u}=o||{},c=!!o&&!!u,h=c&&a===wt.RetryRequest,d=c&&!o.resolved&&l===ni.MoveAllAlternatesMatchingHost;if(!h&&d&&Ct(i)&&!i.endList)this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((h||d)&&A<u.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const f=Dl(u,A);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${A+1}/${u.maxNumRetry} in ${f}ms`),o.resolved=!0,this.retryDate=self.performance.now()+f,this.state=Z.FRAG_LOADING_WAITING_RETRY}else if(u&&o)if(this.resetFragmentErrors(e),A<u.maxNumRetry)!s&&a!==wt.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${A})`);return}else a===wt.SendAlternateToPenaltyBox?this.state=Z.WAITING_LEVEL:this.state=Z.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===Z.PARSING||this.state===Z.PARSED){const t=e.frag,i=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,i),s=n&&n.len>.5;s&&this.reduceMaxBufferLength(n.len,(t==null?void 0:t.duration)||10);const o=!s;return o&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),o}return!1}resetFragmentErrors(e){e===Ee.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Z.STOPPED&&(this.state=Z.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const n=Le.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,i),this.state===Z.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Z.STOPPED&&(this.state=Z.IDLE)}resetStartWhenNotLoaded(e){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of ${this.playlistLabel()} ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,n){const s=i.details;if(!s){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,A)=>{const u=e.elementaryStreams[A];if(u){const c=u.endPTS-u.startPTS;if(c<=0)return this.warn(`Could not parse fragment ${e.sn} ${A} duration reliably (${c})`),l||!1;const h=n?0:Vd(s,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS);return this.hls.trigger(I.LEVEL_PTS_UPDATED,{details:s,level:i,drift:h,type:A,frag:e,start:u.startPTS,end:u.endPTS}),!0}return l},!1)){var a;if(i.fragmentError===0&&this.treatAsGap(e,i),((a=this.transmuxer)==null?void 0:a.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Z.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(I.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===Ee.MAIN?"level":"track"}fragInfo(e,t=!0,i){var n,s;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((n=t&&!i?e.startPTS:(i||e).start)!=null?n:NaN).toFixed(3)}-${((s=t&&!i?e.endPTS:(i||e).end)!=null?s:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function rf(r){return!!r.interstitialsController&&r.enableInterstitialPlayback!==!1}class nf{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=fB(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function fB(r,e){const t=new Uint8Array(e);let i=0;for(let n=0;n<r.length;n++){const s=r[n];t.set(s,i),i+=s.length}return t}var Wl={exports:{}},sf;function gB(){return sf||(sf=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function n(l,A,u){this.fn=l,this.context=A,this.once=u||!1}function s(l,A,u,c,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var d=new n(u,c||l,h),f=t?t+A:A;return l._events[f]?l._events[f].fn?l._events[f]=[l._events[f],d]:l._events[f].push(d):(l._events[f]=d,l._eventsCount++),l}function o(l,A){--l._eventsCount===0?l._events=new i:delete l._events[A]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var A=[],u,c;if(this._eventsCount===0)return A;for(c in u=this._events)e.call(u,c)&&A.push(t?c.slice(1):c);return Object.getOwnPropertySymbols?A.concat(Object.getOwnPropertySymbols(u)):A},a.prototype.listeners=function(A){var u=t?t+A:A,c=this._events[u];if(!c)return[];if(c.fn)return[c.fn];for(var h=0,d=c.length,f=new Array(d);h<d;h++)f[h]=c[h].fn;return f},a.prototype.listenerCount=function(A){var u=t?t+A:A,c=this._events[u];return c?c.fn?1:c.length:0},a.prototype.emit=function(A,u,c,h,d,f){var g=t?t+A:A;if(!this._events[g])return!1;var p=this._events[g],v=arguments.length,B,C;if(p.fn){switch(p.once&&this.removeListener(A,p.fn,void 0,!0),v){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,u),!0;case 3:return p.fn.call(p.context,u,c),!0;case 4:return p.fn.call(p.context,u,c,h),!0;case 5:return p.fn.call(p.context,u,c,h,d),!0;case 6:return p.fn.call(p.context,u,c,h,d,f),!0}for(C=1,B=new Array(v-1);C<v;C++)B[C-1]=arguments[C];p.fn.apply(p.context,B)}else{var y=p.length,x;for(C=0;C<y;C++)switch(p[C].once&&this.removeListener(A,p[C].fn,void 0,!0),v){case 1:p[C].fn.call(p[C].context);break;case 2:p[C].fn.call(p[C].context,u);break;case 3:p[C].fn.call(p[C].context,u,c);break;case 4:p[C].fn.call(p[C].context,u,c,h);break;default:if(!B)for(x=1,B=new Array(v-1);x<v;x++)B[x-1]=arguments[x];p[C].fn.apply(p[C].context,B)}}return!0},a.prototype.on=function(A,u,c){return s(this,A,u,c,!1)},a.prototype.once=function(A,u,c){return s(this,A,u,c,!0)},a.prototype.removeListener=function(A,u,c,h){var d=t?t+A:A;if(!this._events[d])return this;if(!u)return o(this,d),this;var f=this._events[d];if(f.fn)f.fn===u&&(!h||f.once)&&(!c||f.context===c)&&o(this,d);else{for(var g=0,p=[],v=f.length;g<v;g++)(f[g].fn!==u||h&&!f[g].once||c&&f[g].context!==c)&&p.push(f[g]);p.length?this._events[d]=p.length===1?p[0]:p:o(this,d)}return this},a.prototype.removeAllListeners=function(A){var u;return A?(u=t?t+A:A,this._events[u]&&o(this,u)):(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}(Wl)),Wl.exports}var pB=gB(),ql=Yy(pB);const Vn="1.6.2",Yr={};function mB(){return typeof __HLS_WORKER_BUNDLE__=="function"}function EB(){const r=Yr[Vn];if(r)return r.clientCount++,r;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),n={worker:new self.Worker(t),objectURL:t,clientCount:1};return Yr[Vn]=n,n}function IB(r){const e=Yr[r];if(e)return e.clientCount++,e;const t=new self.URL(r,self.location.href).href,n={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Yr[r]=n,n}function vB(r){const e=Yr[r||Vn];if(e&&e.clientCount--===1){const{worker:i,objectURL:n}=e;delete Yr[r||Vn],n&&self.URL.revokeObjectURL(n),i.terminate()}}function of(r,e){return 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}function Jl(r,e){return 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}function Qo(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}function Kn(r,e){const t=e;let i=0;for(;Jl(r,e);){i+=10;const n=Qo(r,e+6);i+=n,of(r,e+10)&&(i+=10),e+=i}if(i>0)return r.subarray(t,t+i)}function yB(r,e,t,i){const n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],s=e[t+2],o=s>>2&15;if(o>12){const d=new Error(`invalid ADTS sampling index:${o}`);r.emit(I.ERROR,I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!0,error:d,reason:d.message});return}const a=(s>>6&3)+1,l=e[t+3]>>6&3|(s&1)<<2,A="mp4a.40."+a,u=n[o];let c=o;(a===5||a===29)&&(c-=3);const h=[a<<3|(c&14)>>1,(c&1)<<7|l<<3];return Ue.log(`manifest codec:${i}, parsed codec:${A}, channels:${l}, rate:${u} (ADTS object type:${a} sampling index:${o})`),{config:h,samplerate:u,channelCount:l,codec:A,parsedCodec:A,manifestCodec:i}}function af(r,e){return r[e]===255&&(r[e+1]&246)===240}function lf(r,e){return r[e+1]&1?7:9}function jl(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function CB(r,e){return e+5<r.length}function _o(r,e){return e+1<r.length&&af(r,e)}function BB(r,e){return CB(r,e)&&af(r,e)&&jl(r,e)<=r.length-e}function TB(r,e){if(_o(r,e)){const t=lf(r,e);if(e+t>=r.length)return!1;const i=jl(r,e);if(i<=t)return!1;const n=e+i;return n===r.length||_o(r,n)}return!1}function Af(r,e,t,i,n){if(!r.samplerate){const s=yB(e,t,i,n);if(!s)return;qe(r,s)}}function cf(r){return 9216e4/r}function bB(r,e){const t=lf(r,e);if(e+t<=r.length){const i=jl(r,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function uf(r,e,t,i,n){const s=cf(r.samplerate),o=i+n*s,a=bB(e,t);let l;if(a){const{frameLength:c,headerLength:h}=a,d=h+c,f=Math.max(0,t+d-e.length);f?(l=new Uint8Array(d-h),l.set(e.subarray(t+h,e.length),0)):l=e.subarray(t+h,t+d);const g={unit:l,pts:o};return f||r.samples.push(g),{sample:g,length:d,missing:f}}const A=e.length-t;return l=new Uint8Array(A),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:o},length:A,missing:-1}}function SB(r,e){return Jl(r,e)&&Qo(r,e+6)+10<=r.length-e}function xB(r){if(r.size<2)return;const e=$t(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}}function QB(r){if(r.size<2)return;if(r.type==="TXXX"){let t=1;const i=$t(r.data.subarray(t),!0);t+=i.length+1;const n=$t(r.data.subarray(t));return{key:r.type,info:i,data:n}}const e=$t(r.data.subarray(1));return{key:r.type,info:"",data:e}}function _B(r){if(r.type==="WXXX"){if(r.size<2)return;let t=1;const i=$t(r.data.subarray(t),!0);t+=i.length+1;const n=$t(r.data.subarray(t));return{key:r.type,info:i,data:n}}const e=$t(r.data);return{key:r.type,info:"",data:e}}function wB(r){return btoa(String.fromCharCode(...r))}function hf(r,e){if(r<0)return-hf(-r,e);const t=Math.pow(10,e);if(Math.abs(r*t%1-.5)<Number.EPSILON){const n=Math.floor(r*t);return(n%2===0?n:n+1)/t}else return Math.round(r*t)/t}function RB(r,e){const t=new URL(r),i=new URL(e);if(t.origin!==i.origin)return r;const n=t.pathname.split("/").slice(1),s=i.pathname.split("/").slice(1,-1);for(;n[0]===s[0];)n.shift(),s.shift();for(;s.length;)s.shift(),n.unshift("..");return n.join("/")}function DB(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const s=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(n=="x"?s:s&3|8).toString(16)})}}}function LB(r){return r instanceof ArrayBuffer?r:r.byteOffset==0&&r.byteLength==r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer}function Xl(r,e=0,t=1/0){return kB(r,e,t,Uint8Array)}function kB(r,e,t,i){const n=MB(r);let s=1;"BYTES_PER_ELEMENT"in i&&(s=i.BYTES_PER_ELEMENT);const o=FB(r)?r.byteOffset:0,a=(o+r.byteLength)/s,l=(o+e)/s,A=Math.floor(Math.max(0,Math.min(l,a))),u=Math.floor(Math.min(A+Math.max(t,0),a));return new i(n,A,u-A)}function MB(r){return r instanceof ArrayBuffer?r:r.buffer}function FB(r){return r&&r.buffer instanceof ArrayBuffer&&r.byteLength!==void 0&&r.byteOffset!==void 0}function PB(r){const e={key:r.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(r.size<2)return;if(r.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const i=r.data.subarray(1).indexOf(0);if(i===-1)return;const n=$t(Xl(r.data,1,i)),s=r.data[2+i],o=r.data.subarray(3+i).indexOf(0);if(o===-1)return;const a=$t(Xl(r.data,3+i,o));let l;return n==="-->"?l=$t(Xl(r.data,4+i+o)):l=LB(r.data.subarray(4+i+o)),e.mimeType=n,e.pictureType=s,e.description=a,e.data=l,e}function NB(r){return r.type==="PRIV"?xB(r):r.type[0]==="W"?_B(r):r.type==="APIC"?PB(r):QB(r)}function OB(r){const e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=Qo(r,4),i=10;return{type:e,size:t,data:r.subarray(i,i+t)}}const wo=10,UB=10;function df(r){let e=0;const t=[];for(;Jl(r,e);){const i=Qo(r,e+6);r[e+5]>>6&1&&(e+=wo),e+=wo;const n=e+i;for(;e+UB<n;){const s=OB(r.subarray(e)),o=NB(s);o&&t.push(o),e+=s.size+wo}of(r,e)&&(e+=wo)}return t}function ff(r){return r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp"}function GB(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)}}function zl(r){const e=df(r);for(let t=0;t<e.length;t++){const i=e[t];if(ff(i))return GB(i)}}let Ht=function(r){return r.audioId3="org.id3",r.dateRange="com.apple.quicktime.HLS",r.emsg="https://aomedia.org/emsg/ID3",r.misbklv="urn:misb:KLV:bin:1910.1",r}({});function pi(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Zl{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,n){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=Jt(this.cachedData,e),this.cachedData=null);let i=Kn(e,0),n=i?i.length:0,s;const o=this._audioTrack,a=this._id3Track,l=i?zl(i):void 0,A=e.length;for((this.basePTS===null||this.frameIndex===0&&de(l))&&(this.basePTS=$B(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:Ht.audioId3,duration:Number.POSITIVE_INFINITY});n<A;){if(this.canParse(e,n)){const u=this.appendFrame(o,e,n);u?(this.frameIndex++,this.lastPTS=u.sample.pts,n+=u.length,s=n):n=A}else SB(e,n)?(i=Kn(e,n),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Ht.audioId3,duration:Number.POSITIVE_INFINITY}),n+=i.length,s=n):n++;if(n===A&&s!==A){const u=e.slice(s);this.cachedData?this.cachedData=Jt(this.cachedData,u):this.cachedData=u}}return{audioTrack:o,videoTrack:pi(),id3Track:a,textTrack:pi()}}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:pi(),id3Track:this._id3Track,textTrack:pi()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const $B=(r,e,t)=>{if(de(r))return r*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};let Ro=null;const HB=[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],YB=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],VB=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],KB=[0,1,1,4];function gf(r,e,t,i,n){if(t+24>e.length)return;const s=pf(e,t);if(s&&t+s.frameLength<=e.length){const o=s.samplesPerFrame*9e4/s.sampleRate,a=i+n*o,l={unit:e.subarray(t,t+s.frameLength),pts:a,dts:a};return r.config=[],r.channelCount=s.channelCount,r.samplerate=s.sampleRate,r.samples.push(l),{sample:l,length:s.frameLength,missing:0}}}function pf(r,e){const t=r[e+1]>>3&3,i=r[e+1]>>1&3,n=r[e+2]>>4&15,s=r[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&s!==3){const o=r[e+2]>>1&1,a=r[e+3]>>6,l=t===3?3-i:i===3?3:4,A=HB[l*14+n-1]*1e3,c=YB[(t===3?0:t===2?1:2)*3+s],h=a===3?1:2,d=VB[t][i],f=KB[i],g=d*8*f,p=Math.floor(d*A/c+o)*f;if(Ro===null){const C=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ro=C?parseInt(C[1]):0}return!!Ro&&Ro<=87&&i===2&&A>=224e3&&a===0&&(r[e+3]=r[e+3]|128),{sampleRate:c,channelCount:h,frameLength:p,samplesPerFrame:g}}}function eA(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function mf(r,e){return e+1<r.length&&eA(r,e)}function WB(r,e){return eA(r,e)&&4<=r.length-e}function Ef(r,e){if(e+1<r.length&&eA(r,e)){const i=pf(r,e);let n=4;i!=null&&i.frameLength&&(n=i.frameLength);const s=e+n;return s===r.length||mf(r,s)}return!1}class qB extends Zl{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const i=Kn(e,0);let n=(i==null?void 0:i.length)||0;if(Ef(e,n))return!1;for(let s=e.length;n<s;n++)if(TB(e,n))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return BB(e,t)}appendFrame(e,t,i){Af(e,this.observer,t,i,e.manifestCodec);const n=uf(e,t,i,this.basePTS,this.frameIndex);if(n&&n.missing===0)return n}}const If=(r,e)=>{let t=0,i=5;e+=i;const n=new Uint32Array(1),s=new Uint32Array(1),o=new Uint8Array(1);for(;i>0;){o[0]=r[e];const a=Math.min(i,8),l=8-a;s[0]=4278190080>>>24+l<<l,n[0]=(o[0]&s[0])>>l,t=t?t<<a|n[0]:n[0],e+=1,i-=a}return t};class JB extends Zl{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const n=vf(e,t,i,this.basePTS,this.frameIndex);if(n!==-1)return{sample:e.samples[e.samples.length-1],length:n,missing:0}}static probe(e){if(!e)return!1;const t=Kn(e,0);if(!t)return!1;const i=t.length;return e[i]===11&&e[i+1]===119&&zl(t)!==void 0&&If(e,i)<16}}function vf(r,e,t,i,n){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const s=e[t+4]>>6;if(s>=3)return-1;const a=[48e3,44100,32e3][s],l=e[t+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+s]*2;if(t+u>e.length)return-1;const c=e[t+6]>>5;let h=0;c===2?h+=2:(c&1&&c!==1&&(h+=2),c&4&&(h+=2));const d=(e[t+6]<<8|e[t+7])>>12-h&1,g=[2,1,2,3,3,4,4,5][c]+d,p=e[t+5]>>3,v=e[t+5]&7,B=new Uint8Array([s<<6|p<<1|v>>2,(v&3)<<6|c<<3|d<<2|l>>4,l<<4&224]),C=1536/a*9e4,y=i+n*C,x=e.subarray(t,t+u);return r.config=B,r.channelCount=g,r.samplerate=a,r.samples.push({unit:x,pts:y}),u}class jB extends Zl{resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Kn(e,0);let i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&zl(t)!==void 0&&If(e,i)<=16)return!1;for(let n=e.length;i<n;i++)if(Ef(e,i))return Ue.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return WB(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return gf(e,t,i,this.basePTS,this.frameIndex)}}const XB=/\/emsg[-/]ID3/i;class zB{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,n){const s=this.videoTrack=pi("video",1),o=this.audioTrack=pi("audio",1),a=this.txtTrack=pi("text",1);if(this.id3Track=pi("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=zh(e);if(l.video){const{id:A,timescale:u,codec:c,supplemental:h}=l.video;s.id=A,s.timescale=a.timescale=u,s.codec=c,s.supplemental=h}if(l.audio){const{id:A,timescale:u,codec:c}=l.audio;o.id=A,o.timescale=u,o.codec=c}a.id=qh.text,s.sampleDuration=0,s.duration=o.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return Jy(e)}demux(e,t){this.timeOffset=t;let i=e;const n=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Jt(this.remainderData,e));const a=rC(i);this.remainderData=a.remainder,n.samples=a.valid||new Uint8Array}else n.samples=i;const o=this.extractID3Track(n,t);return s.samples=ed(t,n),{videoTrack:n,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 n=this.extractID3Track(t,this.timeOffset);return i.samples=ed(e,t),{videoTrack:t,audioTrack:pi(),id3Track:n,textTrack:pi()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const n=we(e.samples,["emsg"]);n&&n.forEach(s=>{const o=sC(s);if(XB.test(o.schemeIdUri)){const a=yf(o,t);let l=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const A=o.payload;i.samples.push({data:A,len:A.byteLength,dts:a,pts:a,type:Ht.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata&&o.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const a=yf(o,t);i.samples.push({data:o.payload,len:o.payload.byteLength,dts:a,pts:a,type:Ht.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function yf(r,e){return de(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale}class ZB{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Ll(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,er.cbc)}decryptAacSample(e,t,i){const n=e[t].unit;if(n.length<=16)return;const s=n.subarray(16,n.length-n.length%16),o=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(o).then(a=>{const l=new Uint8Array(a);n.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 n=0;for(let s=32;s<e.length-16;s+=160,n+=16)i.set(e.subarray(s,s+16),n);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let n=0;for(let s=32;s<e.length-16;s+=160,n+=16)e.set(i.subarray(n,n+16),s);return e}decryptAvcSample(e,t,i,n,s){const o=td(s.data),a=this.getAvcEncryptedData(o);this.decryptBuffer(a.buffer).then(l=>{s.data=this.getAvcDecryptedUnit(o,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,n)})}decryptAvcSamples(e,t,i,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){n();return}const s=e[t].units;for(;!(i>=s.length);i++){const o=s[i];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,t,i,n,o),!this.decrypter.isSync()))return}}}}class Cf{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,n;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const s=i.units;n=s[s.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,n=i.length;if(n){const s=i[n-1];e.pts=s.pts,e.dts=s.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){const n=t.byteLength;let s=e.naluState||0;const o=s,a=[];let l=0,A,u,c,h=-1,d=0;for(s===-1&&(h=0,d=this.getNALuType(t,0),s=0,l=1);l<n;){if(A=t[l++],!s){s=A?0:1;continue}if(s===1){s=A?0:2;continue}if(!A)s=3;else if(A===1){if(u=l-s-1,h>=0){const f={data:t.subarray(h,u),type:d};a.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(o&&l<=4-o&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-o)),u>0&&(f.data=Jt(f.data,t.subarray(0,u)),f.state=0))}l<n?(c=this.getNALuType(t,l),h=l,d=c,s=0):s=-1}else s=0}if(h>=0&&s>=0){const f={data:t.subarray(h,n),type:d,state:s};a.push(f)}if(a.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=Jt(f.data,t))}return e.naluState=s,a}}class Wn{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,n=new Uint8Array(4),s=Math.min(4,t);if(s===0)throw new Error("no bytes available");n.set(e.subarray(i,i+s)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=s*8,this.bytesAvailable-=s}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&&Ue.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)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)}}class Bf extends Cf{parsePES(e,t,i,n){const s=this.parseNALu(e,i.data,n);let o=this.VideoSample,a,l=!1;i.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach(A=>{var u,c;switch(A.type){case 1:{let g=!1;a=!0;const p=A.data;if(l&&p.length>4){const v=this.readSliceType(p);(v===2||v===4||v===7||v===9)&&(g=!0)}if(g){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.frame=!0,o.key=g;break}case 5:a=!0,(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:{a=!0,xl(A.data,1,i.pts,t.samples);break}case 7:{var d,f;a=!0,l=!0;const g=A.data,p=this.readSPS(g);if(!e.sps||e.width!==p.width||e.height!==p.height||((d=e.pixelRatio)==null?void 0:d[0])!==p.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==p.pixelRatio[1]){e.width=p.width,e.height=p.height,e.pixelRatio=p.pixelRatio,e.sps=[g];const v=g.subarray(1,4);let B="avc1.";for(let C=0;C<3;C++){let y=v[C].toString(16);y.length<2&&(y="0"+y),B+=y}e.codec=B}break}case 8:a=!0,e.pps=[A.data];break;case 9:a=!0,e.audFound=!0,(c=o)!=null&&c.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:a=!0;break;default:a=!1;break}o&&a&&o.units.push(A)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Wn(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,n=8,s;for(let o=0;o<e;o++)n!==0&&(s=t.readEG(),n=(i+s+256)%256),i=n===0?i:n}readSPS(e){const t=new Wn(e);let i=0,n=0,s=0,o=0,a,l,A;const u=t.readUByte.bind(t),c=t.readBits.bind(t),h=t.readUEG.bind(t),d=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),p=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);u();const B=u();if(c(5),f(3),u(),p(),B===100||B===110||B===122||B===244||B===44||B===83||B===86||B===118||B===128){const F=h();if(F===3&&f(1),p(),p(),f(1),d())for(l=F!==3?8:12,A=0;A<l;A++)d()&&(A<6?v(16,t):v(64,t))}p();const C=h();if(C===0)h();else if(C===1)for(f(1),g(),g(),a=h(),A=0;A<a;A++)g();p(),f(1);const y=h(),x=h(),w=c(1);w===0&&f(1),f(1),d()&&(i=h(),n=h(),s=h(),o=h());let D=[1,1];if(d()&&d())switch(u()){case 1:D=[1,1];break;case 2:D=[12,11];break;case 3:D=[10,11];break;case 4:D=[16,11];break;case 5:D=[40,33];break;case 6:D=[24,11];break;case 7:D=[20,11];break;case 8:D=[32,11];break;case 9:D=[80,33];break;case 10:D=[18,11];break;case 11:D=[15,11];break;case 12:D=[64,33];break;case 13:D=[160,99];break;case 14:D=[4,3];break;case 15:D=[3,2];break;case 16:D=[2,1];break;case 255:{D=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((y+1)*16-i*2-n*2),height:(2-w)*(x+1)*16-(w?2:4)*(s+o),pixelRatio:D}}}class Tf extends Cf{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,n){const s=this.parseNALu(e,i.data,n);let o=this.VideoSample,a,l=!1;i.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach(A=>{var u,c;switch(A.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.frame=!0,a=!0;break;case 16:case 17:case 18:case 21:if(a=!0,l){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 19:case 20:a=!0,(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 39:a=!0,xl(A.data,2,i.pts,t.samples);break;case 32:a=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=qe(e.params,this.readVPS(A.data)),this.initVPS=A.data),e.vps=[A.data];break;case 33:if(a=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],A.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const d=this.readSPS(A.data);e.width=d.width,e.height=d.height,e.pixelRatio=d.pixelRatio,e.codec=d.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const f in d.params)e.params[f]=d.params[f]}this.pushParameterSet(e.sps,A.data,e.vps),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0;break;case 34:if(a=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const d=this.readPPS(A.data);for(const f in d)e.params[f]=d[f]}this.pushParameterSet(e.pps,A.data,e.vps)}break;case 35:a=!0,e.audFound=!0,(c=o)!=null&&c.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:a=!1;break}o&&a&&o.units.push(A)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let n=0;n<e.byteLength;n++)n>=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[i]=e[n],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Wn(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const i=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:n}}readSPS(e){const t=new Wn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const n=t.readBits(2),s=t.readBoolean(),o=t.readBits(5),a=t.readUByte(),l=t.readUByte(),A=t.readUByte(),u=t.readUByte(),c=t.readUByte(),h=t.readUByte(),d=t.readUByte(),f=t.readUByte(),g=t.readUByte(),p=t.readUByte(),v=t.readUByte(),B=[],C=[];for(let ye=0;ye<i;ye++)B.push(t.readBoolean()),C.push(t.readBoolean());if(i>0)for(let ye=i;ye<8;ye++)t.readBits(2);for(let ye=0;ye<i;ye++)B[ye]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),C[ye]&&t.readUByte();t.readUEG();const y=t.readUEG();y==3&&t.skipBits(1);const x=t.readUEG(),w=t.readUEG(),D=t.readBoolean();let F=0,O=0,M=0,j=0;D&&(F+=t.readUEG(),O+=t.readUEG(),M+=t.readUEG(),j+=t.readUEG());const X=t.readUEG(),le=t.readUEG(),oe=t.readUEG(),L=t.readBoolean();for(let ye=L?0:i;ye<=i;ye++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let ke=0;ke<4;ke++)for(let Ge=0;Ge<(ke===3?2:6);Ge++)if(!t.readBoolean())t.readUEG();else{const $e=Math.min(64,1<<4+(ke<<1));ke>1&&t.readEG();for(let He=0;He<$e;He++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const R=t.readUEG();let _=0;for(let ye=0;ye<R;ye++){let ke=!1;if(ye!==0&&(ke=t.readBoolean()),ke){ye===R&&t.readUEG(),t.readBoolean(),t.readUEG();let Ge=0;for(let ze=0;ze<=_;ze++){const $e=t.readBoolean();let He=!1;$e||(He=t.readBoolean()),($e||He)&&Ge++}_=Ge}else{const Ge=t.readUEG(),ze=t.readUEG();_=Ge+ze;for(let $e=0;$e<Ge;$e++)t.readUEG(),t.readBoolean();for(let $e=0;$e<ze;$e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const ye=t.readUEG();for(let ke=0;ke<ye;ke++){for(let Ge=0;Ge<oe+4;Ge++)t.readBits(1);t.readBits(1)}}let K=0,Y=1,ie=1,re=!0,he=1,fe=0;t.readBoolean(),t.readBoolean();let _e=!1;if(t.readBoolean()){if(t.readBoolean()){const Ce=t.readUByte(),it=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],at=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Ce>0&&Ce<16?(Y=it[Ce-1],ie=at[Ce-1]):Ce===255&&(Y=t.readBits(16),ie=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),_e=t.readBoolean(),_e&&(F+=t.readUEG(),O+=t.readUEG(),M+=t.readUEG(),j+=t.readUEG()),t.readBoolean()&&(he=t.readBits(32),fe=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const at=t.readBoolean(),tt=t.readBoolean();let Ze=!1;(at||tt)&&(Ze=t.readBoolean(),Ze&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Ze&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let T=0;T<=i;T++){re=t.readBoolean();const m=re||t.readBoolean();let E=!1;m?t.readEG():E=t.readBoolean();const Q=E?1:t.readUEG()+1;if(at)for(let N=0;N<Q;N++)t.readUEG(),t.readUEG(),Ze&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(tt)for(let N=0;N<Q;N++)t.readUEG(),t.readUEG(),Ze&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),K=t.readUEG())}let Fe=x,pe=w;if(D||_e){let ye=1,ke=1;y===1?ye=ke=2:y==2&&(ye=2),Fe=x-ye*O-ye*F,pe=w-ke*j-ke*M}const Qe=n?["A","B","C"][n]:"",Oe=a<<24|l<<16|A<<8|u;let Re=0;for(let ye=0;ye<32;ye++)Re=(Re|(Oe>>ye&1)<<31-ye)>>>0;let We=Re.toString(16);return o===1&&We==="2"&&(We="6"),{codecString:`hvc1.${Qe}${o}.${We}.${s?"H":"L"}${v}.B0`,params:{general_tier_flag:s,general_profile_idc:o,general_profile_space:n,general_profile_compatibility_flags:[a,l,A,u],general_constraint_indicator_flags:[c,h,d,f,g,p],general_level_idc:v,bit_depth:X+8,bit_depth_luma_minus8:X,bit_depth_chroma_minus8:le,min_spatial_segmentation_idc:K,chroma_format_idc:y,frame_rate:{fixed:re,fps:fe/he}},width:Fe,height:pe,pixelRatio:[Y,ie]}}readPPS(e){const t=new Wn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const n=t.readBoolean(),s=t.readBoolean();let o=1;return s&&n?o=0:s?o=3:n&&(o=2),{parallelismType:o}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Bt=188;class tr{constructor(e,t,i,n){this.logger=void 0,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._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=n,this.videoParser=null}static probe(e,t){const i=tr.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){const t=e.length;let i=Math.min(Bt*5,t-Bt)+1,n=0;for(;n<i;){let s=!1,o=-1,a=0;for(let l=n;l<t;l+=Bt)if(e[l]===71&&(t-l===Bt||e[l+Bt]===71)){if(a++,o===-1&&(o=l,o!==0&&(i=Math.min(o+Bt*99,e.length-Bt)+1)),s||(s=tA(e,l)===0),s&&a>1&&(o===0&&a>2||l+Bt>i))return o}else{if(a)return-1;break}n++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:qh[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=tr.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=tr.createTrack("audio",n),this._id3Track=tr.createTrack("id3"),this._txtTrack=tr.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,n=!1){i||(this.sampleAes=null);let s;const o=this._videoTrack,a=this._audioTrack,l=this._id3Track,A=this._txtTrack;let u=o.pid,c=o.pesData,h=a.pid,d=l.pid,f=a.pesData,g=l.pesData,p=null,v=this.pmtParsed,B=this._pmtId,C=e.length;if(this.remainderData&&(e=Jt(this.remainderData,e),C=e.length,this.remainderData=null),C<Bt&&!n)return this.remainderData=e,{audioTrack:a,videoTrack:o,id3Track:l,textTrack:A};const y=Math.max(0,tr.syncOffset(e));C-=(C-y)%Bt,C<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,C,e.buffer.byteLength-C));let x=0;for(let D=y;D<C;D+=Bt)if(e[D]===71){const F=!!(e[D+1]&64),O=tA(e,D),M=(e[D+3]&48)>>4;let j;if(M>1){if(j=D+5+e[D+4],j===D+Bt)continue}else j=D+4;switch(O){case u:if(F){if(c&&(s=Vr(c,this.logger))){if(this.videoParser===null)switch(o.segmentCodec){case"avc":this.videoParser=new Bf;break;case"hevc":this.videoParser=new Tf;break}this.videoParser!==null&&this.videoParser.parsePES(o,A,s,!1)}c={data:[],size:0}}c&&(c.data.push(e.subarray(j,D+Bt)),c.size+=D+Bt-j);break;case h:if(F){if(f&&(s=Vr(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s);break;case"ac3":this.parseAC3PES(a,s);break}f={data:[],size:0}}f&&(f.data.push(e.subarray(j,D+Bt)),f.size+=D+Bt-j);break;case d:F&&(g&&(s=Vr(g,this.logger))&&this.parseID3PES(l,s),g={data:[],size:0}),g&&(g.data.push(e.subarray(j,D+Bt)),g.size+=D+Bt-j);break;case 0:F&&(j+=e[j]+1),B=this._pmtId=eT(e,j);break;case B:{F&&(j+=e[j]+1);const X=tT(e,j,this.typeSupported,i,this.observer,this.logger);u=X.videoPid,u>0&&(o.pid=u,o.segmentCodec=X.segmentVideoCodec),h=X.audioPid,h>0&&(a.pid=h,a.segmentCodec=X.segmentAudioCodec),d=X.id3Pid,d>0&&(l.pid=d),p!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${D} after unknown PID '${p}'. Backtracking to sync byte @${y} to parse all TS packets.`),p=null,D=y-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=O;break}}else x++;x>0&&iA(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=c,a.pesData=f,l.pesData=g;const w={audioTrack:a,videoTrack:o,id3Track:l,textTrack:A};return n&&this.extractRemainingSamples(w),w}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:n,textTrack:s}=e,o=i.pesData,a=t.pesData,l=n.pesData;let A;if(o&&(A=Vr(o,this.logger))){if(this.videoParser===null)switch(i.segmentCodec){case"avc":this.videoParser=new Bf;break;case"hevc":this.videoParser=new Tf;break}this.videoParser!==null&&(this.videoParser.parsePES(i,s,A,!0),i.pesData=null)}else i.pesData=o;if(a&&(A=Vr(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,A);break;case"mp3":this.parseMPEGPES(t,A);break;case"ac3":this.parseAC3PES(t,A);break}t.pesData=null}else a!=null&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;l&&(A=Vr(l,this.logger))?(this.parseID3PES(n,A),n.pesData=null):n.pesData=l}demuxSampleAes(e,t,i){const n=this.demux(e,i,!0,!this.config.progressive),s=this.sampleAes=new ZB(this.observer,this.config,t);return this.decrypt(n,s)}decrypt(e,t){return new Promise(i=>{const{audioTrack:n,videoTrack:s}=e;n.samples&&n.segmentCodec==="aac"?t.decryptAacSamples(n.samples,0,()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,()=>{i(e)}):i(e)}):s.samples&&t.decryptAvcSamples(s.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0;const n=this.aacOverFlow;let s=t.data;if(n){this.aacOverFlow=null;const c=n.missing,h=n.sample.unit.byteLength;if(c===-1)s=Jt(n.sample.unit,s);else{const d=h-c;n.sample.unit.set(s.subarray(0,c),d),e.samples.push(n.sample),i=n.missing}}let o,a;for(o=i,a=s.length;o<a-1&&!_o(s,o);o++);if(o!==i){let c;const h=o<a-1;if(h?c=`AAC PES did not start with ADTS header,offset:${o}`:c="No ADTS header found in AAC PES",iA(this.observer,new Error(c),h,this.logger),!h)return}Af(e,this.observer,s,o,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(n){const c=cf(e.samplerate);l=n.sample.pts+c}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let A=0,u;for(;o<a;)if(u=uf(e,s,o,l,A),o+=u.length,u.missing){this.aacOverFlow=u;break}else for(A++;o<a-1&&!_o(s,o);o++);}parseMPEGPES(e,t){const i=t.data,n=i.length;let s=0,o=0;const a=t.pts;if(a===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;o<n;)if(mf(i,o)){const l=gf(e,i,o,a,s);if(l)o+=l.length,s++;else break}else o++}parseAC3PES(e,t){{const i=t.data,n=t.pts;if(n===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const s=i.length;let o=0,a=0,l;for(;a<s&&(l=vf(e,i,a,n,o++))>0;)a+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=qe({},t,{type:this._videoTrack?Ht.emsg:Ht.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function tA(r,e){return((r[e+1]&31)<<8)+r[e+2]}function eT(r,e){return(r[e+10]&31)<<8|r[e+11]}function tT(r,e,t,i,n,s){const o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=(r[e+1]&15)<<8|r[e+2],l=e+3+a-4,A=(r[e+10]&15)<<8|r[e+11];for(e+=12+A;e<l;){const u=tA(r,e),c=(r[e+3]&15)<<8|r[e+4];switch(r[e]){case 207:if(!i){rA("ADTS AAC",s);break}case 15:o.audioPid===-1&&(o.audioPid=u);break;case 21:o.id3Pid===-1&&(o.id3Pid=u);break;case 219:if(!i){rA("H.264",s);break}case 27:o.videoPid===-1&&(o.videoPid=u);break;case 3:case 4:!t.mpeg&&!t.mp3?s.log("MPEG audio found, not supported in this browser"):o.audioPid===-1&&(o.audioPid=u,o.segmentAudioCodec="mp3");break;case 193:if(!i){rA("AC-3",s);break}case 129:t.ac3?o.audioPid===-1&&(o.audioPid=u,o.segmentAudioCodec="ac3"):s.log("AC-3 audio found, not supported in this browser");break;case 6:if(o.audioPid===-1&&c>0){let h=e+5,d=c;for(;d>2;){switch(r[h]){case 106:t.ac3!==!0?s.log("AC-3 audio found, not supported in this browser for now"):(o.audioPid=u,o.segmentAudioCodec="ac3");break}const g=r[h+1]+2;h+=g,d-=g}}break;case 194:case 135:return iA(n,new Error("Unsupported EC-3 in M2TS found"),void 0,s),o;case 36:o.videoPid===-1&&(o.videoPid=u,o.segmentVideoCodec="hevc",s.log("HEVC in M2TS found"));break}e+=c+5}return o}function iA(r,e,t,i){i.warn(`parsing error: ${e.message}`),r.emit(I.ERROR,I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function rA(r,e){e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function Vr(r,e){let t=0,i,n,s,o,a;const l=r.data;if(!r||r.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=Jt(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(n=(i[4]<<8)+i[5],n&&n>r.size-6)return null;const u=i[7];u&192&&(o=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,u&64?(a=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,o-a>54e5&&(e.warn(`${Math.round((o-a)/9e4)}s delta between PTS and DTS, align them`),o=a)):a=o),s=i[8];let c=s+9;if(r.size<=c)return null;r.size-=c;const h=new Uint8Array(r.size);for(let d=0,f=l.length;d<f;d++){i=l[d];let g=i.byteLength;if(c)if(c>g){c-=g;continue}else i=i.subarray(c),g-=c,c=0;h.set(i,t),t+=g}return n&&(n-=s+3),{data:h,pts:o,dts:a,len:n}}return null}class iT{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 ir=Math.pow(2,32)-1;class H{static init(){H.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in H.types)H.types.hasOwnProperty(e)&&(H.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]);H.HDLR_TYPES={video:t,audio:i};const n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);H.STTS=H.STSC=H.STCO=s,H.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),H.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),H.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),H.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]);H.FTYP=H.box(H.types.ftyp,o,l,o,a),H.DINF=H.box(H.types.dinf,H.box(H.types.dref,n))}static box(e,...t){let i=8,n=t.length;const s=n;for(;n--;)i+=t[n].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),n=0,i=8;n<s;n++)o.set(t[n],i),i+=t[n].byteLength;return o}static hdlr(e){return H.box(H.types.hdlr,H.HDLR_TYPES[e])}static mdat(e){return H.box(H.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(ir+1)),n=Math.floor(t%(ir+1));return H.box(H.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,n>>24,n>>16&255,n>>8&255,n&255,85,196,0,0]))}static mdia(e){return H.box(H.types.mdia,H.mdhd(e.timescale||0,e.duration||0),H.hdlr(e.type),H.minf(e))}static mfhd(e){return H.box(H.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"?H.box(H.types.minf,H.box(H.types.smhd,H.SMHD),H.DINF,H.stbl(e)):H.box(H.types.minf,H.box(H.types.vmhd,H.VMHD),H.DINF,H.stbl(e))}static moof(e,t,i){return H.box(H.types.moof,H.mfhd(e),H.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=H.trak(e[t]);return H.box.apply(null,[H.types.moov,H.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(H.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=H.trex(e[t]);return H.box.apply(null,[H.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(ir+1)),n=Math.floor(t%(ir+1)),s=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,n>>24,n>>16&255,n>>8&255,n&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 H.box(H.types.mvhd,s)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let n,s;for(n=0;n<t.length;n++)s=t[n].flags,i[n+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return H.box(H.types.sdtp,i)}static stbl(e){return H.box(H.types.stbl,H.stsd(e),H.box(H.types.stts,H.STTS),H.box(H.types.stsc,H.STSC),H.box(H.types.stsz,H.STSZ),H.box(H.types.stco,H.STCO))}static avc1(e){let t=[],i=[],n,s,o;for(n=0;n<e.sps.length;n++)s=e.sps[n],o=s.byteLength,t.push(o>>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(s));for(n=0;n<e.pps.length;n++)s=e.pps[n],o=s.byteLength,i.push(o>>>8&255),i.push(o&255),i=i.concat(Array.prototype.slice.call(s));const a=H.box(H.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,A=e.height,u=e.pixelRatio[0],c=e.pixelRatio[1];return H.box(H.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,A>>8&255,A&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,H.box(H.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),H.box(H.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,c>>24,c>>16&255,c>>8&255,c&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return H.box(H.types.mp4a,H.audioStsd(e),H.box(H.types.esds,H.esds(e)))}static mp3(e){return H.box(H.types[".mp3"],H.audioStsd(e))}static ac3(e){return H.box(H.types["ac-3"],H.audioStsd(e),H.box(H.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return H.box(H.types.stsd,H.STSD,H.mp4a(e));if(t==="ac3"&&e.config)return H.box(H.types.stsd,H.STSD,H.ac3(e));if(t==="mp3"&&e.codec==="mp3")return H.box(H.types.stsd,H.STSD,H.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return H.box(H.types.stsd,H.STSD,H.avc1(e));if(t==="hevc"&&e.vps)return H.box(H.types.stsd,H.STSD,H.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,i=(e.duration||0)*(e.timescale||0),n=e.width||0,s=e.height||0,o=Math.floor(i/(ir+1)),a=Math.floor(i%(ir+1));return H.box(H.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,n>>8&255,n&255,0,0,s>>8&255,s&255,0,0]))}static traf(e,t){const i=H.sdtp(e),n=e.id,s=Math.floor(t/(ir+1)),o=Math.floor(t%(ir+1));return H.box(H.types.traf,H.box(H.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),H.box(H.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,s&255,o>>24,o>>16&255,o>>8&255,o&255])),H.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,H.box(H.types.trak,H.tkhd(e),H.mdia(e))}static trex(e){const t=e.id;return H.box(H.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||[],n=i.length,s=12+16*n,o=new Uint8Array(s);let a,l,A,u,c,h;for(t+=8+s,o.set([e.type==="video"?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,n&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),a=0;a<n;a++)l=i[a],A=l.duration,u=l.size,c=l.flags,h=l.cts,o.set([A>>>24&255,A>>>16&255,A>>>8&255,A&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,c.degradPrio&61440,c.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*a);return H.box(H.types.trun,o)}static initSegment(e){H.types||H.init();const t=H.moov(e);return Jt(H.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],n=4,s=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),n-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let o=s.length;for(let f=0;f<i.length;f+=1){o+=3;for(let g=0;g<i[f].length;g+=1)o+=2+i[f][g].length}const a=new Uint8Array(o);a.set(s,0),o=s.length;const l=i.length-1;for(let f=0;f<i.length;f+=1){a.set(new Uint8Array([32+f|(f===l?128:0),0,i[f].length]),o),o+=3;for(let g=0;g<i[f].length;g+=1)a.set(new Uint8Array([i[f][g].length>>8,i[f][g].length&255]),o),o+=2,a.set(i[f][g],o),o+=i[f][g].length}const A=H.box(H.types.hvcC,a),u=e.width,c=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return H.box(H.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,u&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,H.box(H.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),H.box(H.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,d>>24,d>>16&255,d>>8&255,d&255])))}}H.types=void 0,H.HDLR_TYPES=void 0,H.STTS=void 0,H.STSC=void 0,H.STCO=void 0,H.STSZ=void 0,H.VMHD=void 0,H.SMHD=void 0,H.STSD=void 0,H.FTYP=void 0,H.DINF=void 0;const bf=9e4;function nA(r,e,t=1,i=!1){const n=r*e*t;return i?Math.round(n):n}function rT(r,e,t=1,i=!1){return nA(r,e,1/t,i)}function qn(r,e=!1){return nA(r,1e3,1/bf,e)}function nT(r,e=1){return nA(r,bf,1/e)}const sT=10*1e3,oT=1024,aT=1152,lT=1536;let Kr=null,sA=null;function Sf(r,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:r?2:1,isNonSync:r?0:1}}}class Do{constructor(e,t,i,n){if(this.logger=void 0,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.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=n,this.ISGenerated=!1,Kr===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Kr=o?parseInt(o[1]):0}if(sA===null){const s=navigator.userAgent.match(/Safari\/(\d+)/i);sA=s?parseInt(s[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,n=e.reduce((s,o)=>{let a=o.pts,l=a-s;return l<-4294967296&&(t=!0,a=jt(a,i),l=a-s),l>0?s:a},i);return t&&this.logger.debug("PTS rollover detected"),n}remux(e,t,i,n,s,o,a,l){let A,u,c,h,d,f,g=s,p=s;const v=e.pid>-1,B=t.pid>-1,C=t.samples.length,y=e.samples.length>0,x=a&&C>0||C>1;if((!v||y)&&(!B||x)||this.ISGenerated||a){if(this.ISGenerated){var D,F,O,M;const oe=this.videoTrackConfig;(oe&&(t.width!==oe.width||t.height!==oe.height||((D=t.pixelRatio)==null?void 0:D[0])!==((F=oe.pixelRatio)==null?void 0:F[0])||((O=t.pixelRatio)==null?void 0:O[1])!==((M=oe.pixelRatio)==null?void 0:M[1]))||!oe&&x||this.nextAudioPts===null&&y)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,s,o));const j=this.isVideoContiguous;let X=-1,le;if(x&&(X=AT(t.samples),!j&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,X>0){this.logger.warn(`[mp4-remuxer]: Dropped ${X} out of ${C} video samples due to a missing keyframe`);const oe=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(X),t.dropped+=X,p+=(t.samples[0].pts-oe)/t.inputTimeScale,le=p}else X===-1&&(this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${C} video samples`),f=!1);if(this.ISGenerated){if(y&&x){const oe=this.getVideoStartPts(t.samples),U=(jt(e.samples[0].pts,oe)-oe)/t.inputTimeScale;g+=Math.max(0,U),p+=Math.max(0,-U)}if(y){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(e,t,s,o)),u=this.remuxAudio(e,g,this.isAudioContiguous,o,B||x||l===Ee.AUDIO?p:void 0),x){const oe=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(e,t,s,o)),A=this.remuxVideo(t,p,j,oe)}}else x&&(A=this.remuxVideo(t,p,j,0));A&&(A.firstKeyFrame=X,A.independent=X!==-1,A.firstKeyFramePTS=le)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(d=xf(i,s,this._initPTS,this._initDTS)),n.samples.length&&(h=Qf(n,s,this._initPTS))),{audio:u,video:A,initSegment:c,independent:f,text:h,id3:d}}generateIS(e,t,i,n){const s=e.samples,o=t.samples,a=this.typeSupported,l={},A=this._initPTS;let u=!A||n,c="audio/mp4",h,d,f;if(u&&(h=d=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(c="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:c,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):H.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(f=e.inputTimeScale,!A||f!==A.timescale?h=d=s[0].pts-Math.round(f*i):u=!1)}if(t.sps&&t.pps&&o.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:H.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(f=t.inputTimeScale,!A||f!==A.timescale){const g=this.getVideoStartPts(o),p=Math.round(f*i);d=Math.min(d,jt(o[0].dts,g)-p),h=Math.min(h,g-p)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:f},this._initDTS={baseTime:d,timescale:f}):h=f=void 0,{tracks:l,initPTS:h,timescale:f}}remuxVideo(e,t,i,n){const s=e.inputTimeScale,o=e.samples,a=[],l=o.length,A=this._initPTS;let u=this.nextAvcDts,c=8,h=this.videoSampleDuration,d,f,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!i||u===null){const _=t*s,k=o[0].pts-jt(o[0].dts,o[0].pts);Kr&&u!==null&&Math.abs(_-k-u)<15e3?i=!0:u=_-k}const B=A.baseTime*s/A.timescale;for(let _=0;_<l;_++){const k=o[_];k.pts=jt(k.pts-B,u),k.dts=jt(k.dts-B,u),k.dts<o[_>0?_-1:_].dts&&(v=!0)}v&&o.sort(function(_,k){const K=_.dts-k.dts,Y=_.pts-k.pts;return K||Y}),d=o[0].dts,f=o[o.length-1].dts;const C=f-d,y=C?Math.round(C/(l-1)):h||e.inputTimeScale/30;if(i){const _=d-u,k=_>y,K=_<-1;if((k||K)&&(k?this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${qn(_,!0)} ms (${_}dts) hole between fragments detected at ${t.toFixed(3)}`):this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${qn(-_,!0)} ms (${_}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!K||u>=o[0].pts||Kr)){d=u;const Y=o[0].pts-_;if(k)o[0].dts=d,o[0].pts=Y;else{let ie=!0;for(let re=0;re<o.length&&!(o[re].dts>Y&&ie);re++){const he=o[re].pts;if(o[re].dts-=_,o[re].pts-=_,re<o.length-1){const fe=o[re+1].pts,_e=o[re].pts,be=fe<=_e,Fe=fe<=he;ie=be==Fe}}}this.logger.log(`Video: Initial PTS/DTS adjusted: ${qn(Y,!0)}/${qn(d,!0)}, delta: ${qn(_,!0)} ms`)}}d=Math.max(0,d);let x=0,w=0,D=d;for(let _=0;_<l;_++){const k=o[_],K=k.units,Y=K.length;let ie=0;for(let re=0;re<Y;re++)ie+=K[re].data.length;w+=ie,x+=Y,k.length=ie,k.dts<D?(k.dts=D,D+=y/4|0||1):D=k.dts,g=Math.min(k.pts,g),p=Math.max(k.pts,p)}f=o[l-1].dts;const F=w+4*x+8;let O;try{O=new Uint8Array(F)}catch(_){this.observer.emit(I.ERROR,I.ERROR,{type:Ie.MUX_ERROR,details:V.REMUX_ALLOC_ERROR,fatal:!1,error:_,bytes:F,reason:`fail allocating video mdat ${F}`});return}const M=new DataView(O.buffer);M.setUint32(0,F),O.set(H.types.mdat,4);let j=!1,X=Number.POSITIVE_INFINITY,le=Number.POSITIVE_INFINITY,oe=Number.NEGATIVE_INFINITY,L=Number.NEGATIVE_INFINITY;for(let _=0;_<l;_++){const k=o[_],K=k.units;let Y=0;for(let he=0,fe=K.length;he<fe;he++){const _e=K[he],be=_e.data,Fe=_e.data.byteLength;M.setUint32(c,Fe),c+=4,O.set(be,c),c+=Fe,Y+=4+Fe}let ie;if(_<l-1)h=o[_+1].dts-k.dts,ie=o[_+1].pts-k.pts;else{const he=this.config,fe=_>0?k.dts-o[_-1].dts:y;if(ie=_>0?k.pts-o[_-1].pts:y,he.stretchShortVideoTrack&&this.nextAudioPts!==null){const _e=Math.floor(he.maxBufferHole*s),be=(n?g+n*s:this.nextAudioPts)-k.pts;be>_e?(h=be-fe,h<0?h=fe:j=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${be/90} ms to the next segment; using duration ${h/90} ms for the last video frame.`)):h=fe}else h=fe}const re=Math.round(k.pts-k.dts);X=Math.min(X,h),oe=Math.max(oe,h),le=Math.min(le,ie),L=Math.max(L,ie),a.push(Sf(k.key,h,Y,re))}if(a.length){if(Kr){if(Kr<70){const _=a[0].flags;_.dependsOn=2,_.isNonSync=0}}else if(sA&&L-le<oe-X&&y/oe<.025&&a[0].cts===0){this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let _=d;for(let k=0,K=a.length;k<K;k++){const Y=_+a[k].duration,ie=_+a[k].cts;if(k<K-1){const re=Y+a[k+1].cts;a[k].duration=re-ie}else a[k].duration=k?a[k-1].duration:y;a[k].cts=0,_=Y}}}h=j||!h?y:h,this.nextAvcDts=u=f+h,this.videoSampleDuration=h,this.isVideoContiguous=!0;const R={data1:H.moof(e.sequenceNumber++,d,qe(e,{samples:a})),data2:O,startPTS:g/s,endPTS:(p+h)/s,startDTS:d/s,endDTS:u/s,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,R}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return aT;case"ac3":return lT;default:return oT}}remuxAudio(e,t,i,n,s){const o=e.inputTimeScale,a=e.samplerate?e.samplerate:o,l=o/a,A=this.getSamplesPerFrame(e),u=A*l,c=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,d=[],f=s!==void 0;let g=e.samples,p=h?0:8,v=this.nextAudioPts||-1;const B=t*o,C=c.baseTime*o/c.timescale;if(this.isAudioContiguous=i=i||g.length&&v>0&&(n&&Math.abs(B-v)<9e3||Math.abs(jt(g[0].pts-C,B)-v)<20*u),g.forEach(function(U){U.pts=jt(U.pts-C,B)}),!i||v<0){if(g=g.filter(U=>U.pts>=0),!g.length)return;s===0?v=0:n&&!f?v=Math.max(0,B):v=g[0].pts}if(e.segmentCodec==="aac"){const U=this.config.maxAudioFramesDrift;for(let q=0,R=v;q<g.length;q++){const _=g[q],k=_.pts,K=k-R,Y=Math.abs(1e3*K/o);if(K<=-U*u&&f)q===0&&(this.logger.warn(`Audio frame @ ${(k/o).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*K/o)} ms.`),this.nextAudioPts=v=R=k);else if(K>=U*u&&Y<sT&&f){let ie=Math.round(K/u);R=k-ie*u,R<0&&(ie--,R+=u),q===0&&(this.nextAudioPts=v=R),this.logger.warn(`[mp4-remuxer]: Injecting ${ie} audio frame @ ${(R/o).toFixed(3)}s due to ${Math.round(1e3*K/o)} ms gap.`);for(let re=0;re<ie;re++){const he=Math.max(R,0);let fe=iT.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);fe||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),fe=_.unit.subarray()),g.splice(q,0,{unit:fe,pts:he}),R+=u,q++}}_.pts=R,R+=u}}let y=null,x=null,w,D=0,F=g.length;for(;F--;)D+=g[F].unit.byteLength;for(let U=0,q=g.length;U<q;U++){const R=g[U],_=R.unit;let k=R.pts;if(x!==null){const Y=d[U-1];Y.duration=Math.round((k-x)/l)}else if(i&&e.segmentCodec==="aac"&&(k=v),y=k,D>0){D+=p;try{w=new Uint8Array(D)}catch(Y){this.observer.emit(I.ERROR,I.ERROR,{type:Ie.MUX_ERROR,details:V.REMUX_ALLOC_ERROR,fatal:!1,error:Y,bytes:D,reason:`fail allocating audio mdat ${D}`});return}h||(new DataView(w.buffer).setUint32(0,D),w.set(H.types.mdat,4))}else return;w.set(_,p);const K=_.byteLength;p+=K,d.push(Sf(!0,A,K,0)),x=k}const O=d.length;if(!O)return;const M=d[d.length-1];this.nextAudioPts=v=x+l*M.duration;const j=h?new Uint8Array(0):H.moof(e.sequenceNumber++,y/l,qe({},e,{samples:d}));e.samples=[];const X=y/o,le=v/o,L={data1:j,data2:w,startPTS:X,endPTS:le,startDTS:X,endDTS:le,type:"audio",hasAudio:!0,hasVideo:!1,nb:O};return this.isAudioContiguous=!0,L}}function jt(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 AT(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function xf(r,e,t,i){const n=r.samples.length;if(!n)return;const s=r.inputTimeScale;for(let a=0;a<n;a++){const l=r.samples[a];l.pts=jt(l.pts-t.baseTime*s/t.timescale,e*s)/s,l.dts=jt(l.dts-i.baseTime*s/i.timescale,e*s)/s}const o=r.samples;return r.samples=[],{samples:o}}function Qf(r,e,t){const i=r.samples.length;if(!i)return;const n=r.inputTimeScale;for(let o=0;o<i;o++){const a=r.samples[o];a.pts=jt(a.pts-t.baseTime*n/t.timescale,e*n)/n}r.samples.sort((o,a)=>o.pts-a.pts);const s=r.samples;return r.samples=[],{samples:s}}class cT{constructor(e,t,i,n){this.logger=void 0,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,this.logger=n}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,n){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(zy(e,n)),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 n=this.initData=zh(e);n.audio&&(t=_f(n.audio,Je.AUDIO)),n.video&&(i=_f(n.video,Je.VIDEO));const s={};n.audio&&n.video?s.audiovideo={container:"video/mp4",codec:t+","+i,supplemental:n.video.supplemental,initSegment:e,id:"main"}:n.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:n.video?s.video={container:"video/mp4",codec:i,supplemental:n.video.supplemental,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,i,n,s,o){var a,l;let{initPTS:A,lastEndTime:u}=this;const c={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};de(u)||(u=this.lastEndTime=s||0);const h=t.samples;if(!(h!=null&&h.length))return c;const d={initPTS:void 0,timescale:1};let f=this.initData;if((a=f)!=null&&a.length||(this.generateInitSegment(h),f=this.initData),!((l=f)!=null&&l.length))return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(d.tracks=this.initTracks,this.emitInitSegment=!1);const g=eC(h,f),p=Zy(f,h),v=p===null?s:p;(o||!A)&&(uT(A,v,s,g)||d.timescale!==A.timescale)&&(d.initPTS=v-s,A&&A.timescale===1&&this.logger.warn(`Adjusting initPTS @${s} from ${A.baseTime/A.timescale} to ${d.initPTS}`),this.initPTS=A={baseTime:d.initPTS,timescale:1});const B=e?v-A.baseTime/A.timescale:u,C=B+g;iC(f,h,A.baseTime/A.timescale),g>0?this.lastEndTime=C:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const y=!!f.audio,x=!!f.video;let w="";y&&(w+="audio"),x&&(w+="video");const D={data1:h,startPTS:B,startDTS:B,endPTS:C,endDTS:C,type:w,hasAudio:y,hasVideo:x,nb:1,dropped:0};return c.audio=D.type==="audio"?D:void 0,c.video=D.type!=="audio"?D:void 0,c.initSegment=d,c.id3=xf(i,s,A,A),n.samples.length&&(c.text=Qf(n,s,A)),c}}function uT(r,e,t,i){if(r===null)return!0;const n=Math.max(i,1),s=e-r.baseTime/r.timescale;return Math.abs(s-t)>n}function _f(r,e){const t=r==null?void 0:r.codec;return t&&t.length>4?t:e===Je.AUDIO?t==="ec-3"||t==="ac-3"||t==="alac"?t:t==="fLaC"||t==="Opus"?fo(t,!1):(Ue.warn(`Unhandled audio codec "${t}" in mp4 MAP`),t||"mp4a"):(Ue.warn(`Unhandled video codec "${t}" in mp4 MAP`),t||"avc1")}let Di;try{Di=self.performance.now.bind(self.performance)}catch{Di=Date.now}const Lo=[{demux:zB,remux:cT},{demux:tr,remux:Do},{demux:qB,remux:Do},{demux:jB,remux:Do}];Lo.splice(2,0,{demux:JB,remux:Do});class wf{constructor(e,t,i,n,s,o){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=s,this.logger=o}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,n){const s=i.transmuxing;s.executeStart=Di();let o=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:l}=this;n&&(this.currentTransmuxState=n);const{contiguous:A,discontinuity:u,trackSwitch:c,accurateTimeOffset:h,timeOffset:d,initSegmentChange:f}=n||a,{audioCodec:g,videoCodec:p,defaultInitPts:v,duration:B,initSegmentData:C}=l,y=hT(o,t);if(y&&Hr(y.method)){const F=this.getDecrypter(),O=Fl(y.method);if(F.isSync()){let M=F.softwareDecrypt(o,y.key.buffer,y.iv.buffer,O);if(i.part>-1){const X=F.flush();M=X&&X.buffer}if(!M)return s.executeEnd=Di(),oA(i);o=new Uint8Array(M)}else return this.asyncResult=!0,this.decryptionPromise=F.webCryptoDecrypt(o,y.key.buffer,y.iv.buffer,O).then(M=>{const j=this.push(M,null,i);return this.decryptionPromise=null,j}),this.decryptionPromise}const x=this.needsProbing(u,c);if(x){const F=this.configureTransmuxer(o);if(F)return this.logger.warn(`[transmuxer] ${F.message}`),this.observer.emit(I.ERROR,I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!1,error:F,reason:F.message}),s.executeEnd=Di(),oA(i)}(u||c||f||x)&&this.resetInitSegment(C,g,p,B,t),(u||f||x)&&this.resetInitialTimestamp(v),A||this.resetContiguity();const w=this.transmux(o,y,d,h,i);this.asyncResult=Jn(w);const D=this.currentTransmuxState;return D.contiguous=!0,D.discontinuity=!1,D.trackSwitch=!1,s.executeEnd=Di(),w}flush(e){const t=e.transmuxing;t.executeStart=Di();const{decrypter:i,currentTransmuxState:n,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then(()=>this.flush(e));const o=[],{timeOffset:a}=n;if(i){const c=i.flush();c&&o.push(this.push(c.buffer,null,e))}const{demuxer:l,remuxer:A}=this;if(!l||!A){t.executeEnd=Di();const c=[oA(e)];return this.asyncResult?Promise.resolve(c):c}const u=l.flush(a);return Jn(u)?(this.asyncResult=!0,u.then(c=>(this.flushRemux(o,c,e),o))):(this.flushRemux(o,u,e),this.asyncResult?Promise.resolve(o):o)}flushRemux(e,t,i){const{audioTrack:n,videoTrack:s,id3Track:o,textTrack:a}=t,{accurateTimeOffset:l,timeOffset:A}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===Ee.MAIN?"level":"track"} ${i.level}`);const u=this.remuxer.remux(n,s,o,a,A,l,!0,this.id);e.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=Di()}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,n,s){const{demuxer:o,remuxer:a}=this;!o||!a||(o.resetInitSegment(e,t,i,n),a.resetInitSegment(e,t,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,n,s){let o;return t&&t.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,t,i,n,s):o=this.transmuxUnencrypted(e,i,n,s),o}transmuxUnencrypted(e,t,i,n){const{audioTrack:s,videoTrack:o,id3Track:a,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,o,a,l,t,i,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,i,n,s){return this.demuxer.demuxSampleAes(e,t,i).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,i,n,!1,this.id),chunkMeta:s}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:n}=this;let s;for(let c=0,h=Lo.length;c<h;c++){var o;if((o=Lo[c].demux)!=null&&o.probe(e,this.logger)){s=Lo[c];break}}if(!s)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,l=this.remuxer,A=s.remux,u=s.demux;(!l||!(l instanceof A))&&(this.remuxer=new A(i,t,n,this.logger)),(!a||!(a instanceof u))&&(this.demuxer=new u(i,t,n,this.logger),this.probe=u.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Ll(this.config)),e}}function hT(r,e){let t=null;return r.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const oA=r=>({remuxResult:{},chunkMeta:r});function Jn(r){return"then"in r&&r.then instanceof Function}class dT{constructor(e,t,i,n,s){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=n,this.defaultInitPts=s||null}}class fT{constructor(e,t,i,n,s,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=n,this.timeOffset=s,this.initSegmentChange=o}}let Rf=0;class Df{constructor(e,t,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Rf++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{const A=l.data,u=this.hls;if(!(!u||!(A!=null&&A.event)||A.instanceNo!==this.instanceNo))switch(A.event){case"init":{var c;const h=(c=this.workerContext)==null?void 0:c.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(A.data);break}case"flush":{this.onFlush(A.data);break}case"workerLog":{u.logger[A.data.logType]&&u.logger[A.data.logType](A.data.message);break}default:{A.data=A.data||{},A.data.frag=this.frag,A.data.part=this.part,A.data.id=this.id,u.trigger(A.event,A.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const A=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:A})};const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;const o=(l,A)=>{A=A||{},A.frag=this.frag||void 0,l===I.ERROR&&(A=A,A.parent=this.id,A.part=this.part,this.error=A.error),this.hls.trigger(l,A)};this.observer=new ql,this.observer.on(I.FRAG_DECRYPTED,o),this.observer.on(I.ERROR,o);const a=od(s.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(s.workerPath||mB()){try{s.workerPath?(l.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=IB(s.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=EB());const{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:rt(s)})}catch(u){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new wf(this.observer,a,s,"",t,e.logger)}return}}this.transmuxer=new wf(this.observer,a,s,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Rf++;const t=this.hls.config,i=od(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:rt(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),vB(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,n,s,o,a,l,A,u){var c,h;A.transmuxing.start=self.performance.now();const{instanceNo:d,transmuxer:f}=this,g=o?o.start:s.start,p=s.decryptdata,v=this.frag,B=!(v&&s.cc===v.cc),C=!(v&&A.level===v.level),y=v?A.sn-v.sn:-1,x=this.part?A.part-this.part.index:-1,w=y===0&&A.id>1&&A.id===(v==null?void 0:v.stats.chunkCount),D=!C&&(y===1||y===0&&(x===1||w&&x<=0)),F=self.performance.now();(C||y||s.stats.parsing.start===0)&&(s.stats.parsing.start=F),o&&(x||!D)&&(o.stats.parsing.start=F);const O=!(v&&((c=s.initSegment)==null?void 0:c.url)===((h=v.initSegment)==null?void 0:h.url)),M=new fT(B,D,l,C,g,O);if(!D||B||O){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${A.sn}${A.part>-1?" part: "+A.part:""} ${this.id===Ee.MAIN?"level":"track"}: ${A.level} id: ${A.id}
2500
+ ${t.m3u8}`)}function Wd(r,e,t=!0){const i=e.startSN+e.skippedSegments-r.startSN,n=r.fragments,s=i>=0;let o=0;if(s&&i<n.length)o=n[i].start;else if(s&&e.startSN===r.endSN+1)o=r.fragmentEnd;else if(s&&t)o=r.fragmentStart+i*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=r.fragmentStart;else return;Vl(e,o)}function Vl(r,e){if(e){const t=r.fragments;for(let i=r.skippedSegments;i<t.length;i++)t[i].addStart(e);r.fragmentHint&&r.fragmentHint.addStart(e)}}function qd(r,e=1/0){let t=1e3*r.targetduration;if(r.updated){const i=r.fragments;if(i.length&&t*4>e){const s=i[i.length-1].duration*1e3;s<t&&(t=s)}}else t/=2;return Math.round(t)}function Jd(r,e,t){if(!r)return null;let i=r.fragments[e-r.startSN];return i||(i=r.fragmentHint,i&&i.sn===e)?i:e<r.startSN&&t&&t.sn===e?t:null}function jd(r,e,t){return r?Xd(r.partList,e,t):null}function Xd(r,e,t){if(r)for(let i=r.length;i--;){const n=r[i];if(n.index===t&&n.fragment.sn===e)return n}return null}function zd(r){r.forEach((e,t)=>{var i;(i=e.details)==null||i.fragments.forEach(n=>{n.level=t,n.initSegment&&(n.initSegment.level=t)})})}function Yn(r,e){for(let i=0,n=r.length;i<n;i++){var t;if(((t=r[i])==null?void 0:t.cc)===e)return r[i]}return null}function uB(r,e){return!!(r&&e.startCC<r.endCC&&e.endCC>r.startCC)}function Zd(r,e){if(r){const t=r.start+e;r.start=r.startPTS=t,r.endPTS=t+r.duration}}function ef(r,e){const t=e.fragments;for(let i=0,n=t.length;i<n;i++)Zd(t[i],r);e.fragmentHint&&Zd(e.fragmentHint,r),e.alignedSliding=!0}function hB(r,e){r&&(tf(e,r),!e.alignedSliding&&r&&xo(e,r),!e.alignedSliding&&r&&!e.skippedSegments&&Wd(r,e,!1))}function tf(r,e){if(!uB(e,r))return;const t=Math.min(e.endCC,r.endCC),i=Yn(e.fragments,t),n=Yn(r.fragments,t);if(!i||!n)return;Ue.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const s=i.start-n.start;ef(s,r)}function xo(r,e){if(!r.hasProgramDateTime||!e.hasProgramDateTime)return;const t=r.fragments,i=e.fragments;if(!t.length||!i.length)return;let n,s;const o=Math.min(e.endCC,r.endCC);e.startCC<o&&r.startCC<o&&(n=Yn(i,o),s=Yn(t,o)),(!n||!s)&&(n=i[Math.floor(i.length/2)],s=Yn(t,n.cc)||t[Math.floor(t.length/2)]);const a=n.programDateTime,l=s.programDateTime;if(!a||!l)return;const A=(l-a)/1e3-(s.start-n.start);ef(A,r)}const dB={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}},Z={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 Kl extends Sd{constructor(e,t,i,n,s){super(n,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Z.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.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.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:o,fragCurrent:a,media:l,mediaBuffer:A,state:u}=this,c=l?l.currentTime:0,h=Le.bufferInfo(A||l,c,o.maxBufferHole);if(this.log(`media seeking to ${de(c)?c.toFixed(3):c}, state: ${u}`),this.state===Z.ENDED)this.resetLoadingState();else if(a){const d=o.maxFragLookUpTolerance,f=a.start-d,g=a.start+a.duration+d;if(!h.len||g<h.start||f>h.end){const p=c>g;(c<f||p)&&(p&&a.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),a.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0);const d=this.lastCurrentTime;if(c>d&&(this.lastCurrentTime=c),!this.loadingParts){const f=Math.max(h.end,c),g=this.shouldLoadParts(this.getLevelDetails(),f);g&&(this.log(`LL-Part loading ON after seeking to ${c.toFixed(2)} with buffer @${f.toFixed(2)}`),this.loadingParts=g)}}!this.hls.hasEnoughToStart&&!h.len&&(this.log(`setting startPosition to ${c} because of seek before start`),this.nextLoadPosition=this.startPosition=c),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=s,this.hls=e,this.fragmentLoader=new GC(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ll(e.config)}registerListeners(){const{hls:e}=this;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Z.STOPPED)return;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=Z.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,n=this.config.timelineOffset||0;if(i<=n)return!1;const s=e.nextStart;if(s&&s>n&&s<t.edge||this.media.currentTime<e.start)return!1;const a=t.partList;if(a!=null&&a.length){const A=a[a.length-1];return Le.isBuffered(this.media,A.start+A.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levelLastLoaded)==null?void 0:e.details}}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("ended",this.onMediaEnded),i.addEventListener("seeking",this.onMediaSeeking),i.addEventListener("ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===Z.STOPPED&&this.startLoad(n.startPosition)}onMediaDetaching(e,t){const i=!!t.transferMedia,n=this.media;if(n!==null){if(n.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),n.removeEventListener("seeking",this.onMediaSeeking),n.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Z.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const n=s=>{const o=s.frag;if(this.fragContextChanged(o)){this.warn(`${o.type} sn: ${o.sn}${s.part?" part: "+s.part.index:""} of ${this.fragInfo(o,!1,s.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(o);return}o.stats.chunkCount++,this._handleFragmentLoadProgress(s)};this._doFragLoad(e,t,i,n).then(s=>{if(!s)return;const o=this.state,a=s.frag;if(this.fragContextChanged(a)){(o===Z.FRAG_LOADING||!this.fragCurrent&&o===Z.PARSING)&&(this.fragmentTracker.removeFragment(a),this.state=Z.IDLE);return}"payload"in s&&(this.log(`Loaded ${a.type} sn: ${a.sn} of ${this.playlistLabel()} ${a.level}`),this.hls.trigger(I.FRAG_LOADED,s)),this._handleFragmentLoadComplete(s)}).catch(s=>{this.state===Z.STOPPED||this.state===Z.ERROR||(this.warn(`Frag error: ${(s==null?void 0:s.message)||s}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===vt.APPENDING){const s=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,s),a=Math.max(e.duration,o?o.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(a,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===vt.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:i};this.hls.trigger(I.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{const n=i==null?void 0:i.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:n}=this,{frag:s,payload:o}=i,a=s.decryptdata;if(o&&o.byteLength>0&&a!=null&&a.key&&a.iv&&Hr(a.method)){const l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(o),a.key.buffer,a.iv.buffer,Fl(a.method)).catch(A=>{throw n.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_DECRYPT_ERROR,fatal:!1,error:A,reason:A.message,frag:s}),A}).then(A=>{const u=self.performance.now();return n.trigger(I.FRAG_DECRYPTED,{frag:s,payload:A,stats:{tstart:l,tdecrypt:u}}),i.payload=A,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===Z.STOPPED||this.state===Z.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==Z.STOPPED&&(this.state=Z.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?dB.toString(Le.getBuffered(i)):"(detached)"})`),Ct(e)){var n;if(e.type!==Ee.SUBTITLE){const o=e.elementaryStreams;if(!Object.keys(o).some(a=>!!o[a])){this.state=Z.IDLE;return}}const s=(n=this.levels)==null?void 0:n[e.level];s!=null&&s.fragmentError&&(this.log(`Resetting level fragment error count of ${s.fragmentError} on frag buffered`),s.fragmentError=0)}this.state=Z.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:n,partsLoaded:s}=e,o=!s||s.length===0||s.some(l=>!l),a=new kl(i.level,i.sn,i.stats.chunkCount+1,0,n?n.index:-1,!o);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,n){var s;this.fragCurrent=e;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;e.encrypted&&!((s=e.decryptdata)!=null&&s.key)?(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Z.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then(c=>{if(!this.fragContextChanged(c.frag))return this.hls.trigger(I.KEY_LOADED,c),this.state===Z.KEY_LOADING&&(this.state=Z.IDLE),c}),this.hls.trigger(I.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);const l=this.fragPrevious;if(Ct(e)&&(!l||e.sn!==l.sn)){const c=this.shouldLoadParts(t.details,e.end);c!==this.loadingParts&&(this.log(`LL-Part loading ${c?"ON":"OFF"} loading sn ${l==null?void 0:l.sn}->${e.sn}`),this.loadingParts=c)}if(i=Math.max(e.start,i||0),this.loadingParts&&Ct(e)){const c=o.partList;if(c&&n){i>e.end&&o.fragmentHint&&(e=o.fragmentHint);const h=this.getNextPart(c,e,i);if(h>-1){const d=c[h];e=this.fragCurrent=d.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${d.index} (${h}/${c.length-1}) of ${this.fragInfo(e,!1,d)}) cc: ${e.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=d.start+d.duration,this.state=Z.FRAG_LOADING;let f;return a?f=a.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,d,t,n)).catch(g=>this.handleFragLoadError(g)):f=this.doFragPartsLoad(e,d,t,n).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(I.FRAG_LOADING,{frag:e,part:d,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(c,i))return Promise.resolve(null)}}if(Ct(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${o?"["+o.startSN+"-"+o.endSN+"]":""}, target: ${parseFloat(i.toFixed(3))}`),de(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Z.FRAG_LOADING;const A=this.config.progressive;let u;return A&&a?u=a.then(c=>!c||this.fragContextChanged(c==null?void 0:c.frag)?null:this.fragmentLoader.load(e,n)).catch(c=>this.handleFragLoadError(c)):u=Promise.all([this.fragmentLoader.load(e,A?n:void 0),a]).then(([c])=>(!A&&c&&n&&n(c),c)).catch(c=>this.handleFragLoadError(c)),this.hls.trigger(I.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,i,n){return new Promise((s,o)=>{var a;const l=[],A=(a=i.details)==null?void 0:a.partList,u=c=>{this.fragmentLoader.loadPart(e,c,n).then(h=>{l[c.index]=h;const d=h.part;this.hls.trigger(I.FRAG_LOADED,h);const f=jd(i.details,e.sn,c.index+1)||Xd(A,e.sn,c.index+1);if(f)u(f);else return s({frag:e,part:d,partsLoaded:l})}).catch(o)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===V.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(I.ERROR,t)}else this.hls.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Z.PARSING){!this.fragCurrent&&this.state!==Z.STOPPED&&this.state!==Z.ERROR&&(this.state=Z.IDLE);return}const{frag:i,part:n,level:s}=t,o=self.performance.now();i.stats.parsing.end=o,n&&(n.stats.parsing.end=o);const a=this.getLevelDetails(),A=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);A!==this.loadingParts&&(this.log(`LL-Part loading ${A?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=A),this.updateLevelTiming(i,n,s,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e!=null&&e.partList){var i;const s=e.partList[0],o=s.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=o){var n;if((this.hls.hasEnoughToStart?((n=this.media)==null?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:n,sn:s,part:o}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const a=t[n],l=a.details,A=o>-1?jd(l,s,o):null,u=A?A.fragment:Jd(l,s,i);return u?(i&&i!==u&&(u.stats=i.stats),{frag:u,part:A,level:a}):null}bufferFragmentData(e,t,i,n,s){var o;if(!e||this.state!==Z.PARSING)return;const{data1:a,data2:l}=e;let A=a;if(a&&l&&(A=Jt(a,l)),!((o=A)!=null&&o.length))return;const u={type:e.type,frag:t,part:i,chunkMeta:n,parent:t.type,data:A};if(this.hls.trigger(I.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Le.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,n=Le.bufferInfo(t,i,0),s=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,s*.25),a=Math.max(Math.min(e.start-o,n.end-o),i+o);e.start-a>o&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var i;const n=this.getLoadPosition();if(!de(n))return null;const o=this.lastCurrentTime>n||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,o)}getFwdBufferInfoAtPos(e,t,i,n){const s=Le.bufferInfo(e,t,n);if(s.len===0&&s.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(t,i);if(o&&(s.nextStart<=o.end||o.gap)){const a=Math.max(Math.min(s.nextStart,o.end)-t,n);return Le.bufferInfo(e,t,a)}}return s}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,t){const i=this.config,n=Math.max(Math.min(e-t,i.maxBufferLength),t),s=Math.max(e-t*3,i.maxMaxBufferLength/2,n);return s>=n?(i.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0):!1}getAppendedFrag(e,t=Ee.MAIN){var i;const n=(i=this.fragmentTracker)==null?void 0:i.getAppendedFrag(e,t);return n&&"fragment"in n?n.fragment:n}getNextFragment(e,t){const i=t.fragments,n=i.length;if(!n)return null;const{config:s}=this,o=i[0].start,a=s.lowLatencyMode&&!!t.partList;let l=null;if(t.live){const c=s.initialLiveManifestSize;if(n<c)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${c})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<o){var A;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(t,i);const h=this.hls.startPosition,d=this.hls.liveSyncPosition,f=l?(h!==-1&&h>=o?h:d)||l.start:e;this.log(`Setting startPosition to ${f} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${d} frag.start: ${(A=l)==null?void 0:A.start}`),this.startPosition=this.nextLoadPosition=f}}else e<=o&&(l=i[0]);if(!l){const c=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,c,t)}let u=this.filterReplacedPrimary(l,t);if(!u&&l){const c=l.sn-t.startSN;u=this.filterReplacedPrimary(i[c+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===vt.OK||i===vt.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,n,s){let o=null;if(e.gap&&(o=this.getNextFragment(this.nextLoadPosition,t),o&&!o.gap&&i.nextStart)){const a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,n,0);if(a!==null&&i.len+a.len>=s){const l=o.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,o}get primaryPrefetch(){if(rf(this.hls.config)){var e,t;if((e=this.hls.interstitialsManager)==null||(t=e.playingItem)==null?void 0:t.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(rf(this.hls.config)&&e.type!==Ee.SUBTITLE){const i=this.hls.interstitialsManager,n=i==null?void 0:i.bufferingItem;if(n){const o=n.event;if(o){if(o.appendInPlace||Math.abs(e.start-n.start)>1||n.start===0)return null}else if(e.end<=n.start&&(t==null?void 0:t.live)===!1||e.start>n.end&&n.nextEvent&&(n.nextEvent.appendInPlace||e.start-n.end>1))return null}const s=i==null?void 0:i.playerQueue;if(s)for(let o=s.length;o--;){const a=s[o].interstitial;if(a.appendInPlace&&e.start>=a.startTime&&e.end<=a.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let n=-1,s=!1,o=!0;for(let a=0,l=e.length;a<l;a++){const A=e[a];if(o=o&&!A.independent,n>-1&&i<A.start)break;const u=A.loaded;u?n=-1:(s||A.independent||o)&&A.fragment===t&&(n=a),s=u}return n}loadedEndOfParts(e,t){const i=e[e.length-1];return i&&t>i.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let n=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),n=QC(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const s=i.sn+1;if(s>=e.startSN&&s<=e.endSN){const o=t[s-e.startSN];i.cc===o.cc&&(n=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=Id(t,i.cc),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const s=this.hls.liveSyncPosition;s!==null&&(n=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,i){const{config:n}=this;let{fragPrevious:s}=this,{fragments:o,endSN:a}=i;const{fragmentHint:l}=i,{maxFragLookUpTolerance:A}=n,u=i.partList,c=!!(this.loadingParts&&u!=null&&u.length&&l);c&&l&&!this.bitrateTest&&u[u.length-1].fragment.sn===l.sn&&(o=o.concat(l),a=l.sn);let h;if(e<t){var d;const g=e<this.lastCurrentTime||e>t-A||(d=this.media)!=null&&d.paused||!this.startFragRequested?0:A;h=Br(s,o,e,g)}else h=o[o.length-1];if(h){const f=h.sn-i.startSN,g=this.fragmentTracker.getState(h);if((g===vt.OK||g===vt.PARTIAL&&h.gap)&&(s=h),s&&h.sn===s.sn&&(!c||u[0].fragment.sn>h.sn||!i.live&&!c)&&s&&h.level===s.level){const v=o[f+1];h.sn<a&&this.fragmentTracker.getState(v)!==vt.OK?h=v:h=null}}return h}alignPlaylists(e,t,i){const n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const s=e.fragmentStart,o=!t,a=e.alignedSliding&&de(s);if(o||!a&&!s){hB(i,e);const l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${n}`),l}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);const n=this.timelineOffset;if(i===-1){const s=this.startTimeOffset!==null,o=s?this.startTimeOffset:e.startTimeOffset;o!==null&&de(o)?(i=t+o,o<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${o} found in ${s?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+n}this.nextLoadPosition=i+n}getLoadPosition(){var e;const{media:t}=this;let i=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ct(e)&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==Z.FRAG_LOADING_WAITING_RETRY)&&(this.state=Z.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const f=this.getCurrentContext(t.chunkMeta);f&&(t.frag=f.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var n;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}const s=t.details===V.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction,{action:a,flags:l,retryCount:A=0,retryConfig:u}=o||{},c=!!o&&!!u,h=c&&a===Rt.RetryRequest,d=c&&!o.resolved&&l===ni.MoveAllAlternatesMatchingHost;if(!h&&d&&Ct(i)&&!i.endList)this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((h||d)&&A<u.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const f=Dl(u,A);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${A+1}/${u.maxNumRetry} in ${f}ms`),o.resolved=!0,this.retryDate=self.performance.now()+f,this.state=Z.FRAG_LOADING_WAITING_RETRY}else if(u&&o)if(this.resetFragmentErrors(e),A<u.maxNumRetry)!s&&a!==Rt.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${A})`);return}else a===Rt.SendAlternateToPenaltyBox?this.state=Z.WAITING_LEVEL:this.state=Z.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===Z.PARSING||this.state===Z.PARSED){const t=e.frag,i=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,i),s=n&&n.len>.5;s&&this.reduceMaxBufferLength(n.len,(t==null?void 0:t.duration)||10);const o=!s;return o&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),o}return!1}resetFragmentErrors(e){e===Ee.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Z.STOPPED&&(this.state=Z.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const n=Le.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,i),this.state===Z.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Z.STOPPED&&(this.state=Z.IDLE)}resetStartWhenNotLoaded(e){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of ${this.playlistLabel()} ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,n){const s=i.details;if(!s){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,A)=>{const u=e.elementaryStreams[A];if(u){const c=u.endPTS-u.startPTS;if(c<=0)return this.warn(`Could not parse fragment ${e.sn} ${A} duration reliably (${c})`),l||!1;const h=n?0:Vd(s,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS);return this.hls.trigger(I.LEVEL_PTS_UPDATED,{details:s,level:i,drift:h,type:A,frag:e,start:u.startPTS,end:u.endPTS}),!0}return l},!1)){var a;if(i.fragmentError===0&&this.treatAsGap(e,i),((a=this.transmuxer)==null?void 0:a.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Z.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(I.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===Ee.MAIN?"level":"track"}fragInfo(e,t=!0,i){var n,s;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((n=t&&!i?e.startPTS:(i||e).start)!=null?n:NaN).toFixed(3)}-${((s=t&&!i?e.endPTS:(i||e).end)!=null?s:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function rf(r){return!!r.interstitialsController&&r.enableInterstitialPlayback!==!1}class nf{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=fB(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function fB(r,e){const t=new Uint8Array(e);let i=0;for(let n=0;n<r.length;n++){const s=r[n];t.set(s,i),i+=s.length}return t}var Wl={exports:{}},sf;function gB(){return sf||(sf=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function n(l,A,u){this.fn=l,this.context=A,this.once=u||!1}function s(l,A,u,c,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var d=new n(u,c||l,h),f=t?t+A:A;return l._events[f]?l._events[f].fn?l._events[f]=[l._events[f],d]:l._events[f].push(d):(l._events[f]=d,l._eventsCount++),l}function o(l,A){--l._eventsCount===0?l._events=new i:delete l._events[A]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var A=[],u,c;if(this._eventsCount===0)return A;for(c in u=this._events)e.call(u,c)&&A.push(t?c.slice(1):c);return Object.getOwnPropertySymbols?A.concat(Object.getOwnPropertySymbols(u)):A},a.prototype.listeners=function(A){var u=t?t+A:A,c=this._events[u];if(!c)return[];if(c.fn)return[c.fn];for(var h=0,d=c.length,f=new Array(d);h<d;h++)f[h]=c[h].fn;return f},a.prototype.listenerCount=function(A){var u=t?t+A:A,c=this._events[u];return c?c.fn?1:c.length:0},a.prototype.emit=function(A,u,c,h,d,f){var g=t?t+A:A;if(!this._events[g])return!1;var p=this._events[g],v=arguments.length,B,C;if(p.fn){switch(p.once&&this.removeListener(A,p.fn,void 0,!0),v){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,u),!0;case 3:return p.fn.call(p.context,u,c),!0;case 4:return p.fn.call(p.context,u,c,h),!0;case 5:return p.fn.call(p.context,u,c,h,d),!0;case 6:return p.fn.call(p.context,u,c,h,d,f),!0}for(C=1,B=new Array(v-1);C<v;C++)B[C-1]=arguments[C];p.fn.apply(p.context,B)}else{var y=p.length,x;for(C=0;C<y;C++)switch(p[C].once&&this.removeListener(A,p[C].fn,void 0,!0),v){case 1:p[C].fn.call(p[C].context);break;case 2:p[C].fn.call(p[C].context,u);break;case 3:p[C].fn.call(p[C].context,u,c);break;case 4:p[C].fn.call(p[C].context,u,c,h);break;default:if(!B)for(x=1,B=new Array(v-1);x<v;x++)B[x-1]=arguments[x];p[C].fn.apply(p[C].context,B)}}return!0},a.prototype.on=function(A,u,c){return s(this,A,u,c,!1)},a.prototype.once=function(A,u,c){return s(this,A,u,c,!0)},a.prototype.removeListener=function(A,u,c,h){var d=t?t+A:A;if(!this._events[d])return this;if(!u)return o(this,d),this;var f=this._events[d];if(f.fn)f.fn===u&&(!h||f.once)&&(!c||f.context===c)&&o(this,d);else{for(var g=0,p=[],v=f.length;g<v;g++)(f[g].fn!==u||h&&!f[g].once||c&&f[g].context!==c)&&p.push(f[g]);p.length?this._events[d]=p.length===1?p[0]:p:o(this,d)}return this},a.prototype.removeAllListeners=function(A){var u;return A?(u=t?t+A:A,this._events[u]&&o(this,u)):(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}(Wl)),Wl.exports}var pB=gB(),ql=Yy(pB);const Vn="1.6.2",Yr={};function mB(){return typeof __HLS_WORKER_BUNDLE__=="function"}function EB(){const r=Yr[Vn];if(r)return r.clientCount++,r;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),n={worker:new self.Worker(t),objectURL:t,clientCount:1};return Yr[Vn]=n,n}function IB(r){const e=Yr[r];if(e)return e.clientCount++,e;const t=new self.URL(r,self.location.href).href,n={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Yr[r]=n,n}function vB(r){const e=Yr[r||Vn];if(e&&e.clientCount--===1){const{worker:i,objectURL:n}=e;delete Yr[r||Vn],n&&self.URL.revokeObjectURL(n),i.terminate()}}function of(r,e){return 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}function Jl(r,e){return 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}function Qo(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}function Kn(r,e){const t=e;let i=0;for(;Jl(r,e);){i+=10;const n=Qo(r,e+6);i+=n,of(r,e+10)&&(i+=10),e+=i}if(i>0)return r.subarray(t,t+i)}function yB(r,e,t,i){const n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],s=e[t+2],o=s>>2&15;if(o>12){const d=new Error(`invalid ADTS sampling index:${o}`);r.emit(I.ERROR,I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!0,error:d,reason:d.message});return}const a=(s>>6&3)+1,l=e[t+3]>>6&3|(s&1)<<2,A="mp4a.40."+a,u=n[o];let c=o;(a===5||a===29)&&(c-=3);const h=[a<<3|(c&14)>>1,(c&1)<<7|l<<3];return Ue.log(`manifest codec:${i}, parsed codec:${A}, channels:${l}, rate:${u} (ADTS object type:${a} sampling index:${o})`),{config:h,samplerate:u,channelCount:l,codec:A,parsedCodec:A,manifestCodec:i}}function af(r,e){return r[e]===255&&(r[e+1]&246)===240}function lf(r,e){return r[e+1]&1?7:9}function jl(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function CB(r,e){return e+5<r.length}function _o(r,e){return e+1<r.length&&af(r,e)}function BB(r,e){return CB(r,e)&&af(r,e)&&jl(r,e)<=r.length-e}function TB(r,e){if(_o(r,e)){const t=lf(r,e);if(e+t>=r.length)return!1;const i=jl(r,e);if(i<=t)return!1;const n=e+i;return n===r.length||_o(r,n)}return!1}function Af(r,e,t,i,n){if(!r.samplerate){const s=yB(e,t,i,n);if(!s)return;qe(r,s)}}function cf(r){return 9216e4/r}function bB(r,e){const t=lf(r,e);if(e+t<=r.length){const i=jl(r,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function uf(r,e,t,i,n){const s=cf(r.samplerate),o=i+n*s,a=bB(e,t);let l;if(a){const{frameLength:c,headerLength:h}=a,d=h+c,f=Math.max(0,t+d-e.length);f?(l=new Uint8Array(d-h),l.set(e.subarray(t+h,e.length),0)):l=e.subarray(t+h,t+d);const g={unit:l,pts:o};return f||r.samples.push(g),{sample:g,length:d,missing:f}}const A=e.length-t;return l=new Uint8Array(A),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:o},length:A,missing:-1}}function SB(r,e){return Jl(r,e)&&Qo(r,e+6)+10<=r.length-e}function xB(r){if(r.size<2)return;const e=$t(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}}function QB(r){if(r.size<2)return;if(r.type==="TXXX"){let t=1;const i=$t(r.data.subarray(t),!0);t+=i.length+1;const n=$t(r.data.subarray(t));return{key:r.type,info:i,data:n}}const e=$t(r.data.subarray(1));return{key:r.type,info:"",data:e}}function _B(r){if(r.type==="WXXX"){if(r.size<2)return;let t=1;const i=$t(r.data.subarray(t),!0);t+=i.length+1;const n=$t(r.data.subarray(t));return{key:r.type,info:i,data:n}}const e=$t(r.data);return{key:r.type,info:"",data:e}}function wB(r){return btoa(String.fromCharCode(...r))}function hf(r,e){if(r<0)return-hf(-r,e);const t=Math.pow(10,e);if(Math.abs(r*t%1-.5)<Number.EPSILON){const n=Math.floor(r*t);return(n%2===0?n:n+1)/t}else return Math.round(r*t)/t}function RB(r,e){const t=new URL(r),i=new URL(e);if(t.origin!==i.origin)return r;const n=t.pathname.split("/").slice(1),s=i.pathname.split("/").slice(1,-1);for(;n[0]===s[0];)n.shift(),s.shift();for(;s.length;)s.shift(),n.unshift("..");return n.join("/")}function DB(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const s=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(n=="x"?s:s&3|8).toString(16)})}}}function LB(r){return r instanceof ArrayBuffer?r:r.byteOffset==0&&r.byteLength==r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer}function Xl(r,e=0,t=1/0){return kB(r,e,t,Uint8Array)}function kB(r,e,t,i){const n=MB(r);let s=1;"BYTES_PER_ELEMENT"in i&&(s=i.BYTES_PER_ELEMENT);const o=FB(r)?r.byteOffset:0,a=(o+r.byteLength)/s,l=(o+e)/s,A=Math.floor(Math.max(0,Math.min(l,a))),u=Math.floor(Math.min(A+Math.max(t,0),a));return new i(n,A,u-A)}function MB(r){return r instanceof ArrayBuffer?r:r.buffer}function FB(r){return r&&r.buffer instanceof ArrayBuffer&&r.byteLength!==void 0&&r.byteOffset!==void 0}function PB(r){const e={key:r.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(r.size<2)return;if(r.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const i=r.data.subarray(1).indexOf(0);if(i===-1)return;const n=$t(Xl(r.data,1,i)),s=r.data[2+i],o=r.data.subarray(3+i).indexOf(0);if(o===-1)return;const a=$t(Xl(r.data,3+i,o));let l;return n==="-->"?l=$t(Xl(r.data,4+i+o)):l=LB(r.data.subarray(4+i+o)),e.mimeType=n,e.pictureType=s,e.description=a,e.data=l,e}function NB(r){return r.type==="PRIV"?xB(r):r.type[0]==="W"?_B(r):r.type==="APIC"?PB(r):QB(r)}function OB(r){const e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=Qo(r,4),i=10;return{type:e,size:t,data:r.subarray(i,i+t)}}const wo=10,UB=10;function df(r){let e=0;const t=[];for(;Jl(r,e);){const i=Qo(r,e+6);r[e+5]>>6&1&&(e+=wo),e+=wo;const n=e+i;for(;e+UB<n;){const s=OB(r.subarray(e)),o=NB(s);o&&t.push(o),e+=s.size+wo}of(r,e)&&(e+=wo)}return t}function ff(r){return r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp"}function GB(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)}}function zl(r){const e=df(r);for(let t=0;t<e.length;t++){const i=e[t];if(ff(i))return GB(i)}}let Ht=function(r){return r.audioId3="org.id3",r.dateRange="com.apple.quicktime.HLS",r.emsg="https://aomedia.org/emsg/ID3",r.misbklv="urn:misb:KLV:bin:1910.1",r}({});function pi(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Zl{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,n){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=Jt(this.cachedData,e),this.cachedData=null);let i=Kn(e,0),n=i?i.length:0,s;const o=this._audioTrack,a=this._id3Track,l=i?zl(i):void 0,A=e.length;for((this.basePTS===null||this.frameIndex===0&&de(l))&&(this.basePTS=$B(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:Ht.audioId3,duration:Number.POSITIVE_INFINITY});n<A;){if(this.canParse(e,n)){const u=this.appendFrame(o,e,n);u?(this.frameIndex++,this.lastPTS=u.sample.pts,n+=u.length,s=n):n=A}else SB(e,n)?(i=Kn(e,n),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Ht.audioId3,duration:Number.POSITIVE_INFINITY}),n+=i.length,s=n):n++;if(n===A&&s!==A){const u=e.slice(s);this.cachedData?this.cachedData=Jt(this.cachedData,u):this.cachedData=u}}return{audioTrack:o,videoTrack:pi(),id3Track:a,textTrack:pi()}}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:pi(),id3Track:this._id3Track,textTrack:pi()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const $B=(r,e,t)=>{if(de(r))return r*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};let Ro=null;const HB=[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],YB=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],VB=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],KB=[0,1,1,4];function gf(r,e,t,i,n){if(t+24>e.length)return;const s=pf(e,t);if(s&&t+s.frameLength<=e.length){const o=s.samplesPerFrame*9e4/s.sampleRate,a=i+n*o,l={unit:e.subarray(t,t+s.frameLength),pts:a,dts:a};return r.config=[],r.channelCount=s.channelCount,r.samplerate=s.sampleRate,r.samples.push(l),{sample:l,length:s.frameLength,missing:0}}}function pf(r,e){const t=r[e+1]>>3&3,i=r[e+1]>>1&3,n=r[e+2]>>4&15,s=r[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&s!==3){const o=r[e+2]>>1&1,a=r[e+3]>>6,l=t===3?3-i:i===3?3:4,A=HB[l*14+n-1]*1e3,c=YB[(t===3?0:t===2?1:2)*3+s],h=a===3?1:2,d=VB[t][i],f=KB[i],g=d*8*f,p=Math.floor(d*A/c+o)*f;if(Ro===null){const C=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ro=C?parseInt(C[1]):0}return!!Ro&&Ro<=87&&i===2&&A>=224e3&&a===0&&(r[e+3]=r[e+3]|128),{sampleRate:c,channelCount:h,frameLength:p,samplesPerFrame:g}}}function eA(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function mf(r,e){return e+1<r.length&&eA(r,e)}function WB(r,e){return eA(r,e)&&4<=r.length-e}function Ef(r,e){if(e+1<r.length&&eA(r,e)){const i=pf(r,e);let n=4;i!=null&&i.frameLength&&(n=i.frameLength);const s=e+n;return s===r.length||mf(r,s)}return!1}class qB extends Zl{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const i=Kn(e,0);let n=(i==null?void 0:i.length)||0;if(Ef(e,n))return!1;for(let s=e.length;n<s;n++)if(TB(e,n))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return BB(e,t)}appendFrame(e,t,i){Af(e,this.observer,t,i,e.manifestCodec);const n=uf(e,t,i,this.basePTS,this.frameIndex);if(n&&n.missing===0)return n}}const If=(r,e)=>{let t=0,i=5;e+=i;const n=new Uint32Array(1),s=new Uint32Array(1),o=new Uint8Array(1);for(;i>0;){o[0]=r[e];const a=Math.min(i,8),l=8-a;s[0]=4278190080>>>24+l<<l,n[0]=(o[0]&s[0])>>l,t=t?t<<a|n[0]:n[0],e+=1,i-=a}return t};class JB extends Zl{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const n=vf(e,t,i,this.basePTS,this.frameIndex);if(n!==-1)return{sample:e.samples[e.samples.length-1],length:n,missing:0}}static probe(e){if(!e)return!1;const t=Kn(e,0);if(!t)return!1;const i=t.length;return e[i]===11&&e[i+1]===119&&zl(t)!==void 0&&If(e,i)<16}}function vf(r,e,t,i,n){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const s=e[t+4]>>6;if(s>=3)return-1;const a=[48e3,44100,32e3][s],l=e[t+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+s]*2;if(t+u>e.length)return-1;const c=e[t+6]>>5;let h=0;c===2?h+=2:(c&1&&c!==1&&(h+=2),c&4&&(h+=2));const d=(e[t+6]<<8|e[t+7])>>12-h&1,g=[2,1,2,3,3,4,4,5][c]+d,p=e[t+5]>>3,v=e[t+5]&7,B=new Uint8Array([s<<6|p<<1|v>>2,(v&3)<<6|c<<3|d<<2|l>>4,l<<4&224]),C=1536/a*9e4,y=i+n*C,x=e.subarray(t,t+u);return r.config=B,r.channelCount=g,r.samplerate=a,r.samples.push({unit:x,pts:y}),u}class jB extends Zl{resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Kn(e,0);let i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&zl(t)!==void 0&&If(e,i)<=16)return!1;for(let n=e.length;i<n;i++)if(Ef(e,i))return Ue.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return WB(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return gf(e,t,i,this.basePTS,this.frameIndex)}}const XB=/\/emsg[-/]ID3/i;class zB{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,n){const s=this.videoTrack=pi("video",1),o=this.audioTrack=pi("audio",1),a=this.txtTrack=pi("text",1);if(this.id3Track=pi("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=zh(e);if(l.video){const{id:A,timescale:u,codec:c,supplemental:h}=l.video;s.id=A,s.timescale=a.timescale=u,s.codec=c,s.supplemental=h}if(l.audio){const{id:A,timescale:u,codec:c}=l.audio;o.id=A,o.timescale=u,o.codec=c}a.id=qh.text,s.sampleDuration=0,s.duration=o.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return Jy(e)}demux(e,t){this.timeOffset=t;let i=e;const n=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Jt(this.remainderData,e));const a=rC(i);this.remainderData=a.remainder,n.samples=a.valid||new Uint8Array}else n.samples=i;const o=this.extractID3Track(n,t);return s.samples=ed(t,n),{videoTrack:n,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 n=this.extractID3Track(t,this.timeOffset);return i.samples=ed(e,t),{videoTrack:t,audioTrack:pi(),id3Track:n,textTrack:pi()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const n=we(e.samples,["emsg"]);n&&n.forEach(s=>{const o=sC(s);if(XB.test(o.schemeIdUri)){const a=yf(o,t);let l=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const A=o.payload;i.samples.push({data:A,len:A.byteLength,dts:a,pts:a,type:Ht.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata&&o.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const a=yf(o,t);i.samples.push({data:o.payload,len:o.payload.byteLength,dts:a,pts:a,type:Ht.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function yf(r,e){return de(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale}class ZB{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Ll(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,er.cbc)}decryptAacSample(e,t,i){const n=e[t].unit;if(n.length<=16)return;const s=n.subarray(16,n.length-n.length%16),o=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(o).then(a=>{const l=new Uint8Array(a);n.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 n=0;for(let s=32;s<e.length-16;s+=160,n+=16)i.set(e.subarray(s,s+16),n);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let n=0;for(let s=32;s<e.length-16;s+=160,n+=16)e.set(i.subarray(n,n+16),s);return e}decryptAvcSample(e,t,i,n,s){const o=td(s.data),a=this.getAvcEncryptedData(o);this.decryptBuffer(a.buffer).then(l=>{s.data=this.getAvcDecryptedUnit(o,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,n)})}decryptAvcSamples(e,t,i,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){n();return}const s=e[t].units;for(;!(i>=s.length);i++){const o=s[i];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,t,i,n,o),!this.decrypter.isSync()))return}}}}class Cf{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,n;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const s=i.units;n=s[s.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,n=i.length;if(n){const s=i[n-1];e.pts=s.pts,e.dts=s.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){const n=t.byteLength;let s=e.naluState||0;const o=s,a=[];let l=0,A,u,c,h=-1,d=0;for(s===-1&&(h=0,d=this.getNALuType(t,0),s=0,l=1);l<n;){if(A=t[l++],!s){s=A?0:1;continue}if(s===1){s=A?0:2;continue}if(!A)s=3;else if(A===1){if(u=l-s-1,h>=0){const f={data:t.subarray(h,u),type:d};a.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(o&&l<=4-o&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-o)),u>0&&(f.data=Jt(f.data,t.subarray(0,u)),f.state=0))}l<n?(c=this.getNALuType(t,l),h=l,d=c,s=0):s=-1}else s=0}if(h>=0&&s>=0){const f={data:t.subarray(h,n),type:d,state:s};a.push(f)}if(a.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=Jt(f.data,t))}return e.naluState=s,a}}class Wn{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,n=new Uint8Array(4),s=Math.min(4,t);if(s===0)throw new Error("no bytes available");n.set(e.subarray(i,i+s)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=s*8,this.bytesAvailable-=s}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&&Ue.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)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)}}class Bf extends Cf{parsePES(e,t,i,n){const s=this.parseNALu(e,i.data,n);let o=this.VideoSample,a,l=!1;i.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach(A=>{var u,c;switch(A.type){case 1:{let g=!1;a=!0;const p=A.data;if(l&&p.length>4){const v=this.readSliceType(p);(v===2||v===4||v===7||v===9)&&(g=!0)}if(g){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.frame=!0,o.key=g;break}case 5:a=!0,(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:{a=!0,xl(A.data,1,i.pts,t.samples);break}case 7:{var d,f;a=!0,l=!0;const g=A.data,p=this.readSPS(g);if(!e.sps||e.width!==p.width||e.height!==p.height||((d=e.pixelRatio)==null?void 0:d[0])!==p.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==p.pixelRatio[1]){e.width=p.width,e.height=p.height,e.pixelRatio=p.pixelRatio,e.sps=[g];const v=g.subarray(1,4);let B="avc1.";for(let C=0;C<3;C++){let y=v[C].toString(16);y.length<2&&(y="0"+y),B+=y}e.codec=B}break}case 8:a=!0,e.pps=[A.data];break;case 9:a=!0,e.audFound=!0,(c=o)!=null&&c.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:a=!0;break;default:a=!1;break}o&&a&&o.units.push(A)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Wn(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,n=8,s;for(let o=0;o<e;o++)n!==0&&(s=t.readEG(),n=(i+s+256)%256),i=n===0?i:n}readSPS(e){const t=new Wn(e);let i=0,n=0,s=0,o=0,a,l,A;const u=t.readUByte.bind(t),c=t.readBits.bind(t),h=t.readUEG.bind(t),d=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),p=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);u();const B=u();if(c(5),f(3),u(),p(),B===100||B===110||B===122||B===244||B===44||B===83||B===86||B===118||B===128){const F=h();if(F===3&&f(1),p(),p(),f(1),d())for(l=F!==3?8:12,A=0;A<l;A++)d()&&(A<6?v(16,t):v(64,t))}p();const C=h();if(C===0)h();else if(C===1)for(f(1),g(),g(),a=h(),A=0;A<a;A++)g();p(),f(1);const y=h(),x=h(),w=c(1);w===0&&f(1),f(1),d()&&(i=h(),n=h(),s=h(),o=h());let D=[1,1];if(d()&&d())switch(u()){case 1:D=[1,1];break;case 2:D=[12,11];break;case 3:D=[10,11];break;case 4:D=[16,11];break;case 5:D=[40,33];break;case 6:D=[24,11];break;case 7:D=[20,11];break;case 8:D=[32,11];break;case 9:D=[80,33];break;case 10:D=[18,11];break;case 11:D=[15,11];break;case 12:D=[64,33];break;case 13:D=[160,99];break;case 14:D=[4,3];break;case 15:D=[3,2];break;case 16:D=[2,1];break;case 255:{D=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((y+1)*16-i*2-n*2),height:(2-w)*(x+1)*16-(w?2:4)*(s+o),pixelRatio:D}}}class Tf extends Cf{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,n){const s=this.parseNALu(e,i.data,n);let o=this.VideoSample,a,l=!1;i.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach(A=>{var u,c;switch(A.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.frame=!0,a=!0;break;case 16:case 17:case 18:case 21:if(a=!0,l){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 19:case 20:a=!0,(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 39:a=!0,xl(A.data,2,i.pts,t.samples);break;case 32:a=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=qe(e.params,this.readVPS(A.data)),this.initVPS=A.data),e.vps=[A.data];break;case 33:if(a=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],A.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const d=this.readSPS(A.data);e.width=d.width,e.height=d.height,e.pixelRatio=d.pixelRatio,e.codec=d.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const f in d.params)e.params[f]=d.params[f]}this.pushParameterSet(e.sps,A.data,e.vps),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0;break;case 34:if(a=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const d=this.readPPS(A.data);for(const f in d)e.params[f]=d[f]}this.pushParameterSet(e.pps,A.data,e.vps)}break;case 35:a=!0,e.audFound=!0,(c=o)!=null&&c.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:a=!1;break}o&&a&&o.units.push(A)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let n=0;n<e.byteLength;n++)n>=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[i]=e[n],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Wn(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const i=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:n}}readSPS(e){const t=new Wn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const n=t.readBits(2),s=t.readBoolean(),o=t.readBits(5),a=t.readUByte(),l=t.readUByte(),A=t.readUByte(),u=t.readUByte(),c=t.readUByte(),h=t.readUByte(),d=t.readUByte(),f=t.readUByte(),g=t.readUByte(),p=t.readUByte(),v=t.readUByte(),B=[],C=[];for(let ye=0;ye<i;ye++)B.push(t.readBoolean()),C.push(t.readBoolean());if(i>0)for(let ye=i;ye<8;ye++)t.readBits(2);for(let ye=0;ye<i;ye++)B[ye]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),C[ye]&&t.readUByte();t.readUEG();const y=t.readUEG();y==3&&t.skipBits(1);const x=t.readUEG(),w=t.readUEG(),D=t.readBoolean();let F=0,O=0,M=0,j=0;D&&(F+=t.readUEG(),O+=t.readUEG(),M+=t.readUEG(),j+=t.readUEG());const X=t.readUEG(),le=t.readUEG(),oe=t.readUEG(),L=t.readBoolean();for(let ye=L?0:i;ye<=i;ye++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let ke=0;ke<4;ke++)for(let Ge=0;Ge<(ke===3?2:6);Ge++)if(!t.readBoolean())t.readUEG();else{const $e=Math.min(64,1<<4+(ke<<1));ke>1&&t.readEG();for(let He=0;He<$e;He++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const R=t.readUEG();let _=0;for(let ye=0;ye<R;ye++){let ke=!1;if(ye!==0&&(ke=t.readBoolean()),ke){ye===R&&t.readUEG(),t.readBoolean(),t.readUEG();let Ge=0;for(let ze=0;ze<=_;ze++){const $e=t.readBoolean();let He=!1;$e||(He=t.readBoolean()),($e||He)&&Ge++}_=Ge}else{const Ge=t.readUEG(),ze=t.readUEG();_=Ge+ze;for(let $e=0;$e<Ge;$e++)t.readUEG(),t.readBoolean();for(let $e=0;$e<ze;$e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const ye=t.readUEG();for(let ke=0;ke<ye;ke++){for(let Ge=0;Ge<oe+4;Ge++)t.readBits(1);t.readBits(1)}}let K=0,Y=1,ie=1,re=!0,he=1,fe=0;t.readBoolean(),t.readBoolean();let _e=!1;if(t.readBoolean()){if(t.readBoolean()){const Ce=t.readUByte(),it=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],at=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Ce>0&&Ce<16?(Y=it[Ce-1],ie=at[Ce-1]):Ce===255&&(Y=t.readBits(16),ie=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),_e=t.readBoolean(),_e&&(F+=t.readUEG(),O+=t.readUEG(),M+=t.readUEG(),j+=t.readUEG()),t.readBoolean()&&(he=t.readBits(32),fe=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const at=t.readBoolean(),tt=t.readBoolean();let Ze=!1;(at||tt)&&(Ze=t.readBoolean(),Ze&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Ze&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let T=0;T<=i;T++){re=t.readBoolean();const m=re||t.readBoolean();let E=!1;m?t.readEG():E=t.readBoolean();const Q=E?1:t.readUEG()+1;if(at)for(let N=0;N<Q;N++)t.readUEG(),t.readUEG(),Ze&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(tt)for(let N=0;N<Q;N++)t.readUEG(),t.readUEG(),Ze&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),K=t.readUEG())}let Fe=x,pe=w;if(D||_e){let ye=1,ke=1;y===1?ye=ke=2:y==2&&(ye=2),Fe=x-ye*O-ye*F,pe=w-ke*j-ke*M}const Qe=n?["A","B","C"][n]:"",Oe=a<<24|l<<16|A<<8|u;let Re=0;for(let ye=0;ye<32;ye++)Re=(Re|(Oe>>ye&1)<<31-ye)>>>0;let We=Re.toString(16);return o===1&&We==="2"&&(We="6"),{codecString:`hvc1.${Qe}${o}.${We}.${s?"H":"L"}${v}.B0`,params:{general_tier_flag:s,general_profile_idc:o,general_profile_space:n,general_profile_compatibility_flags:[a,l,A,u],general_constraint_indicator_flags:[c,h,d,f,g,p],general_level_idc:v,bit_depth:X+8,bit_depth_luma_minus8:X,bit_depth_chroma_minus8:le,min_spatial_segmentation_idc:K,chroma_format_idc:y,frame_rate:{fixed:re,fps:fe/he}},width:Fe,height:pe,pixelRatio:[Y,ie]}}readPPS(e){const t=new Wn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const n=t.readBoolean(),s=t.readBoolean();let o=1;return s&&n?o=0:s?o=3:n&&(o=2),{parallelismType:o}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Bt=188;class tr{constructor(e,t,i,n){this.logger=void 0,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._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=n,this.videoParser=null}static probe(e,t){const i=tr.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){const t=e.length;let i=Math.min(Bt*5,t-Bt)+1,n=0;for(;n<i;){let s=!1,o=-1,a=0;for(let l=n;l<t;l+=Bt)if(e[l]===71&&(t-l===Bt||e[l+Bt]===71)){if(a++,o===-1&&(o=l,o!==0&&(i=Math.min(o+Bt*99,e.length-Bt)+1)),s||(s=tA(e,l)===0),s&&a>1&&(o===0&&a>2||l+Bt>i))return o}else{if(a)return-1;break}n++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:qh[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=tr.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=tr.createTrack("audio",n),this._id3Track=tr.createTrack("id3"),this._txtTrack=tr.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,n=!1){i||(this.sampleAes=null);let s;const o=this._videoTrack,a=this._audioTrack,l=this._id3Track,A=this._txtTrack;let u=o.pid,c=o.pesData,h=a.pid,d=l.pid,f=a.pesData,g=l.pesData,p=null,v=this.pmtParsed,B=this._pmtId,C=e.length;if(this.remainderData&&(e=Jt(this.remainderData,e),C=e.length,this.remainderData=null),C<Bt&&!n)return this.remainderData=e,{audioTrack:a,videoTrack:o,id3Track:l,textTrack:A};const y=Math.max(0,tr.syncOffset(e));C-=(C-y)%Bt,C<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,C,e.buffer.byteLength-C));let x=0;for(let D=y;D<C;D+=Bt)if(e[D]===71){const F=!!(e[D+1]&64),O=tA(e,D),M=(e[D+3]&48)>>4;let j;if(M>1){if(j=D+5+e[D+4],j===D+Bt)continue}else j=D+4;switch(O){case u:if(F){if(c&&(s=Vr(c,this.logger))){if(this.videoParser===null)switch(o.segmentCodec){case"avc":this.videoParser=new Bf;break;case"hevc":this.videoParser=new Tf;break}this.videoParser!==null&&this.videoParser.parsePES(o,A,s,!1)}c={data:[],size:0}}c&&(c.data.push(e.subarray(j,D+Bt)),c.size+=D+Bt-j);break;case h:if(F){if(f&&(s=Vr(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s);break;case"ac3":this.parseAC3PES(a,s);break}f={data:[],size:0}}f&&(f.data.push(e.subarray(j,D+Bt)),f.size+=D+Bt-j);break;case d:F&&(g&&(s=Vr(g,this.logger))&&this.parseID3PES(l,s),g={data:[],size:0}),g&&(g.data.push(e.subarray(j,D+Bt)),g.size+=D+Bt-j);break;case 0:F&&(j+=e[j]+1),B=this._pmtId=eT(e,j);break;case B:{F&&(j+=e[j]+1);const X=tT(e,j,this.typeSupported,i,this.observer,this.logger);u=X.videoPid,u>0&&(o.pid=u,o.segmentCodec=X.segmentVideoCodec),h=X.audioPid,h>0&&(a.pid=h,a.segmentCodec=X.segmentAudioCodec),d=X.id3Pid,d>0&&(l.pid=d),p!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${D} after unknown PID '${p}'. Backtracking to sync byte @${y} to parse all TS packets.`),p=null,D=y-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=O;break}}else x++;x>0&&iA(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=c,a.pesData=f,l.pesData=g;const w={audioTrack:a,videoTrack:o,id3Track:l,textTrack:A};return n&&this.extractRemainingSamples(w),w}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:n,textTrack:s}=e,o=i.pesData,a=t.pesData,l=n.pesData;let A;if(o&&(A=Vr(o,this.logger))){if(this.videoParser===null)switch(i.segmentCodec){case"avc":this.videoParser=new Bf;break;case"hevc":this.videoParser=new Tf;break}this.videoParser!==null&&(this.videoParser.parsePES(i,s,A,!0),i.pesData=null)}else i.pesData=o;if(a&&(A=Vr(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,A);break;case"mp3":this.parseMPEGPES(t,A);break;case"ac3":this.parseAC3PES(t,A);break}t.pesData=null}else a!=null&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;l&&(A=Vr(l,this.logger))?(this.parseID3PES(n,A),n.pesData=null):n.pesData=l}demuxSampleAes(e,t,i){const n=this.demux(e,i,!0,!this.config.progressive),s=this.sampleAes=new ZB(this.observer,this.config,t);return this.decrypt(n,s)}decrypt(e,t){return new Promise(i=>{const{audioTrack:n,videoTrack:s}=e;n.samples&&n.segmentCodec==="aac"?t.decryptAacSamples(n.samples,0,()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,()=>{i(e)}):i(e)}):s.samples&&t.decryptAvcSamples(s.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0;const n=this.aacOverFlow;let s=t.data;if(n){this.aacOverFlow=null;const c=n.missing,h=n.sample.unit.byteLength;if(c===-1)s=Jt(n.sample.unit,s);else{const d=h-c;n.sample.unit.set(s.subarray(0,c),d),e.samples.push(n.sample),i=n.missing}}let o,a;for(o=i,a=s.length;o<a-1&&!_o(s,o);o++);if(o!==i){let c;const h=o<a-1;if(h?c=`AAC PES did not start with ADTS header,offset:${o}`:c="No ADTS header found in AAC PES",iA(this.observer,new Error(c),h,this.logger),!h)return}Af(e,this.observer,s,o,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(n){const c=cf(e.samplerate);l=n.sample.pts+c}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let A=0,u;for(;o<a;)if(u=uf(e,s,o,l,A),o+=u.length,u.missing){this.aacOverFlow=u;break}else for(A++;o<a-1&&!_o(s,o);o++);}parseMPEGPES(e,t){const i=t.data,n=i.length;let s=0,o=0;const a=t.pts;if(a===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;o<n;)if(mf(i,o)){const l=gf(e,i,o,a,s);if(l)o+=l.length,s++;else break}else o++}parseAC3PES(e,t){{const i=t.data,n=t.pts;if(n===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const s=i.length;let o=0,a=0,l;for(;a<s&&(l=vf(e,i,a,n,o++))>0;)a+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=qe({},t,{type:this._videoTrack?Ht.emsg:Ht.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function tA(r,e){return((r[e+1]&31)<<8)+r[e+2]}function eT(r,e){return(r[e+10]&31)<<8|r[e+11]}function tT(r,e,t,i,n,s){const o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=(r[e+1]&15)<<8|r[e+2],l=e+3+a-4,A=(r[e+10]&15)<<8|r[e+11];for(e+=12+A;e<l;){const u=tA(r,e),c=(r[e+3]&15)<<8|r[e+4];switch(r[e]){case 207:if(!i){rA("ADTS AAC",s);break}case 15:o.audioPid===-1&&(o.audioPid=u);break;case 21:o.id3Pid===-1&&(o.id3Pid=u);break;case 219:if(!i){rA("H.264",s);break}case 27:o.videoPid===-1&&(o.videoPid=u);break;case 3:case 4:!t.mpeg&&!t.mp3?s.log("MPEG audio found, not supported in this browser"):o.audioPid===-1&&(o.audioPid=u,o.segmentAudioCodec="mp3");break;case 193:if(!i){rA("AC-3",s);break}case 129:t.ac3?o.audioPid===-1&&(o.audioPid=u,o.segmentAudioCodec="ac3"):s.log("AC-3 audio found, not supported in this browser");break;case 6:if(o.audioPid===-1&&c>0){let h=e+5,d=c;for(;d>2;){switch(r[h]){case 106:t.ac3!==!0?s.log("AC-3 audio found, not supported in this browser for now"):(o.audioPid=u,o.segmentAudioCodec="ac3");break}const g=r[h+1]+2;h+=g,d-=g}}break;case 194:case 135:return iA(n,new Error("Unsupported EC-3 in M2TS found"),void 0,s),o;case 36:o.videoPid===-1&&(o.videoPid=u,o.segmentVideoCodec="hevc",s.log("HEVC in M2TS found"));break}e+=c+5}return o}function iA(r,e,t,i){i.warn(`parsing error: ${e.message}`),r.emit(I.ERROR,I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function rA(r,e){e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function Vr(r,e){let t=0,i,n,s,o,a;const l=r.data;if(!r||r.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=Jt(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(n=(i[4]<<8)+i[5],n&&n>r.size-6)return null;const u=i[7];u&192&&(o=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,u&64?(a=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,o-a>54e5&&(e.warn(`${Math.round((o-a)/9e4)}s delta between PTS and DTS, align them`),o=a)):a=o),s=i[8];let c=s+9;if(r.size<=c)return null;r.size-=c;const h=new Uint8Array(r.size);for(let d=0,f=l.length;d<f;d++){i=l[d];let g=i.byteLength;if(c)if(c>g){c-=g;continue}else i=i.subarray(c),g-=c,c=0;h.set(i,t),t+=g}return n&&(n-=s+3),{data:h,pts:o,dts:a,len:n}}return null}class iT{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 ir=Math.pow(2,32)-1;class H{static init(){H.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in H.types)H.types.hasOwnProperty(e)&&(H.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]);H.HDLR_TYPES={video:t,audio:i};const n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);H.STTS=H.STSC=H.STCO=s,H.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),H.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),H.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),H.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]);H.FTYP=H.box(H.types.ftyp,o,l,o,a),H.DINF=H.box(H.types.dinf,H.box(H.types.dref,n))}static box(e,...t){let i=8,n=t.length;const s=n;for(;n--;)i+=t[n].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),n=0,i=8;n<s;n++)o.set(t[n],i),i+=t[n].byteLength;return o}static hdlr(e){return H.box(H.types.hdlr,H.HDLR_TYPES[e])}static mdat(e){return H.box(H.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(ir+1)),n=Math.floor(t%(ir+1));return H.box(H.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,n>>24,n>>16&255,n>>8&255,n&255,85,196,0,0]))}static mdia(e){return H.box(H.types.mdia,H.mdhd(e.timescale||0,e.duration||0),H.hdlr(e.type),H.minf(e))}static mfhd(e){return H.box(H.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"?H.box(H.types.minf,H.box(H.types.smhd,H.SMHD),H.DINF,H.stbl(e)):H.box(H.types.minf,H.box(H.types.vmhd,H.VMHD),H.DINF,H.stbl(e))}static moof(e,t,i){return H.box(H.types.moof,H.mfhd(e),H.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=H.trak(e[t]);return H.box.apply(null,[H.types.moov,H.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(H.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=H.trex(e[t]);return H.box.apply(null,[H.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(ir+1)),n=Math.floor(t%(ir+1)),s=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,n>>24,n>>16&255,n>>8&255,n&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 H.box(H.types.mvhd,s)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let n,s;for(n=0;n<t.length;n++)s=t[n].flags,i[n+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return H.box(H.types.sdtp,i)}static stbl(e){return H.box(H.types.stbl,H.stsd(e),H.box(H.types.stts,H.STTS),H.box(H.types.stsc,H.STSC),H.box(H.types.stsz,H.STSZ),H.box(H.types.stco,H.STCO))}static avc1(e){let t=[],i=[],n,s,o;for(n=0;n<e.sps.length;n++)s=e.sps[n],o=s.byteLength,t.push(o>>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(s));for(n=0;n<e.pps.length;n++)s=e.pps[n],o=s.byteLength,i.push(o>>>8&255),i.push(o&255),i=i.concat(Array.prototype.slice.call(s));const a=H.box(H.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,A=e.height,u=e.pixelRatio[0],c=e.pixelRatio[1];return H.box(H.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,A>>8&255,A&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,H.box(H.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),H.box(H.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,c>>24,c>>16&255,c>>8&255,c&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return H.box(H.types.mp4a,H.audioStsd(e),H.box(H.types.esds,H.esds(e)))}static mp3(e){return H.box(H.types[".mp3"],H.audioStsd(e))}static ac3(e){return H.box(H.types["ac-3"],H.audioStsd(e),H.box(H.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return H.box(H.types.stsd,H.STSD,H.mp4a(e));if(t==="ac3"&&e.config)return H.box(H.types.stsd,H.STSD,H.ac3(e));if(t==="mp3"&&e.codec==="mp3")return H.box(H.types.stsd,H.STSD,H.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return H.box(H.types.stsd,H.STSD,H.avc1(e));if(t==="hevc"&&e.vps)return H.box(H.types.stsd,H.STSD,H.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,i=(e.duration||0)*(e.timescale||0),n=e.width||0,s=e.height||0,o=Math.floor(i/(ir+1)),a=Math.floor(i%(ir+1));return H.box(H.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,n>>8&255,n&255,0,0,s>>8&255,s&255,0,0]))}static traf(e,t){const i=H.sdtp(e),n=e.id,s=Math.floor(t/(ir+1)),o=Math.floor(t%(ir+1));return H.box(H.types.traf,H.box(H.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),H.box(H.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,s&255,o>>24,o>>16&255,o>>8&255,o&255])),H.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,H.box(H.types.trak,H.tkhd(e),H.mdia(e))}static trex(e){const t=e.id;return H.box(H.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||[],n=i.length,s=12+16*n,o=new Uint8Array(s);let a,l,A,u,c,h;for(t+=8+s,o.set([e.type==="video"?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,n&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),a=0;a<n;a++)l=i[a],A=l.duration,u=l.size,c=l.flags,h=l.cts,o.set([A>>>24&255,A>>>16&255,A>>>8&255,A&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,c.degradPrio&61440,c.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*a);return H.box(H.types.trun,o)}static initSegment(e){H.types||H.init();const t=H.moov(e);return Jt(H.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],n=4,s=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),n-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let o=s.length;for(let f=0;f<i.length;f+=1){o+=3;for(let g=0;g<i[f].length;g+=1)o+=2+i[f][g].length}const a=new Uint8Array(o);a.set(s,0),o=s.length;const l=i.length-1;for(let f=0;f<i.length;f+=1){a.set(new Uint8Array([32+f|(f===l?128:0),0,i[f].length]),o),o+=3;for(let g=0;g<i[f].length;g+=1)a.set(new Uint8Array([i[f][g].length>>8,i[f][g].length&255]),o),o+=2,a.set(i[f][g],o),o+=i[f][g].length}const A=H.box(H.types.hvcC,a),u=e.width,c=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return H.box(H.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,u&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,H.box(H.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),H.box(H.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,d>>24,d>>16&255,d>>8&255,d&255])))}}H.types=void 0,H.HDLR_TYPES=void 0,H.STTS=void 0,H.STSC=void 0,H.STCO=void 0,H.STSZ=void 0,H.VMHD=void 0,H.SMHD=void 0,H.STSD=void 0,H.FTYP=void 0,H.DINF=void 0;const bf=9e4;function nA(r,e,t=1,i=!1){const n=r*e*t;return i?Math.round(n):n}function rT(r,e,t=1,i=!1){return nA(r,e,1/t,i)}function qn(r,e=!1){return nA(r,1e3,1/bf,e)}function nT(r,e=1){return nA(r,bf,1/e)}const sT=10*1e3,oT=1024,aT=1152,lT=1536;let Kr=null,sA=null;function Sf(r,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:r?2:1,isNonSync:r?0:1}}}class Do{constructor(e,t,i,n){if(this.logger=void 0,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.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=n,this.ISGenerated=!1,Kr===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Kr=o?parseInt(o[1]):0}if(sA===null){const s=navigator.userAgent.match(/Safari\/(\d+)/i);sA=s?parseInt(s[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,n=e.reduce((s,o)=>{let a=o.pts,l=a-s;return l<-4294967296&&(t=!0,a=jt(a,i),l=a-s),l>0?s:a},i);return t&&this.logger.debug("PTS rollover detected"),n}remux(e,t,i,n,s,o,a,l){let A,u,c,h,d,f,g=s,p=s;const v=e.pid>-1,B=t.pid>-1,C=t.samples.length,y=e.samples.length>0,x=a&&C>0||C>1;if((!v||y)&&(!B||x)||this.ISGenerated||a){if(this.ISGenerated){var D,F,O,M;const oe=this.videoTrackConfig;(oe&&(t.width!==oe.width||t.height!==oe.height||((D=t.pixelRatio)==null?void 0:D[0])!==((F=oe.pixelRatio)==null?void 0:F[0])||((O=t.pixelRatio)==null?void 0:O[1])!==((M=oe.pixelRatio)==null?void 0:M[1]))||!oe&&x||this.nextAudioPts===null&&y)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,s,o));const j=this.isVideoContiguous;let X=-1,le;if(x&&(X=AT(t.samples),!j&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,X>0){this.logger.warn(`[mp4-remuxer]: Dropped ${X} out of ${C} video samples due to a missing keyframe`);const oe=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(X),t.dropped+=X,p+=(t.samples[0].pts-oe)/t.inputTimeScale,le=p}else X===-1&&(this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${C} video samples`),f=!1);if(this.ISGenerated){if(y&&x){const oe=this.getVideoStartPts(t.samples),U=(jt(e.samples[0].pts,oe)-oe)/t.inputTimeScale;g+=Math.max(0,U),p+=Math.max(0,-U)}if(y){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(e,t,s,o)),u=this.remuxAudio(e,g,this.isAudioContiguous,o,B||x||l===Ee.AUDIO?p:void 0),x){const oe=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(e,t,s,o)),A=this.remuxVideo(t,p,j,oe)}}else x&&(A=this.remuxVideo(t,p,j,0));A&&(A.firstKeyFrame=X,A.independent=X!==-1,A.firstKeyFramePTS=le)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(d=xf(i,s,this._initPTS,this._initDTS)),n.samples.length&&(h=Qf(n,s,this._initPTS))),{audio:u,video:A,initSegment:c,independent:f,text:h,id3:d}}generateIS(e,t,i,n){const s=e.samples,o=t.samples,a=this.typeSupported,l={},A=this._initPTS;let u=!A||n,c="audio/mp4",h,d,f;if(u&&(h=d=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(c="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:c,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):H.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(f=e.inputTimeScale,!A||f!==A.timescale?h=d=s[0].pts-Math.round(f*i):u=!1)}if(t.sps&&t.pps&&o.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:H.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(f=t.inputTimeScale,!A||f!==A.timescale){const g=this.getVideoStartPts(o),p=Math.round(f*i);d=Math.min(d,jt(o[0].dts,g)-p),h=Math.min(h,g-p)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:f},this._initDTS={baseTime:d,timescale:f}):h=f=void 0,{tracks:l,initPTS:h,timescale:f}}remuxVideo(e,t,i,n){const s=e.inputTimeScale,o=e.samples,a=[],l=o.length,A=this._initPTS;let u=this.nextAvcDts,c=8,h=this.videoSampleDuration,d,f,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!i||u===null){const _=t*s,k=o[0].pts-jt(o[0].dts,o[0].pts);Kr&&u!==null&&Math.abs(_-k-u)<15e3?i=!0:u=_-k}const B=A.baseTime*s/A.timescale;for(let _=0;_<l;_++){const k=o[_];k.pts=jt(k.pts-B,u),k.dts=jt(k.dts-B,u),k.dts<o[_>0?_-1:_].dts&&(v=!0)}v&&o.sort(function(_,k){const K=_.dts-k.dts,Y=_.pts-k.pts;return K||Y}),d=o[0].dts,f=o[o.length-1].dts;const C=f-d,y=C?Math.round(C/(l-1)):h||e.inputTimeScale/30;if(i){const _=d-u,k=_>y,K=_<-1;if((k||K)&&(k?this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${qn(_,!0)} ms (${_}dts) hole between fragments detected at ${t.toFixed(3)}`):this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${qn(-_,!0)} ms (${_}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!K||u>=o[0].pts||Kr)){d=u;const Y=o[0].pts-_;if(k)o[0].dts=d,o[0].pts=Y;else{let ie=!0;for(let re=0;re<o.length&&!(o[re].dts>Y&&ie);re++){const he=o[re].pts;if(o[re].dts-=_,o[re].pts-=_,re<o.length-1){const fe=o[re+1].pts,_e=o[re].pts,be=fe<=_e,Fe=fe<=he;ie=be==Fe}}}this.logger.log(`Video: Initial PTS/DTS adjusted: ${qn(Y,!0)}/${qn(d,!0)}, delta: ${qn(_,!0)} ms`)}}d=Math.max(0,d);let x=0,w=0,D=d;for(let _=0;_<l;_++){const k=o[_],K=k.units,Y=K.length;let ie=0;for(let re=0;re<Y;re++)ie+=K[re].data.length;w+=ie,x+=Y,k.length=ie,k.dts<D?(k.dts=D,D+=y/4|0||1):D=k.dts,g=Math.min(k.pts,g),p=Math.max(k.pts,p)}f=o[l-1].dts;const F=w+4*x+8;let O;try{O=new Uint8Array(F)}catch(_){this.observer.emit(I.ERROR,I.ERROR,{type:Ie.MUX_ERROR,details:V.REMUX_ALLOC_ERROR,fatal:!1,error:_,bytes:F,reason:`fail allocating video mdat ${F}`});return}const M=new DataView(O.buffer);M.setUint32(0,F),O.set(H.types.mdat,4);let j=!1,X=Number.POSITIVE_INFINITY,le=Number.POSITIVE_INFINITY,oe=Number.NEGATIVE_INFINITY,L=Number.NEGATIVE_INFINITY;for(let _=0;_<l;_++){const k=o[_],K=k.units;let Y=0;for(let he=0,fe=K.length;he<fe;he++){const _e=K[he],be=_e.data,Fe=_e.data.byteLength;M.setUint32(c,Fe),c+=4,O.set(be,c),c+=Fe,Y+=4+Fe}let ie;if(_<l-1)h=o[_+1].dts-k.dts,ie=o[_+1].pts-k.pts;else{const he=this.config,fe=_>0?k.dts-o[_-1].dts:y;if(ie=_>0?k.pts-o[_-1].pts:y,he.stretchShortVideoTrack&&this.nextAudioPts!==null){const _e=Math.floor(he.maxBufferHole*s),be=(n?g+n*s:this.nextAudioPts)-k.pts;be>_e?(h=be-fe,h<0?h=fe:j=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${be/90} ms to the next segment; using duration ${h/90} ms for the last video frame.`)):h=fe}else h=fe}const re=Math.round(k.pts-k.dts);X=Math.min(X,h),oe=Math.max(oe,h),le=Math.min(le,ie),L=Math.max(L,ie),a.push(Sf(k.key,h,Y,re))}if(a.length){if(Kr){if(Kr<70){const _=a[0].flags;_.dependsOn=2,_.isNonSync=0}}else if(sA&&L-le<oe-X&&y/oe<.025&&a[0].cts===0){this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let _=d;for(let k=0,K=a.length;k<K;k++){const Y=_+a[k].duration,ie=_+a[k].cts;if(k<K-1){const re=Y+a[k+1].cts;a[k].duration=re-ie}else a[k].duration=k?a[k-1].duration:y;a[k].cts=0,_=Y}}}h=j||!h?y:h,this.nextAvcDts=u=f+h,this.videoSampleDuration=h,this.isVideoContiguous=!0;const R={data1:H.moof(e.sequenceNumber++,d,qe(e,{samples:a})),data2:O,startPTS:g/s,endPTS:(p+h)/s,startDTS:d/s,endDTS:u/s,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,R}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return aT;case"ac3":return lT;default:return oT}}remuxAudio(e,t,i,n,s){const o=e.inputTimeScale,a=e.samplerate?e.samplerate:o,l=o/a,A=this.getSamplesPerFrame(e),u=A*l,c=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,d=[],f=s!==void 0;let g=e.samples,p=h?0:8,v=this.nextAudioPts||-1;const B=t*o,C=c.baseTime*o/c.timescale;if(this.isAudioContiguous=i=i||g.length&&v>0&&(n&&Math.abs(B-v)<9e3||Math.abs(jt(g[0].pts-C,B)-v)<20*u),g.forEach(function(U){U.pts=jt(U.pts-C,B)}),!i||v<0){if(g=g.filter(U=>U.pts>=0),!g.length)return;s===0?v=0:n&&!f?v=Math.max(0,B):v=g[0].pts}if(e.segmentCodec==="aac"){const U=this.config.maxAudioFramesDrift;for(let q=0,R=v;q<g.length;q++){const _=g[q],k=_.pts,K=k-R,Y=Math.abs(1e3*K/o);if(K<=-U*u&&f)q===0&&(this.logger.warn(`Audio frame @ ${(k/o).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*K/o)} ms.`),this.nextAudioPts=v=R=k);else if(K>=U*u&&Y<sT&&f){let ie=Math.round(K/u);R=k-ie*u,R<0&&(ie--,R+=u),q===0&&(this.nextAudioPts=v=R),this.logger.warn(`[mp4-remuxer]: Injecting ${ie} audio frame @ ${(R/o).toFixed(3)}s due to ${Math.round(1e3*K/o)} ms gap.`);for(let re=0;re<ie;re++){const he=Math.max(R,0);let fe=iT.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);fe||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),fe=_.unit.subarray()),g.splice(q,0,{unit:fe,pts:he}),R+=u,q++}}_.pts=R,R+=u}}let y=null,x=null,w,D=0,F=g.length;for(;F--;)D+=g[F].unit.byteLength;for(let U=0,q=g.length;U<q;U++){const R=g[U],_=R.unit;let k=R.pts;if(x!==null){const Y=d[U-1];Y.duration=Math.round((k-x)/l)}else if(i&&e.segmentCodec==="aac"&&(k=v),y=k,D>0){D+=p;try{w=new Uint8Array(D)}catch(Y){this.observer.emit(I.ERROR,I.ERROR,{type:Ie.MUX_ERROR,details:V.REMUX_ALLOC_ERROR,fatal:!1,error:Y,bytes:D,reason:`fail allocating audio mdat ${D}`});return}h||(new DataView(w.buffer).setUint32(0,D),w.set(H.types.mdat,4))}else return;w.set(_,p);const K=_.byteLength;p+=K,d.push(Sf(!0,A,K,0)),x=k}const O=d.length;if(!O)return;const M=d[d.length-1];this.nextAudioPts=v=x+l*M.duration;const j=h?new Uint8Array(0):H.moof(e.sequenceNumber++,y/l,qe({},e,{samples:d}));e.samples=[];const X=y/o,le=v/o,L={data1:j,data2:w,startPTS:X,endPTS:le,startDTS:X,endDTS:le,type:"audio",hasAudio:!0,hasVideo:!1,nb:O};return this.isAudioContiguous=!0,L}}function jt(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 AT(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function xf(r,e,t,i){const n=r.samples.length;if(!n)return;const s=r.inputTimeScale;for(let a=0;a<n;a++){const l=r.samples[a];l.pts=jt(l.pts-t.baseTime*s/t.timescale,e*s)/s,l.dts=jt(l.dts-i.baseTime*s/i.timescale,e*s)/s}const o=r.samples;return r.samples=[],{samples:o}}function Qf(r,e,t){const i=r.samples.length;if(!i)return;const n=r.inputTimeScale;for(let o=0;o<i;o++){const a=r.samples[o];a.pts=jt(a.pts-t.baseTime*n/t.timescale,e*n)/n}r.samples.sort((o,a)=>o.pts-a.pts);const s=r.samples;return r.samples=[],{samples:s}}class cT{constructor(e,t,i,n){this.logger=void 0,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,this.logger=n}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,n){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(zy(e,n)),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 n=this.initData=zh(e);n.audio&&(t=_f(n.audio,Je.AUDIO)),n.video&&(i=_f(n.video,Je.VIDEO));const s={};n.audio&&n.video?s.audiovideo={container:"video/mp4",codec:t+","+i,supplemental:n.video.supplemental,initSegment:e,id:"main"}:n.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:n.video?s.video={container:"video/mp4",codec:i,supplemental:n.video.supplemental,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,i,n,s,o){var a,l;let{initPTS:A,lastEndTime:u}=this;const c={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};de(u)||(u=this.lastEndTime=s||0);const h=t.samples;if(!(h!=null&&h.length))return c;const d={initPTS:void 0,timescale:1};let f=this.initData;if((a=f)!=null&&a.length||(this.generateInitSegment(h),f=this.initData),!((l=f)!=null&&l.length))return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(d.tracks=this.initTracks,this.emitInitSegment=!1);const g=eC(h,f),p=Zy(f,h),v=p===null?s:p;(o||!A)&&(uT(A,v,s,g)||d.timescale!==A.timescale)&&(d.initPTS=v-s,A&&A.timescale===1&&this.logger.warn(`Adjusting initPTS @${s} from ${A.baseTime/A.timescale} to ${d.initPTS}`),this.initPTS=A={baseTime:d.initPTS,timescale:1});const B=e?v-A.baseTime/A.timescale:u,C=B+g;iC(f,h,A.baseTime/A.timescale),g>0?this.lastEndTime=C:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const y=!!f.audio,x=!!f.video;let w="";y&&(w+="audio"),x&&(w+="video");const D={data1:h,startPTS:B,startDTS:B,endPTS:C,endDTS:C,type:w,hasAudio:y,hasVideo:x,nb:1,dropped:0};return c.audio=D.type==="audio"?D:void 0,c.video=D.type!=="audio"?D:void 0,c.initSegment=d,c.id3=xf(i,s,A,A),n.samples.length&&(c.text=Qf(n,s,A)),c}}function uT(r,e,t,i){if(r===null)return!0;const n=Math.max(i,1),s=e-r.baseTime/r.timescale;return Math.abs(s-t)>n}function _f(r,e){const t=r==null?void 0:r.codec;return t&&t.length>4?t:e===Je.AUDIO?t==="ec-3"||t==="ac-3"||t==="alac"?t:t==="fLaC"||t==="Opus"?fo(t,!1):(Ue.warn(`Unhandled audio codec "${t}" in mp4 MAP`),t||"mp4a"):(Ue.warn(`Unhandled video codec "${t}" in mp4 MAP`),t||"avc1")}let Di;try{Di=self.performance.now.bind(self.performance)}catch{Di=Date.now}const Lo=[{demux:zB,remux:cT},{demux:tr,remux:Do},{demux:qB,remux:Do},{demux:jB,remux:Do}];Lo.splice(2,0,{demux:JB,remux:Do});class wf{constructor(e,t,i,n,s,o){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=s,this.logger=o}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,n){const s=i.transmuxing;s.executeStart=Di();let o=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:l}=this;n&&(this.currentTransmuxState=n);const{contiguous:A,discontinuity:u,trackSwitch:c,accurateTimeOffset:h,timeOffset:d,initSegmentChange:f}=n||a,{audioCodec:g,videoCodec:p,defaultInitPts:v,duration:B,initSegmentData:C}=l,y=hT(o,t);if(y&&Hr(y.method)){const F=this.getDecrypter(),O=Fl(y.method);if(F.isSync()){let M=F.softwareDecrypt(o,y.key.buffer,y.iv.buffer,O);if(i.part>-1){const X=F.flush();M=X&&X.buffer}if(!M)return s.executeEnd=Di(),oA(i);o=new Uint8Array(M)}else return this.asyncResult=!0,this.decryptionPromise=F.webCryptoDecrypt(o,y.key.buffer,y.iv.buffer,O).then(M=>{const j=this.push(M,null,i);return this.decryptionPromise=null,j}),this.decryptionPromise}const x=this.needsProbing(u,c);if(x){const F=this.configureTransmuxer(o);if(F)return this.logger.warn(`[transmuxer] ${F.message}`),this.observer.emit(I.ERROR,I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!1,error:F,reason:F.message}),s.executeEnd=Di(),oA(i)}(u||c||f||x)&&this.resetInitSegment(C,g,p,B,t),(u||f||x)&&this.resetInitialTimestamp(v),A||this.resetContiguity();const w=this.transmux(o,y,d,h,i);this.asyncResult=Jn(w);const D=this.currentTransmuxState;return D.contiguous=!0,D.discontinuity=!1,D.trackSwitch=!1,s.executeEnd=Di(),w}flush(e){const t=e.transmuxing;t.executeStart=Di();const{decrypter:i,currentTransmuxState:n,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then(()=>this.flush(e));const o=[],{timeOffset:a}=n;if(i){const c=i.flush();c&&o.push(this.push(c.buffer,null,e))}const{demuxer:l,remuxer:A}=this;if(!l||!A){t.executeEnd=Di();const c=[oA(e)];return this.asyncResult?Promise.resolve(c):c}const u=l.flush(a);return Jn(u)?(this.asyncResult=!0,u.then(c=>(this.flushRemux(o,c,e),o))):(this.flushRemux(o,u,e),this.asyncResult?Promise.resolve(o):o)}flushRemux(e,t,i){const{audioTrack:n,videoTrack:s,id3Track:o,textTrack:a}=t,{accurateTimeOffset:l,timeOffset:A}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===Ee.MAIN?"level":"track"} ${i.level}`);const u=this.remuxer.remux(n,s,o,a,A,l,!0,this.id);e.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=Di()}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,n,s){const{demuxer:o,remuxer:a}=this;!o||!a||(o.resetInitSegment(e,t,i,n),a.resetInitSegment(e,t,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,n,s){let o;return t&&t.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,t,i,n,s):o=this.transmuxUnencrypted(e,i,n,s),o}transmuxUnencrypted(e,t,i,n){const{audioTrack:s,videoTrack:o,id3Track:a,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,o,a,l,t,i,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,i,n,s){return this.demuxer.demuxSampleAes(e,t,i).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,i,n,!1,this.id),chunkMeta:s}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:n}=this;let s;for(let c=0,h=Lo.length;c<h;c++){var o;if((o=Lo[c].demux)!=null&&o.probe(e,this.logger)){s=Lo[c];break}}if(!s)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,l=this.remuxer,A=s.remux,u=s.demux;(!l||!(l instanceof A))&&(this.remuxer=new A(i,t,n,this.logger)),(!a||!(a instanceof u))&&(this.demuxer=new u(i,t,n,this.logger),this.probe=u.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Ll(this.config)),e}}function hT(r,e){let t=null;return r.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const oA=r=>({remuxResult:{},chunkMeta:r});function Jn(r){return"then"in r&&r.then instanceof Function}class dT{constructor(e,t,i,n,s){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=n,this.defaultInitPts=s||null}}class fT{constructor(e,t,i,n,s,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=n,this.timeOffset=s,this.initSegmentChange=o}}let Rf=0;class Df{constructor(e,t,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Rf++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{const A=l.data,u=this.hls;if(!(!u||!(A!=null&&A.event)||A.instanceNo!==this.instanceNo))switch(A.event){case"init":{var c;const h=(c=this.workerContext)==null?void 0:c.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(A.data);break}case"flush":{this.onFlush(A.data);break}case"workerLog":{u.logger[A.data.logType]&&u.logger[A.data.logType](A.data.message);break}default:{A.data=A.data||{},A.data.frag=this.frag,A.data.part=this.part,A.data.id=this.id,u.trigger(A.event,A.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const A=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:A})};const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;const o=(l,A)=>{A=A||{},A.frag=this.frag||void 0,l===I.ERROR&&(A=A,A.parent=this.id,A.part=this.part,this.error=A.error),this.hls.trigger(l,A)};this.observer=new ql,this.observer.on(I.FRAG_DECRYPTED,o),this.observer.on(I.ERROR,o);const a=od(s.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(s.workerPath||mB()){try{s.workerPath?(l.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=IB(s.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=EB());const{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:rt(s)})}catch(u){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new wf(this.observer,a,s,"",t,e.logger)}return}}this.transmuxer=new wf(this.observer,a,s,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Rf++;const t=this.hls.config,i=od(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:rt(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),vB(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,n,s,o,a,l,A,u){var c,h;A.transmuxing.start=self.performance.now();const{instanceNo:d,transmuxer:f}=this,g=o?o.start:s.start,p=s.decryptdata,v=this.frag,B=!(v&&s.cc===v.cc),C=!(v&&A.level===v.level),y=v?A.sn-v.sn:-1,x=this.part?A.part-this.part.index:-1,w=y===0&&A.id>1&&A.id===(v==null?void 0:v.stats.chunkCount),D=!C&&(y===1||y===0&&(x===1||w&&x<=0)),F=self.performance.now();(C||y||s.stats.parsing.start===0)&&(s.stats.parsing.start=F),o&&(x||!D)&&(o.stats.parsing.start=F);const O=!(v&&((c=s.initSegment)==null?void 0:c.url)===((h=v.initSegment)==null?void 0:h.url)),M=new fT(B,D,l,C,g,O);if(!D||B||O){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${A.sn}${A.part>-1?" part: "+A.part:""} ${this.id===Ee.MAIN?"level":"track"}: ${A.level} id: ${A.id}
2501
2501
  discontinuity: ${B}
2502
2502
  trackSwitch: ${C}
2503
2503
  contiguous: ${D}
2504
2504
  accurateTimeOffset: ${l}
2505
2505
  timeOffset: ${g}
2506
- initSegmentChange: ${O}`);const j=new dT(i,n,t,a,u);this.configureTransmuxer(j)}if(this.frag=s,this.part=o,this.workerContext)this.workerContext.worker.postMessage({instanceNo:d,cmd:"demux",data:e,decryptdata:p,chunkMeta:A,state:M},e instanceof ArrayBuffer?[e]:[]);else if(f){const j=f.push(e,p,A,M);Jn(j)?j.then(X=>{this.handleTransmuxComplete(X)}).catch(X=>{this.transmuxerError(X,A,"transmuxer-interface push error")}):this.handleTransmuxComplete(j)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const n=i.flush(e);Jn(n)?n.then(s=>{this.handleFlushResult(s,e)}).catch(s=>{this.transmuxerError(s,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Lf=100;class gT extends Kl{constructor(e,t,i){super(e,t,i,"audio-stream-controller",Ee.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(I.BUFFER_RESET,this.onBufferReset,this),e.on(I.BUFFER_CREATED,this.onBufferCreated,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(I.FRAG_LOADING,this.onFragLoading,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(I.BUFFER_RESET,this.onBufferReset,this),e.off(I.BUFFER_CREATED,this.onBufferCreated,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(I.FRAG_LOADING,this.onFragLoading,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:s}){if(i===Ee.MAIN){const o=t.cc,a=this.fragCurrent;if(this.initPTS[o]={baseTime:n,timescale:s},this.log(`InitPTS for cc: ${o} found from main: ${n}/${s}`),this.mainAnchor=t,this.state===Z.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&(this.nextLoadPosition=this.findSyncFrag(t).start),this.tick()}else!this.hls.hasEnoughToStart&&a&&a.cc!==o?(this.startFragRequested=!1,this.nextLoadPosition=this.findSyncFrag(t).start,a.abortRequests(),this.resetLoadingState()):this.state===Z.IDLE&&this.tick()}}findSyncFrag(e){const t=this.getLevelDetails(),i=e.cc;return RC(t,i,e)||t&&Id(t.fragments,i)||e}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=Z.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(Lf),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=Z.IDLE):this.state=Z.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case Z.IDLE:this.doTickIdle();break;case Z.WAITING_TRACK:{const{levels:t,trackId:i}=this,n=t==null?void 0:t[i],s=n==null?void 0:n.details;if(s&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(s))break;this.state=Z.WAITING_INIT_PTS}break}case Z.FRAG_LOADING_WAITING_RETRY:{var e;const t=performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){const{levels:n,trackId:s}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((n==null?void 0:n[s])||null),this.state=Z.IDLE}break}case Z.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:i,part:n,cache:s,complete:o}=t,a=this.mainAnchor;if(this.initPTS[i.cc]!==void 0){this.waitingData=null,this.state=Z.FRAG_LOADING;const l=s.flush().buffer,A={frag:i,part:n,payload:l,networkDetails:null};this._handleFragmentLoadProgress(A),o&&super._handleFragmentLoadComplete(A)}else a&&a.cc!==t.frag.cc&&(this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${a.cc}`),this.nextLoadPosition=this.findSyncFrag(a).start,this.clearWaitingFragment())}else this.state=Z.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.state!==Z.STOPPED&&(this.state=Z.IDLE))}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:n,trackId:s}=this,o=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!o.startFragPrefetch)||!(i!=null&&i[s]))return;const a=i[s],l=a.details;if(!l||this.waitForLive(a)||this.waitForCdnTuneIn(l)){this.state=Z.WAITING_TRACK,this.startFragRequested=!1;return}const A=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&A&&(this.bufferFlushed=!1,this.afterBufferFlushed(A,Je.AUDIO,Ee.AUDIO));const u=this.getFwdBufferInfo(A,Ee.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,l)){t.trigger(I.BUFFER_EOS,{type:"audio"}),this.state=Z.ENDED;return}const c=u.len,h=t.maxBufferLength,d=l.fragments,f=d[0].start,g=this.getLoadPosition(),p=this.flushing?g:u.end;if(this.switchingTrack&&n){const C=g;l.PTSKnown&&C<f&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=f+.05)}if(c>=h&&!this.switchingTrack&&p<d[d.length-1].start)return;let v=this.getNextFragment(p,l);if(v&&this.isLoopLoading(v,p)&&(v=this.getNextFragmentLoopLoading(v,l,u,Ee.MAIN,h)),!v){this.bufferFlushed=!0;return}let B=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&B&&Ct(v)&&!v.endList&&(!l.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(B)===vt.OK&&(this.mainFragLoading=B=null),B&&Ct(B))){if(v.start>B.end){const y=this.fragmentTracker.getFragAtPos(p,Ee.MAIN);y&&y.end>B.end&&(B=y,this.mainFragLoading={frag:y,targetBufferTime:null})}if(v.start>B.end)return}this.loadFragment(v,a,p)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new Gn(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==Z.STOPPED&&(this.setInterval(Lf),this.state=Z.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(I.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:n}=this,{details:s,id:o,groupId:a,track:l}=t;if(!n){this.warn(`Audio tracks reset while loading track ${o} "${l.name}" of "${a}"`);return}const A=this.mainDetails;if(!A||s.endCC>A.endCC||A.expired){this.cachedTrackLoadedData=t,this.state!==Z.STOPPED&&(this.state=Z.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${o} "${l.name}" of "${a}" loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const u=n[o];let c=0;if(s.live||(i=u.details)!=null&&i.live){if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;if(u.details){var h;c=this.alignPlaylists(s,u.details,(h=this.levelLastLoaded)==null?void 0:h.details)}s.alignedSliding||(tf(s,A),s.alignedSliding||xo(s,A),c=s.fragmentStart)}u.details=s,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(A,c),this.hls.trigger(I.AUDIO_TRACK_UPDATED,{details:s,id:o,groupId:t.groupId}),this.state===Z.WAITING_TRACK&&!this.waitForCdnTuneIn(s)&&(this.state=Z.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:n,payload:s}=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 A=l[a];if(!A){this.warn("Audio track is undefined on fragment load progress");return}const u=A.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const c=o.defaultAudioCodec||A.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new Df(this.hls,Ee.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const d=this.initPTS[i.cc],f=(t=i.initSegment)==null?void 0:t.data;if(d!==void 0){const p=n?n.index:-1,v=p!==-1,B=new kl(i.level,i.sn,i.stats.chunkCount,s.byteLength,p,v);h.push(s,f,c,"",i,n,u.totalduration,!1,B,d)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${u.startSN} ,${u.endSN}],track ${a}`);const{cache:g}=this.waitingData=this.waitingData||{frag:i,part:n,cache:new nf,complete:!1};g.push(new Uint8Array(s)),this.state!==Z.STOPPED&&(this.state=Z.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===Ee.MAIN&&Ct(t.frag)&&(this.mainFragLoading=t,this.state===Z.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:n}=t;if(i.type!==Ee.AUDIO){!this.audioOnly&&i.type===Ee.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Ct(i)){this.fragPrevious=i;const s=this.switchingTrack;s&&(this.bufferedTrack=s,this.switchingTrack=null,this.hls.trigger(I.AUDIO_TRACK_SWITCHED,Ve({},s)))}this.fragBufferedComplete(i,n),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=Z.ERROR;return}switch(t.details){case V.FRAG_GAP:case V.FRAG_PARSING_ERROR:case V.FRAG_DECRYPT_ERROR:case V.FRAG_LOAD_ERROR:case V.FRAG_LOAD_TIMEOUT:case V.KEY_LOAD_ERROR:case V.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ee.AUDIO,t);break;case V.AUDIO_TRACK_LOAD_ERROR:case V.AUDIO_TRACK_LOAD_TIMEOUT:case V.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Z.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===Me.AUDIO_TRACK&&(this.state=Z.IDLE);break;case V.BUFFER_ADD_CODEC_ERROR:case V.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.resetLoadingState();break;case V.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case V.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Je.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Je.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Z.ENDED&&(this.state=Z.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,Ee.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:n}=this,{remuxResult:s,chunkMeta:o}=e,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:l,part:A,level:u}=a,{details:c}=u,{audio:h,text:d,id3:f,initSegment:g}=s;if(this.fragContextChanged(l)||!c){this.fragmentTracker.removeFragment(l);return}if(this.state=Z.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){const p=l.initSegment||l;this._bufferInitSegment(u,g.tracks,p,o),n.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:i,tracks:g.tracks})}if(h){const{startPTS:p,endPTS:v,startDTS:B,endDTS:C}=h;A&&(A.elementaryStreams[Je.AUDIO]={startPTS:p,endPTS:v,startDTS:B,endDTS:C}),l.setElementaryStreamInfo(Je.AUDIO,p,v,B,C),this.bufferFragmentData(h,l,A,o)}if(f!=null&&(t=f.samples)!=null&&t.length){const p=qe({id:i,frag:l,details:c},f);n.trigger(I.FRAG_PARSING_METADATA,p)}if(d){const p=qe({id:i,frag:l,details:c},d);n.trigger(I.FRAG_PARSING_USERDATA,p)}}_bufferInitSegment(e,t,i,n){if(this.state!==Z.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const s=t.audio;s.id=Ee.AUDIO;const o=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${o}/${s.codec}]`),o&&o.split(",").length===1&&(s.levelCodec=o),this.hls.trigger(I.BUFFER_CODECS,t);const a=s.initSegment;if(a!=null&&a.byteLength){const l={type:"audio",frag:i,part:null,chunkMeta:n,parent:i.type,data:a};this.hls.trigger(I.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===vt.NOT_LOADED||n===vt.PARTIAL){var s;if(!Ct(e))this._loadInitSegment(e,t);else if((s=t.details)!=null&&s.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=Z.WAITING_INIT_PTS;const o=this.mainDetails;o&&o.fragmentStart!==t.details.fragmentStart&&xo(t.details,o)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:n,characteristics:s,audioCodec:o,channels:a}=this.bufferedTrack;yr({name:t,lang:i,assocLang:n,characteristics:s,audioCodec:o,channels:a},e,Cr)||(Eo(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(I.AUDIO_TRACK_SWITCHED,Ve({},e))}}class aA extends _i{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const n=t==null?void 0:t.renditionReports;if(n){let s=-1;for(let o=0;o<n.length;o++){const a=n[o];let l;try{l=new self.URL(a.URI,t.url).href}catch(A){this.warn(`Could not construct new URL for Rendition Report: ${A}`),l=a.URI||""}if(l===e){s=o;break}else l===e.substring(0,l.length)&&(s=o)}if(s!==-1){const o=n[s],a=parseInt(o["LAST-MSN"])||(t==null?void 0:t.lastPartSn);let l=parseInt(o["LAST-PART"])||(t==null?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const u=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&u>t.partTarget&&(l+=1)}const A=i&&hd(i);return new dd(a,l>=0?l:void 0,A)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){const{details:n,stats:s}=t,o=self.performance.now(),a=s.loading.first?Math.max(0,o-s.loading.first):0;n.advancedDateTime=Date.now()-a;const l=this.hls.config.timelineOffset;if(l!==n.appliedTimelineOffset){const u=Math.max(l||0,0);n.appliedTimelineOffset=u,n.fragments.forEach(c=>{c.start=c.playlistOffset+u})}if(n.live||i!=null&&i.live){const u="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(i),i&&n.fragments.length>0){aB(i,n);const B=n.playlistParsingError;if(B){this.warn(B);const C=this.hls;if(!C.config.ignorePlaylistParsingErrors){var A;const{networkDetails:y}=t;C.trigger(I.ERROR,{type:Ie.NETWORK_ERROR,details:V.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:B,reason:B.message,level:t.level||void 0,parent:(A=n.fragments[0])==null?void 0:A.type,networkDetails:y,stats:s});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=s.loading.start);const c=this.hls.mainForwardBufferInfo,h=c?c.end-c.len:0,d=(n.edge-h)*1e3,f=qd(n,d);if(n.requestScheduled+f<o?n.requestScheduled=o:n.requestScheduled+=f,this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED"}`),!this.canLoad||!n.live)return;let g,p,v;if(n.canBlockReload&&n.endSN&&n.advanced){const B=this.hls.config.lowLatencyMode,C=n.lastPartSn,y=n.endSN,x=n.lastPartIndex,w=x!==-1,D=C===y;w?D?(p=y+1,v=B?0:x):(p=C,v=B?x+1:n.maxPartIndex):p=y+1;const F=n.age,O=F+n.ageHeader;let M=Math.min(O-n.partTarget,n.targetduration*1.5);if(M>0){if(O>n.targetduration*3)this.log(`Playlist last advanced ${F.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,v=void 0;else if(i!=null&&i.tuneInGoal&&O-n.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${M} with playlist age: ${n.age}`),M=0;else{const j=Math.floor(M/n.targetduration);if(p+=j,v!==void 0){const X=Math.round(M%n.targetduration/n.partTarget);v+=X}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${F.toFixed(2)}s goal: ${M} skip sn ${j} to part ${v}`)}n.tuneInGoal=M}if(g=this.getDeliveryDirectives(n,t.deliveryDirectives,p,v),B||!D){n.requestScheduled=o,this.loadingPlaylist(u,g);return}}else(n.canBlockReload||n.canSkipUntil)&&(g=this.getDeliveryDirectives(n,t.deliveryDirectives,p,v));g&&p!==void 0&&n.canBlockReload&&(n.requestScheduled=s.loading.first+Math.max(f-a*2,f/2)),this.scheduleLoading(u,g,n)}else this.clearTimer()}scheduleLoading(e,t,i){const n=i||e.details;if(!n){this.loadingPlaylist(e,t);return}const s=self.performance.now(),o=n.requestScheduled;if(s>=o){this.loadingPlaylist(e,t);return}const a=o-s;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,i,n){let s=hd(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,n=t.part,s=mo.No),new dd(i,n,s)}checkRetry(e){const t=e.details,i=Io(e),n=e.errorAction,{action:s,retryCount:o=0,retryConfig:a}=n||{},l=!!n&&!!a&&(s===wt.RetryRequest||!n.resolved&&s===wt.SendAlternateToPenaltyBox);if(l){var A;if(o>=a.maxNumRetry)return!1;if(i&&(A=e.context)!=null&&A.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const u=Dl(a,o);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" in ${u}ms`)}e.levelRetry=!0,n.resolved=!0}return l}}function kf(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!jn(r[t].attrs,e[t].attrs))return!1;return!0}function jn(r,e,t){const i=r["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(n=>r[n]!==e[n])}function lA(r,e){return e.label.toLowerCase()===r.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(r.lang||"").toLowerCase())}class pT extends aA{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(I.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:n,details:s}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==n){this.warn(`Audio track with id:${i} and group:${n} not found in active group ${o==null?void 0:o.groupId}`);return}const a=o.details;o.details=t.details,this.log(`Audio track ${i} "${o.name}" lang:${o.lang} group:${n} 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)return;const i=t.audioGroups||null,n=this.groupIds;let s=this.currentTrack;if(!i||(n==null?void 0:n.length)!==(i==null?void 0:i.length)||i!=null&&i.some(a=>(n==null?void 0:n.indexOf(a))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(h=>!i||i.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,d)=>{h.id=d});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const l=this.hls.config.audioPreference;if(!s&&l){const h=fi(l,a,Cr);if(h>-1)s=a[h];else{const d=fi(l,this.tracks);s=this.tracks[d]}}let A=this.findTrackId(s);A===-1&&s&&(A=this.findTrackId(null));const u={audioTracks:a};this.log(`Updating audio tracks, ${a.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(I.AUDIO_TRACKS_UPDATED,u);const c=this.trackId;if(A!==-1&&c===-1)this.setAudioTrack(A);else if(a.length&&c===-1){var o;const h=new Error(`No audio track selected for current audio group-ID(s): ${(o=this.groupIds)==null?void 0:o.join(",")} track count: ${a.length}`);this.warn(h.message),this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===Me.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const n=this.currentTrack;if(n&&yr(e,n,Cr))return n;const s=fi(e,this.tracksInGroup,Cr);if(s>-1){const o=this.tracksInGroup[s];return this.setAudioTrack(s),o}else if(n){let o=t.loadLevel;o===-1&&(o=t.firstAutoLevel);const a=SC(e,t.levels,i,o,Cr);if(a===-1)return null;t.nextLoadLevel=a}if(e.channels||e.audioCodec){const o=fi(e,i);if(o>-1)return i[o]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e],s=n.details&&!n.details.live;if(e===this.trackId&&n===i&&s||(this.log(`Switching to audio-track ${e} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=e,this.currentTrack=n,this.hls.trigger(I.AUDIO_TRACK_SWITCHING,Ve({},n)),s))return;const o=this.switchParams(n.url,i==null?void 0:i.details,n.details);this.loadPlaylist(o)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const n=t[i];if(!(this.selectDefaultTrack&&!n.default)&&(!e||yr(e,n,Cr)))return i}if(e){const{name:i,lang:n,assocLang:s,characteristics:o,audioCodec:a,channels:l}=e;for(let A=0;A<t.length;A++){const u=t[A];if(yr({name:i,lang:n,assocLang:s,characteristics:o,audioCodec:a,channels:l},u,Cr))return A}for(let A=0;A<t.length;A++){const u=t[A];if(jn(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return A}for(let A=0;A<t.length;A++){const u=t[A];if(jn(e.attrs,u.attrs,["LANGUAGE"]))return A}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Eo(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,n=e.groupId,s=this.getUrlWithDirectives(e.url,t),o=e.details,a=o==null?void 0:o.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${s}`),this.hls.trigger(I.AUDIO_TRACK_LOADING,{url:s,id:i,groupId:n,deliveryDirectives:t||null,track:e})}}class mT{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(this.queues===null||this.tracks===null)return;const n=this.queues[t];n.push(e),n.length===1&&!i&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const n=t[0];try{n.execute()}catch(s){var i;if(n.onError(s),this.queues===null||this.tracks===null)return;const o=(i=this.tracks[e])==null?void 0:i.buffer;o!=null&&o.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
2506
+ initSegmentChange: ${O}`);const j=new dT(i,n,t,a,u);this.configureTransmuxer(j)}if(this.frag=s,this.part=o,this.workerContext)this.workerContext.worker.postMessage({instanceNo:d,cmd:"demux",data:e,decryptdata:p,chunkMeta:A,state:M},e instanceof ArrayBuffer?[e]:[]);else if(f){const j=f.push(e,p,A,M);Jn(j)?j.then(X=>{this.handleTransmuxComplete(X)}).catch(X=>{this.transmuxerError(X,A,"transmuxer-interface push error")}):this.handleTransmuxComplete(j)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const n=i.flush(e);Jn(n)?n.then(s=>{this.handleFlushResult(s,e)}).catch(s=>{this.transmuxerError(s,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Lf=100;class gT extends Kl{constructor(e,t,i){super(e,t,i,"audio-stream-controller",Ee.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(I.BUFFER_RESET,this.onBufferReset,this),e.on(I.BUFFER_CREATED,this.onBufferCreated,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(I.FRAG_LOADING,this.onFragLoading,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(I.BUFFER_RESET,this.onBufferReset,this),e.off(I.BUFFER_CREATED,this.onBufferCreated,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(I.FRAG_LOADING,this.onFragLoading,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:s}){if(i===Ee.MAIN){const o=t.cc,a=this.fragCurrent;if(this.initPTS[o]={baseTime:n,timescale:s},this.log(`InitPTS for cc: ${o} found from main: ${n}/${s}`),this.mainAnchor=t,this.state===Z.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&(this.nextLoadPosition=this.findSyncFrag(t).start),this.tick()}else!this.hls.hasEnoughToStart&&a&&a.cc!==o?(this.startFragRequested=!1,this.nextLoadPosition=this.findSyncFrag(t).start,a.abortRequests(),this.resetLoadingState()):this.state===Z.IDLE&&this.tick()}}findSyncFrag(e){const t=this.getLevelDetails(),i=e.cc;return RC(t,i,e)||t&&Id(t.fragments,i)||e}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=Z.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(Lf),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=Z.IDLE):this.state=Z.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case Z.IDLE:this.doTickIdle();break;case Z.WAITING_TRACK:{const{levels:t,trackId:i}=this,n=t==null?void 0:t[i],s=n==null?void 0:n.details;if(s&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(s))break;this.state=Z.WAITING_INIT_PTS}break}case Z.FRAG_LOADING_WAITING_RETRY:{var e;const t=performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){const{levels:n,trackId:s}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((n==null?void 0:n[s])||null),this.state=Z.IDLE}break}case Z.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:i,part:n,cache:s,complete:o}=t,a=this.mainAnchor;if(this.initPTS[i.cc]!==void 0){this.waitingData=null,this.state=Z.FRAG_LOADING;const l=s.flush().buffer,A={frag:i,part:n,payload:l,networkDetails:null};this._handleFragmentLoadProgress(A),o&&super._handleFragmentLoadComplete(A)}else a&&a.cc!==t.frag.cc&&(this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${a.cc}`),this.nextLoadPosition=this.findSyncFrag(a).start,this.clearWaitingFragment())}else this.state=Z.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.state!==Z.STOPPED&&(this.state=Z.IDLE))}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:n,trackId:s}=this,o=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!o.startFragPrefetch)||!(i!=null&&i[s]))return;const a=i[s],l=a.details;if(!l||this.waitForLive(a)||this.waitForCdnTuneIn(l)){this.state=Z.WAITING_TRACK,this.startFragRequested=!1;return}const A=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&A&&(this.bufferFlushed=!1,this.afterBufferFlushed(A,Je.AUDIO,Ee.AUDIO));const u=this.getFwdBufferInfo(A,Ee.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,l)){t.trigger(I.BUFFER_EOS,{type:"audio"}),this.state=Z.ENDED;return}const c=u.len,h=t.maxBufferLength,d=l.fragments,f=d[0].start,g=this.getLoadPosition(),p=this.flushing?g:u.end;if(this.switchingTrack&&n){const C=g;l.PTSKnown&&C<f&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=f+.05)}if(c>=h&&!this.switchingTrack&&p<d[d.length-1].start)return;let v=this.getNextFragment(p,l);if(v&&this.isLoopLoading(v,p)&&(v=this.getNextFragmentLoopLoading(v,l,u,Ee.MAIN,h)),!v){this.bufferFlushed=!0;return}let B=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&B&&Ct(v)&&!v.endList&&(!l.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(B)===vt.OK&&(this.mainFragLoading=B=null),B&&Ct(B))){if(v.start>B.end){const y=this.fragmentTracker.getFragAtPos(p,Ee.MAIN);y&&y.end>B.end&&(B=y,this.mainFragLoading={frag:y,targetBufferTime:null})}if(v.start>B.end)return}this.loadFragment(v,a,p)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new Gn(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==Z.STOPPED&&(this.setInterval(Lf),this.state=Z.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(I.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:n}=this,{details:s,id:o,groupId:a,track:l}=t;if(!n){this.warn(`Audio tracks reset while loading track ${o} "${l.name}" of "${a}"`);return}const A=this.mainDetails;if(!A||s.endCC>A.endCC||A.expired){this.cachedTrackLoadedData=t,this.state!==Z.STOPPED&&(this.state=Z.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${o} "${l.name}" of "${a}" loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const u=n[o];let c=0;if(s.live||(i=u.details)!=null&&i.live){if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;if(u.details){var h;c=this.alignPlaylists(s,u.details,(h=this.levelLastLoaded)==null?void 0:h.details)}s.alignedSliding||(tf(s,A),s.alignedSliding||xo(s,A),c=s.fragmentStart)}u.details=s,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(A,c),this.hls.trigger(I.AUDIO_TRACK_UPDATED,{details:s,id:o,groupId:t.groupId}),this.state===Z.WAITING_TRACK&&!this.waitForCdnTuneIn(s)&&(this.state=Z.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:n,payload:s}=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 A=l[a];if(!A){this.warn("Audio track is undefined on fragment load progress");return}const u=A.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const c=o.defaultAudioCodec||A.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new Df(this.hls,Ee.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const d=this.initPTS[i.cc],f=(t=i.initSegment)==null?void 0:t.data;if(d!==void 0){const p=n?n.index:-1,v=p!==-1,B=new kl(i.level,i.sn,i.stats.chunkCount,s.byteLength,p,v);h.push(s,f,c,"",i,n,u.totalduration,!1,B,d)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${u.startSN} ,${u.endSN}],track ${a}`);const{cache:g}=this.waitingData=this.waitingData||{frag:i,part:n,cache:new nf,complete:!1};g.push(new Uint8Array(s)),this.state!==Z.STOPPED&&(this.state=Z.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===Ee.MAIN&&Ct(t.frag)&&(this.mainFragLoading=t,this.state===Z.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:n}=t;if(i.type!==Ee.AUDIO){!this.audioOnly&&i.type===Ee.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Ct(i)){this.fragPrevious=i;const s=this.switchingTrack;s&&(this.bufferedTrack=s,this.switchingTrack=null,this.hls.trigger(I.AUDIO_TRACK_SWITCHED,Ve({},s)))}this.fragBufferedComplete(i,n),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=Z.ERROR;return}switch(t.details){case V.FRAG_GAP:case V.FRAG_PARSING_ERROR:case V.FRAG_DECRYPT_ERROR:case V.FRAG_LOAD_ERROR:case V.FRAG_LOAD_TIMEOUT:case V.KEY_LOAD_ERROR:case V.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ee.AUDIO,t);break;case V.AUDIO_TRACK_LOAD_ERROR:case V.AUDIO_TRACK_LOAD_TIMEOUT:case V.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Z.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===Me.AUDIO_TRACK&&(this.state=Z.IDLE);break;case V.BUFFER_ADD_CODEC_ERROR:case V.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.resetLoadingState();break;case V.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case V.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Je.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Je.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Z.ENDED&&(this.state=Z.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,Ee.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:n}=this,{remuxResult:s,chunkMeta:o}=e,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:l,part:A,level:u}=a,{details:c}=u,{audio:h,text:d,id3:f,initSegment:g}=s;if(this.fragContextChanged(l)||!c){this.fragmentTracker.removeFragment(l);return}if(this.state=Z.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){const p=l.initSegment||l;this._bufferInitSegment(u,g.tracks,p,o),n.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:i,tracks:g.tracks})}if(h){const{startPTS:p,endPTS:v,startDTS:B,endDTS:C}=h;A&&(A.elementaryStreams[Je.AUDIO]={startPTS:p,endPTS:v,startDTS:B,endDTS:C}),l.setElementaryStreamInfo(Je.AUDIO,p,v,B,C),this.bufferFragmentData(h,l,A,o)}if(f!=null&&(t=f.samples)!=null&&t.length){const p=qe({id:i,frag:l,details:c},f);n.trigger(I.FRAG_PARSING_METADATA,p)}if(d){const p=qe({id:i,frag:l,details:c},d);n.trigger(I.FRAG_PARSING_USERDATA,p)}}_bufferInitSegment(e,t,i,n){if(this.state!==Z.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const s=t.audio;s.id=Ee.AUDIO;const o=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${o}/${s.codec}]`),o&&o.split(",").length===1&&(s.levelCodec=o),this.hls.trigger(I.BUFFER_CODECS,t);const a=s.initSegment;if(a!=null&&a.byteLength){const l={type:"audio",frag:i,part:null,chunkMeta:n,parent:i.type,data:a};this.hls.trigger(I.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===vt.NOT_LOADED||n===vt.PARTIAL){var s;if(!Ct(e))this._loadInitSegment(e,t);else if((s=t.details)!=null&&s.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=Z.WAITING_INIT_PTS;const o=this.mainDetails;o&&o.fragmentStart!==t.details.fragmentStart&&xo(t.details,o)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:n,characteristics:s,audioCodec:o,channels:a}=this.bufferedTrack;yr({name:t,lang:i,assocLang:n,characteristics:s,audioCodec:o,channels:a},e,Cr)||(Eo(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(I.AUDIO_TRACK_SWITCHED,Ve({},e))}}class aA extends _i{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const n=t==null?void 0:t.renditionReports;if(n){let s=-1;for(let o=0;o<n.length;o++){const a=n[o];let l;try{l=new self.URL(a.URI,t.url).href}catch(A){this.warn(`Could not construct new URL for Rendition Report: ${A}`),l=a.URI||""}if(l===e){s=o;break}else l===e.substring(0,l.length)&&(s=o)}if(s!==-1){const o=n[s],a=parseInt(o["LAST-MSN"])||(t==null?void 0:t.lastPartSn);let l=parseInt(o["LAST-PART"])||(t==null?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const u=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&u>t.partTarget&&(l+=1)}const A=i&&hd(i);return new dd(a,l>=0?l:void 0,A)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){const{details:n,stats:s}=t,o=self.performance.now(),a=s.loading.first?Math.max(0,o-s.loading.first):0;n.advancedDateTime=Date.now()-a;const l=this.hls.config.timelineOffset;if(l!==n.appliedTimelineOffset){const u=Math.max(l||0,0);n.appliedTimelineOffset=u,n.fragments.forEach(c=>{c.start=c.playlistOffset+u})}if(n.live||i!=null&&i.live){const u="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(i),i&&n.fragments.length>0){aB(i,n);const B=n.playlistParsingError;if(B){this.warn(B);const C=this.hls;if(!C.config.ignorePlaylistParsingErrors){var A;const{networkDetails:y}=t;C.trigger(I.ERROR,{type:Ie.NETWORK_ERROR,details:V.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:B,reason:B.message,level:t.level||void 0,parent:(A=n.fragments[0])==null?void 0:A.type,networkDetails:y,stats:s});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=s.loading.start);const c=this.hls.mainForwardBufferInfo,h=c?c.end-c.len:0,d=(n.edge-h)*1e3,f=qd(n,d);if(n.requestScheduled+f<o?n.requestScheduled=o:n.requestScheduled+=f,this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED"}`),!this.canLoad||!n.live)return;let g,p,v;if(n.canBlockReload&&n.endSN&&n.advanced){const B=this.hls.config.lowLatencyMode,C=n.lastPartSn,y=n.endSN,x=n.lastPartIndex,w=x!==-1,D=C===y;w?D?(p=y+1,v=B?0:x):(p=C,v=B?x+1:n.maxPartIndex):p=y+1;const F=n.age,O=F+n.ageHeader;let M=Math.min(O-n.partTarget,n.targetduration*1.5);if(M>0){if(O>n.targetduration*3)this.log(`Playlist last advanced ${F.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,v=void 0;else if(i!=null&&i.tuneInGoal&&O-n.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${M} with playlist age: ${n.age}`),M=0;else{const j=Math.floor(M/n.targetduration);if(p+=j,v!==void 0){const X=Math.round(M%n.targetduration/n.partTarget);v+=X}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${F.toFixed(2)}s goal: ${M} skip sn ${j} to part ${v}`)}n.tuneInGoal=M}if(g=this.getDeliveryDirectives(n,t.deliveryDirectives,p,v),B||!D){n.requestScheduled=o,this.loadingPlaylist(u,g);return}}else(n.canBlockReload||n.canSkipUntil)&&(g=this.getDeliveryDirectives(n,t.deliveryDirectives,p,v));g&&p!==void 0&&n.canBlockReload&&(n.requestScheduled=s.loading.first+Math.max(f-a*2,f/2)),this.scheduleLoading(u,g,n)}else this.clearTimer()}scheduleLoading(e,t,i){const n=i||e.details;if(!n){this.loadingPlaylist(e,t);return}const s=self.performance.now(),o=n.requestScheduled;if(s>=o){this.loadingPlaylist(e,t);return}const a=o-s;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,i,n){let s=hd(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,n=t.part,s=mo.No),new dd(i,n,s)}checkRetry(e){const t=e.details,i=Io(e),n=e.errorAction,{action:s,retryCount:o=0,retryConfig:a}=n||{},l=!!n&&!!a&&(s===Rt.RetryRequest||!n.resolved&&s===Rt.SendAlternateToPenaltyBox);if(l){var A;if(o>=a.maxNumRetry)return!1;if(i&&(A=e.context)!=null&&A.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const u=Dl(a,o);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" in ${u}ms`)}e.levelRetry=!0,n.resolved=!0}return l}}function kf(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!jn(r[t].attrs,e[t].attrs))return!1;return!0}function jn(r,e,t){const i=r["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(n=>r[n]!==e[n])}function lA(r,e){return e.label.toLowerCase()===r.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(r.lang||"").toLowerCase())}class pT extends aA{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(I.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:n,details:s}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==n){this.warn(`Audio track with id:${i} and group:${n} not found in active group ${o==null?void 0:o.groupId}`);return}const a=o.details;o.details=t.details,this.log(`Audio track ${i} "${o.name}" lang:${o.lang} group:${n} 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)return;const i=t.audioGroups||null,n=this.groupIds;let s=this.currentTrack;if(!i||(n==null?void 0:n.length)!==(i==null?void 0:i.length)||i!=null&&i.some(a=>(n==null?void 0:n.indexOf(a))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(h=>!i||i.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,d)=>{h.id=d});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const l=this.hls.config.audioPreference;if(!s&&l){const h=fi(l,a,Cr);if(h>-1)s=a[h];else{const d=fi(l,this.tracks);s=this.tracks[d]}}let A=this.findTrackId(s);A===-1&&s&&(A=this.findTrackId(null));const u={audioTracks:a};this.log(`Updating audio tracks, ${a.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(I.AUDIO_TRACKS_UPDATED,u);const c=this.trackId;if(A!==-1&&c===-1)this.setAudioTrack(A);else if(a.length&&c===-1){var o;const h=new Error(`No audio track selected for current audio group-ID(s): ${(o=this.groupIds)==null?void 0:o.join(",")} track count: ${a.length}`);this.warn(h.message),this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===Me.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const n=this.currentTrack;if(n&&yr(e,n,Cr))return n;const s=fi(e,this.tracksInGroup,Cr);if(s>-1){const o=this.tracksInGroup[s];return this.setAudioTrack(s),o}else if(n){let o=t.loadLevel;o===-1&&(o=t.firstAutoLevel);const a=SC(e,t.levels,i,o,Cr);if(a===-1)return null;t.nextLoadLevel=a}if(e.channels||e.audioCodec){const o=fi(e,i);if(o>-1)return i[o]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e],s=n.details&&!n.details.live;if(e===this.trackId&&n===i&&s||(this.log(`Switching to audio-track ${e} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=e,this.currentTrack=n,this.hls.trigger(I.AUDIO_TRACK_SWITCHING,Ve({},n)),s))return;const o=this.switchParams(n.url,i==null?void 0:i.details,n.details);this.loadPlaylist(o)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const n=t[i];if(!(this.selectDefaultTrack&&!n.default)&&(!e||yr(e,n,Cr)))return i}if(e){const{name:i,lang:n,assocLang:s,characteristics:o,audioCodec:a,channels:l}=e;for(let A=0;A<t.length;A++){const u=t[A];if(yr({name:i,lang:n,assocLang:s,characteristics:o,audioCodec:a,channels:l},u,Cr))return A}for(let A=0;A<t.length;A++){const u=t[A];if(jn(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return A}for(let A=0;A<t.length;A++){const u=t[A];if(jn(e.attrs,u.attrs,["LANGUAGE"]))return A}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Eo(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,n=e.groupId,s=this.getUrlWithDirectives(e.url,t),o=e.details,a=o==null?void 0:o.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${s}`),this.hls.trigger(I.AUDIO_TRACK_LOADING,{url:s,id:i,groupId:n,deliveryDirectives:t||null,track:e})}}class mT{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(this.queues===null||this.tracks===null)return;const n=this.queues[t];n.push(e),n.length===1&&!i&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const n=t[0];try{n.execute()}catch(s){var i;if(n.onError(s),this.queues===null||this.tracks===null)return;const o=(i=this.tracks[e])==null?void 0:i.buffer;o!=null&&o.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
2507
2507
  ${this.list("video")}
2508
2508
  ${this.list("audio")}
2509
2509
  ${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=(t=this.tracks)==null?void 0:t[e],n=i==null?void 0:i.buffer;return n?`SourceBuffer${n.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}}const Mf=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Ff="HlsJsTrackRemovedError";class ET extends Error{constructor(e){super(e),this.name=Ff}}class IT extends _i{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=i=>{var n;this.hls&&((n=this.mediaSource)==null?void 0:n.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=i=>{const{media:n,mediaSource:s}=this;i&&this.log("Media source opened"),!(!n||!s)&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(I.MEDIA_ATTACHED,{media:n,mediaSource:s}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:n}=this;i!==n&&this.error(`Media element src was set while attaching MediaSource (${n} > ${i})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=Hy(Zi(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.BUFFER_RESET,this.onBufferReset,this),e.on(I.BUFFER_APPENDING,this.onBufferAppending,this),e.on(I.BUFFER_CODECS,this.onBufferCodecs,this),e.on(I.BUFFER_EOS,this.onBufferEos,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(I.FRAG_PARSED,this.onFragParsed,this),e.on(I.FRAG_CHANGED,this.onFragChanged,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.BUFFER_RESET,this.onBufferReset,this),e.off(I.BUFFER_APPENDING,this.onBufferAppending,this),e.off(I.BUFFER_CODECS,this.onBufferCodecs,this),e.off(I.BUFFER_EOS,this.onBufferEos,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(I.FRAG_PARSED,this.onFragParsed,this),e.off(I.FRAG_CHANGED,this.onFragChanged,this),e.off(I.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const s=this.isUpdating();s||this.operationQueue.removeBlockers();const o=this.isQueued();(s||o)&&this.warn(`Transfering MediaSource with${o?" operations in queue":""}${s?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?qe(i,n.tracks):this.sourceBuffers.forEach(s=>{const[o]=s;o&&(i[o]=qe({},this.tracks[o]),this.removeBuffer(o)),s[0]=s[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var i;let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media,n=Zi(this.appendSource);if(this.transferData=this.overrides=void 0,i&&n){const s=!!t.mediaSource;(s||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const o=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(o),s)this._objectUrl=i.src,this.attachTransferred();else{const a=this._objectUrl=self.URL.createObjectURL(o);if(this.appendSource)try{i.removeAttribute("src");const l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&o instanceof l,Pf(i),vT(i,a),i.load()}catch{i.src=a}else i.src=a}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const i=this.tracks,n=t.tracks,s=n?Object.keys(n):null,o=s?s.length:0,a=()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()};if(n&&s&&o){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
2510
2510
  required tracks: ${rt(i,(l,A)=>l==="initSegment"?void 0:A)};
2511
- transfer tracks: ${rt(n,(l,A)=>l==="initSegment"?void 0:A)}}`),!Yh(n,i)){t.mediaSource=null,t.tracks=void 0;const l=e.currentTime,A=this.details,u=Math.max(l,(A==null?void 0:A.fragments[0].start)||0);if(u-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(i)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(I.MEDIA_DETACHING,{}),this.onMediaAttaching(I.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,s.forEach(l=>{const A=l,u=n[A];if(u){const c=u.buffer;if(c){const h=this.fragmentTracker,d=u.id;if(h.hasFragments(d)||h.hasParts(d)){const p=Le.getBuffered(c);h.detectEvictedFragments(A,p,d,null,!0)}const f=AA(A),g=[A,c];this.sourceBuffers[f]=g,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(A),this.trackSourceBuffer(A,u)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:s,_objectUrl:o}=this;if(s){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([a])=>{a&&this.removeBuffer(a)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const a=s.readyState==="open";try{const l=s.sourceBuffers;for(let A=l.length;A--;)a&&l[A].abort(),s.removeSourceBuffer(l[A]);a&&s.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),i||(o&&self.URL.revokeObjectURL(o),this.mediaSrc===o?(n.removeAttribute("src"),this.appendSource&&Pf(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(I.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(s){this.warn(`onBufferReset ${e}`,s)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[AA(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new mT(this.tracks)}onBufferCodecs(e,t){const i=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);const s="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!s&&this.sourceBufferCount&&this.media&&n.some(a=>!i[a]);if(s||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${n}" SourceBuffers`);return}n.forEach(a=>{var l,A,u;const c=t[a],{id:h,codec:d,levelCodec:f,container:g,metadata:p,supplemental:v}=c;let B=i[a];const C=(l=this.transferData)==null||(A=l.tracks)==null?void 0:A[a],y=C!=null&&C.buffer?C:B,x=(y==null?void 0:y.pendingCodec)||(y==null?void 0:y.codec),w=y==null?void 0:y.levelCodec;B||(B=i[a]={buffer:void 0,listeners:[],codec:d,supplemental:v,container:g,levelCodec:f,metadata:p,id:h});const D=go(x,w),F=D==null?void 0:D.replace(Mf,"$1");let O=go(d,f);const M=(u=O)==null?void 0:u.replace(Mf,"$1");O&&D&&F!==M&&(a.slice(0,5)==="audio"&&(O=fo(O,this.appendSource)),this.log(`switching codec ${x} to ${O}`),O!==(B.pendingCodec||B.codec)&&(B.pendingCodec=O),B.container=g,this.appendChangeType(a,g,O))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&this.mediaSourceOpenOrEnded&&this.checkPendingTracks()}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const n=`${t};codecs=${i}`,s={label:`change-type=${n}`,execute:()=>{const o=this.tracks[e];if(o){const a=o.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),a.changeType(n),o.codec=i,o.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn(`Failed to change ${e} SourceBuffer type`,o)}};this.append(s,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,n=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,Ee.MAIN))==null?void 0:t.gap)===!0)return;const o={label:"block-audio",execute:()=>{var a;const l=this.tracks.video;(this.lastVideoAppendEnd>n||l!=null&&l.buffer&&Le.isBuffered(l.buffer,n)||((a=this.fragmentTracker.getAppendedFrag(n,Ee.MAIN))==null?void 0:a.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn("Error executing block-audio operation",a)}};this.blockedAudioAppend={op:o,frag:e},this.append(o,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:n,type:s,parent:o,frag:a,part:l,chunkMeta:A}=t,u=A.buffering[s],c=a.sn,h=self.performance.now();u.start=h;const d=a.stats.buffering,f=l?l.stats.buffering:null;d.start===0&&(d.start=h),f&&f.start===0&&(f.start=h);const g=i.audio;let p=!1;s==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(p=!this.lastMpegAudioChunk||A.id===1||this.lastMpegAudioChunk.sn!==A.sn,this.lastMpegAudioChunk=A);const v=this.tracks.video,B=v==null?void 0:v.buffer;if(B&&c!=="initSegment"){const x=l||a,w=this.blockedAudioAppend;if(s==="audio"&&o!=="main"&&!this.blockedAudioAppend){const F=x.start+x.duration*.05,O=B.buffered,M=this.currentOp("video");!O.length&&!M?this.blockAudio(x):!M&&!Le.isBuffered(B,F)&&this.lastVideoAppendEnd<F&&this.blockAudio(x)}else if(s==="video"){const D=x.end;if(w){const F=w.frag.start;(D>F||D<this.lastVideoAppendEnd||Le.isBuffered(B,F))&&this.unblockAudio()}this.lastVideoAppendEnd=D}}const C=(l||a).start,y={label:`append-${s}`,execute:()=>{if(u.executeStart=self.performance.now(),p){const x=this.tracks[s];if(x){const w=x.buffer;if(w){const D=C-w.timestampOffset;Math.abs(D)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${C} (delta: ${D}) sn: ${c})`),w.timestampOffset=C)}}}this.appendExecutor(n,s)},onStart:()=>{},onComplete:()=>{const x=self.performance.now();u.executeEnd=u.end=x,d.first===0&&(d.first=x),f&&f.first===0&&(f.first=x);const w={};this.sourceBuffers.forEach(([D,F])=>{D&&(w[D]=Le.getBuffered(F))}),this.appendErrors[s]=0,s==="audio"||s==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(I.BUFFER_APPENDED,{type:s,frag:a,part:l,chunkMeta:A,parent:a.type,timeRanges:w})},onError:x=>{var w;const D={type:Ie.MEDIA_ERROR,parent:a.type,details:V.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:a,part:l,chunkMeta:A,error:x,err:x,fatal:!1},F=(w=this.media)==null?void 0:w.error;if(x.code===DOMException.QUOTA_EXCEEDED_ERR)D.details=V.BUFFER_FULL_ERROR;else if(x.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!F)D.errorAction=$n(!0);else if(x.name===Ff&&this.sourceBufferCount===0)D.errorAction=$n(!0);else{const O=++this.appendErrors[s];this.warn(`Failed ${O}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${s}" sourceBuffer (${F||"no media error"})`),(O>=this.hls.config.appendErrorMaxRetry||F)&&(D.fatal=!0)}this.hls.trigger(I.ERROR,D)}};this.append(y,s,this.isPending(this.tracks[s]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(I.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:i,startOffset:n,endOffset:s}=t;i?this.append(this.getFlushOp(i,n,s),i):this.sourceBuffers.forEach(([o])=>{o&&this.append(this.getFlushOp(o,n,s),o)})}onFragParsed(e,t){const{frag:i,part:n}=t,s=[],o=n?n.elementaryStreams:i.elementaryStreams;o[Je.AUDIOVIDEO]?s.push("audiovideo"):(o[Je.AUDIO]&&s.push("audio"),o[Je.VIDEO]&&s.push("video"));const a=()=>{const l=self.performance.now();i.stats.buffering.end=l,n&&(n.stats.buffering.end=l);const A=n?n.stats:i.stats;this.hls.trigger(I.FRAG_BUFFERED,{frag:i,part:n,stats:A,id:i.type})};s.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(a,s).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t,i;return e&&(!((t=this.tracks[e])!=null&&t.ended)||((i=this.tracks[e])==null?void 0:i.ending))})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([o])=>{if(o){const a=this.tracks[o];(!t.type||t.type===o)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${o} buffer reached EOS`)))}});const n=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([o])=>{var a;return o&&!((a=this.tracks[o])!=null&&a.ended)})&&(n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:o}=this;if(!o||o.readyState!=="open"){o&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${o.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),o.endOfStream(),this.hls.trigger(I.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(I.BUFFERED_TO_END,void 0)))}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){const e=this.getDurationAndRange();e&&this.blockUntilOpen(()=>this.updateMediaSource(e))}onError(e,t){if(t.details===V.BUFFER_APPEND_ERROR&&t.frag){var i;const n=(i=t.errorAction)==null?void 0:i.nextAutoLevel;de(n)&&n!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;const n=e.config,s=i.currentTime,o=t.levelTargetDuration,a=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(de(a)&&a>=0){const l=Math.max(a,o),A=Math.floor(s/o)*o-l;this.flushBackBuffer(s,o,A)}if(de(n.frontBufferFlushThreshold)&&n.frontBufferFlushThreshold>0){const l=Math.max(n.maxBufferLength,n.frontBufferFlushThreshold),A=Math.max(l,o),u=Math.floor(s/o)*o+A;this.flushFrontBuffer(s,o,u)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([n,s])=>{if(s){const a=Le.getBuffered(s);if(a.length>0&&i>a.start(0)){var o;this.hls.trigger(I.BACK_BUFFER_REACHED,{bufferEnd:i});const l=this.tracks[n];if((o=this.details)!=null&&o.live)this.hls.trigger(I.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l!=null&&l.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([n,s])=>{if(s){const o=Le.getBuffered(s),a=o.length;if(a<2)return;const l=o.start(a-1),A=o.end(a-1);if(i>l||e>=l&&e<=A)return;this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||(i==null?void 0:i.readyState)!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&i.setLiveSeekableRange){const A=Math.max(0,t.fragmentStart),u=Math.max(A,n);return{duration:1/0,start:A,end:u}}return{duration:1/0}}const s=(e=this.overrides)==null?void 0:e.duration;if(s)return de(s)?{duration:s}:null;const o=this.media.duration,a=de(i.duration)?i.duration:0;return n>a&&n>o||!de(o)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:i}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(de(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${i}.`),n.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${rt(i)}`),this.tracksReady){var n;const s=(n=this.transferData)==null?void 0:n.tracks;s&&Object.keys(s).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,i])=>{if(t){const n=this.tracks[t];e[t]={buffer:i,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger(I.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const s in e){const o=s,a=e[o];if(this.isPending(a)){const l=this.getTrackCodec(a,o),A=`${a.container};codecs=${l}`;a.codec=l,this.log(`creating sourceBuffer(${A})${this.currentOp(o)?" Queued":""} ${rt(a)}`);try{const u=i.addSourceBuffer(A),c=AA(o),h=[o,u];t[c]=h,a.buffer=u}catch(u){var n;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(o),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[o],this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:o,mimeType:A,parent:a.id});return}this.trackSourceBuffer(o,a)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let n=e.codec;i&&(t==="video"||t==="audiovideo")&&Ql(i,"video")&&(n=hC(n,i));const s=go(n,e.levelCodec);return s?t.slice(0,5)==="audio"?fo(s,this.appendSource):s:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(s,o)=>{const a=o.removedRanges;a!=null&&a.length&&this.hls.trigger(I.BUFFER_FLUSHED,{type:s})})}get mediaSrc(){var e,t;const i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i==null?void 0:i.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${n}`,t),this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const s=this.currentOp(e);s&&s.onError(n)}removeExecutor(e,t,i){const{media:n,mediaSource:s}=this,o=this.tracks[e],a=o==null?void 0:o.buffer;if(!n||!s||!a){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const l=de(n.duration)?n.duration:1/0,A=de(s.duration)?s.duration:1/0,u=Math.max(0,t),c=Math.min(i,l,A);c>u&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${u},${c}] from the ${e} SourceBuffer`),a.remove(u,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],n=i==null?void 0:i.buffer;if(!n)throw new ET(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,n.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,n=t.map(o=>this.appendBlocker(o));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(o=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;const n=(i=this.tracks[t])==null?void 0:i.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const n=this.tracks[e];if(!n)return;const s=n.buffer;if(!s)return;const o=i.bind(this,e);n.listeners.push({event:t,listener:o}),s.addEventListener(t,o)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(n=>{i.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}}function Pf(r){const e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function vT(r,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}function AA(r){return r==="audio"?1:0}class cA{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.BUFFER_CODECS,this.onBufferCodecs,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.BUFFER_CODECS,this.onBufferCodecs,this),e.off(I.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,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&de(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((n,s)=>this.isLevelAllowed(n)&&s<=e);return this.clientRect=null,cA.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;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 Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const n=(a,l)=>l?a.width!==l.width||a.height!==l.height:!0;let s=e.length-1;const o=Math.max(t,i);for(let a=0;a<e.length;a+=1){const l=e[a];if((l.width>=o||l.height>=o)&&n(l,e[a+1])){s=a;break}}return s}}const Nt={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},yT={HLS:"h"},Xn={OBJECT:"CMCD-Object",REQUEST:"CMCD-Request",SESSION:"CMCD-Session",STATUS:"CMCD-Status"},CT={[Xn.OBJECT]:["br","d","ot","tb"],[Xn.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Xn.SESSION]:["cid","pr","sf","sid","st","v"],[Xn.STATUS]:["bs","rtp"]};class Wr{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Wr?i:new Wr(i))),this.value=e,this.params=t}}const BT="Dict";function TT(r){return Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":typeof r=="object"?JSON.stringify(r):String(r)}function bT(r,e,t,i){return new Error(`failed to ${r} "${TT(e)}" as ${t}`,{cause:i})}function mi(r,e,t){return bT("serialize",r,e,t)}class Nf{constructor(e){this.description=e}}const Of="Bare Item",ST="Boolean";function xT(r){if(typeof r!="boolean")throw mi(r,ST);return r?"?1":"?0"}const QT="Byte Sequence";function _T(r){if(ArrayBuffer.isView(r)===!1)throw mi(r,QT);return`:${wB(r)}:`}const wT="Integer";function RT(r){return r<-999999999999999||999999999999999<r}function Uf(r){if(RT(r))throw mi(r,wT);return r.toString()}function DT(r){return`@${Uf(r.getTime()/1e3)}`}const LT="Decimal";function kT(r){const e=hf(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw mi(r,LT);const t=e.toString();return t.includes(".")?t:`${t}.0`}const MT="String",FT=/[\x00-\x1f\x7f]+/;function PT(r){if(FT.test(r))throw mi(r,MT);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function NT(r){return r.description||r.toString().slice(7,-1)}const OT="Token";function Gf(r){const e=NT(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw mi(e,OT);return e}function uA(r){switch(typeof r){case"number":if(!de(r))throw mi(r,Of);return Number.isInteger(r)?Uf(r):kT(r);case"string":return PT(r);case"symbol":return Gf(r);case"boolean":return xT(r);case"object":if(r instanceof Date)return DT(r);if(r instanceof Uint8Array)return _T(r);if(r instanceof Nf)return Gf(r);default:throw mi(r,Of)}}const UT="Key";function hA(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw mi(r,UT);return r}function dA(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${hA(e)}`:`;${hA(e)}=${uA(t)}`).join("")}function $f(r){return r instanceof Wr?`${uA(r.value)}${dA(r.params)}`:uA(r)}function GT(r){return`(${r.value.map($f).join(" ")})${dA(r.params)}`}function $T(r,e={whitespace:!0}){if(typeof r!="object")throw mi(r,BT);const t=r instanceof Map?r.entries():Object.entries(r),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([n,s])=>{s instanceof Wr||(s=new Wr(s));let o=hA(n);return s.value===!0?o+=dA(s.params):(o+="=",Array.isArray(s.value)?o+=GT(s):o+=$f(s)),o}).join(`,${i}`)}function HT(r,e){return $T(r,e)}function YT(r){return r==="ot"||r==="sf"||r==="st"}function VT(r){return typeof r=="number"?de(r):r!=null&&r!==""&&r!==!1}const ko=r=>Math.round(r),KT=(r,e)=>(e!=null&&e.baseUrl&&(r=RB(r,e.baseUrl)),encodeURIComponent(r)),Mo=r=>ko(r/100)*100,WT={br:ko,d:ko,bl:Mo,dl:Mo,mtp:Mo,nor:KT,rtp:Mo,tb:ko};function qT(r,e){const t={};if(r==null||typeof r!="object")return t;const i=Object.keys(r).sort(),n=qe({},WT,e==null?void 0:e.formatters),s=e==null?void 0:e.filter;return i.forEach(o=>{if(s!=null&&s(o))return;let a=r[o];const l=n[o];l&&(a=l(a,e)),!(o==="v"&&a===1)&&(o=="pr"&&a===1||VT(a)&&(YT(o)&&typeof a=="string"&&(a=new Nf(a)),t[o]=a))}),t}function Hf(r,e={}){return r?HT(qT(r,e),qe({whitespace:!1},e)):""}function JT(r,e={}){const t={};if(!r)return t;const i=Object.entries(r),n=Object.entries(CT).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),s=i.reduce((o,a)=>{var l,A;const[u,c]=a,h=((l=n.find(d=>d[1].includes(u)))===null||l===void 0?void 0:l[0])||Xn.REQUEST;return(A=o[h])!==null&&A!==void 0||(o[h]={}),o[h][u]=c,o},{});return Object.entries(s).reduce((o,[a,l])=>(o[a]=Hf(l,e),o),t)}function jT(r,e,t){return qe(r,JT(e,t))}const XT="CMCD";function zT(r,e={}){if(!r)return"";const t=Hf(r,e);return`${XT}=${encodeURIComponent(t)}`}const Yf=/CMCD=[^&#]+/;function ZT(r,e,t){const i=zT(e,t);if(!i)return r;if(Yf.test(r))return r.replace(Yf,i);const n=r.includes("?")?"&":"?";return`${r}${n}${i}`}class eb{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.includeKeys=void 0,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=n=>{try{this.apply(n,{ot:Nt.MANIFEST,su:!this.initialized})}catch(s){this.hls.logger.warn("Could not generate manifest CMCD data.",s)}},this.applyFragmentData=n=>{try{const{frag:s,part:o}=n,a=this.hls.levels[s.level],l=this.getObjectType(s),A={d:(o||s).duration*1e3,ot:l};(l===Nt.VIDEO||l===Nt.AUDIO||l==Nt.MUXED)&&(A.br=a.bitrate/1e3,A.tb=this.getTopBandwidth(l)/1e3,A.bl=this.getBufferLength(l));const u=o?this.getNextPart(o):this.getNextFrag(s);u!=null&&u.url&&u.url!==s.url&&(A.nor=u.url),this.apply(n,A)}catch(s){this.hls.logger.warn("Could not generate segment CMCD data.",s)}},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||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHED,this.onMediaDetached,this),e.on(I.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHED,this.onMediaDetached,this),e.off(I.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,n;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:yT.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){qe(t,this.createData());const i=t.ot===Nt.INIT||t.ot===Nt.VIDEO||t.ot===Nt.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:n}=this;n&&(t=Object.keys(t).reduce((o,a)=>(n.includes(a)&&(o[a]=t[a]),o),{}));const s={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),jT(e.headers,t,s)):e.url=ZT(e.url,t,s)}getNextFrag(e){var t;const i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){const n=e.sn-i.startSN;return i.fragments[n+1]}}getNextPart(e){var t,i;const{index:n,fragment:s}=e,o=(t=this.hls.levels[s.level])==null||(i=t.details)==null?void 0:i.partList;if(o){const{sn:a}=s;for(let l=o.length-1;l>=0;l--){const A=o[l];if(A.index===n&&A.fragment.sn===a)return o[l+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Nt.TIMED_TEXT;if(e.sn==="initSegment")return Nt.INIT;if(t==="audio")return Nt.AUDIO;if(t==="main")return this.hls.audioTracks.length?Nt.VIDEO:Nt.MUXED}getTopBandwidth(e){let t=0,i;const n=this.hls;if(e===Nt.AUDIO)i=n.audioTracks;else{const s=n.maxAutoLevel,o=s>-1?s+1:n.levels.length;i=n.levels.slice(0,o)}for(const s of i)s.bitrate>t&&(t=s.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===Nt.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:Le.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(s){this.loader=void 0,this.loader=new i(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,o,a){t(s),this.loader.load(s,o,a)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new i(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,o,a){t(s),this.loader.load(s,o,a)}}}}const tb=3e5;class ib extends _i{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){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)===wt.SendAlternateToPenaltyBox&&i.flags===ni.MoveAllAlternatesMatchingHost){const n=this.levels;let s=this._pathwayPriority,o=this.pathwayId;if(t.context){const{groupId:a,pathwayId:l,type:A}=t.context;a&&n?o=this.getPathwayForGroupId(a,A,o):l&&(o=l)}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!s&&n&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==o),i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${o} levels: ${n&&n.length} priorities: ${rt(s)} penalized: ${rt(this.penalizedPathways)}`)}}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}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const i=this.penalizedPathways,n=performance.now();Object.keys(i).forEach(s=>{n-i[s]>tb&&delete i[s]});for(let s=0;s<e.length;s++){const o=e[s];if(o in i)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,zd(t),this.hls.trigger(I.LEVELS_UPDATED,{levels:t});const A=this.hls.levels[a];l&&A&&this.levels&&(A.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&A.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${A.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,i){const n=this.getLevelsForPathway(i).concat(this.levels||[]);for(let s=0;s<n.length;s++)if(t===Me.AUDIO_TRACK&&n[s].hasAudioGroup(e)||t===Me.SUBTITLE_TRACK&&n[s].hasSubtitleGroup(e))return n[s].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},n={};e.forEach(s=>{const{ID:o,"BASE-ID":a,"URI-REPLACEMENT":l}=s;if(t.some(u=>u.pathwayId===o))return;const A=this.getLevelsForPathway(a).map(u=>{const c=new ot(u.attrs);c["PATHWAY-ID"]=o;const h=c.AUDIO&&`${c.AUDIO}_clone_${o}`,d=c.SUBTITLES&&`${c.SUBTITLES}_clone_${o}`;h&&(i[c.AUDIO]=h,c.AUDIO=h),d&&(n[c.SUBTITLES]=d,c.SUBTITLES=d);const f=Kf(u.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new Gn({attrs:c,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:f,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let p=1;p<u.audioGroups.length;p++)g.addGroupId("audio",`${u.audioGroups[p]}_clone_${o}`);if(u.subtitleGroups)for(let p=1;p<u.subtitleGroups.length;p++)g.addGroupId("text",`${u.subtitleGroups[p]}_clone_${o}`);return g});t.push(...A),Vf(this.audioTracks,i,l,o),Vf(this.subtitleTracks,n,l,o)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let n;try{n=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(n.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+u)}const s={responseType:"json",url:n.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},A={onSuccess:(u,c,h,d)=>{this.log(`Loaded steering manifest: "${n}"`);const f=u.data;if((f==null?void 0:f.VERSION)!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":g,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":v}=f;if(g)try{this.uri=new self.URL(g,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||h.url),p&&this.clonePathways(p);const B={steeringManifest:f,url:n.toString()};this.hls.trigger(I.STEERING_MANIFEST_LOADED,B),v&&this.updatePathwayPriority(v)},onError:(u,c,h,d)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${c.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let f=this.timeToLoad*1e3;if(u.code===429){const g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){const p=g.getResponseHeader("Retry-After");p&&(f=parseFloat(p)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,f)},onTimeout:(u,c,h)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(s,l,A)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const n=(i=this.hls)==null?void 0:i.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Vf(r,e,t,i){r&&Object.keys(e).forEach(n=>{const s=r.filter(o=>o.groupId===n).map(o=>{const a=qe({},o);return a.details=void 0,a.attrs=new ot(a.attrs),a.url=a.attrs.URI=Kf(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),a.groupId=a.attrs["GROUP-ID"]=e[n],a.attrs["PATHWAY-ID"]=i,a});r.push(...s)})}function Kf(r,e,t,i){const{HOST:n,PARAMS:s,[t]:o}=i;let a;e&&(a=o==null?void 0:o[e],a&&(r=a));const l=new self.URL(r);return n&&!a&&(l.host=n),s&&Object.keys(s).sort().forEach(A=>{A&&l.searchParams.set(A,s[A])}),l.href}class qr extends _i{constructor(e){super("eme",e.logger),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=qr.CDMCleanupPromise?[qr.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:i,initData:n}=t,s=`"${t.type}" event: init data type: "${i}"`;if(this.debug(s),n!==null){if(!this.keyFormatPromise){let o=Object.keys(this.keySystemAccessPromises);o.length||(o=bo(this.config));const a=o.map(Gl).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(a)}this.keyFormatPromise.then(o=>{const a=Ol(o);let l,A;if(i==="sinf"){if(a!==Ke.FAIRPLAY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${a}`);return}const f=It(new Uint8Array(n));try{const g=Pl(JSON.parse(f).sinf),p=Zh(g);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(p.subarray(8,24)),A=Ke.FAIRPLAY}catch(g){this.warn(`${s} Failed to parse sinf: ${g}`);return}}else{if(a!==Ke.WIDEVINE&&a!==Ke.PLAYREADY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${a}`);return}const f=lC(n),g=f.filter(v=>!!v.systemId&&Ul(v.systemId)===a);g.length>1&&this.warn(`${s} Using first of ${g.length} pssh found for selected key-system ${a}`);const p=g[0];if(!p){f.length===0||f.some(v=>!v.systemId)?this.warn(`${s} contains incomplete or invalid pssh data`):this.log(`ignoring ${s} for ${f.map(v=>Ul(v.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(A=Ul(p.systemId),p.version===0&&p.data)if(A===Ke.WIDEVINE){const v=p.data.length-22;l=new Uint8Array(p.data.subarray(v,v+16))}else A===Ke.PLAYREADY&&(l=kd(p.data))}if(!A||!l)return;const u=ui.hexDump(l),{keyIdToKeySessionPromise:c,mediaKeySessions:h}=this;let d=c[u];for(let f=0;f<h.length;f++){const g=h[f],p=g.decryptdata;if(!p.keyId)continue;const v=ui.hexDump(p.keyId);if(u===v||p.uri.replace(/-/g,"").indexOf(u)!==-1){if(d=c[v],p.pssh)break;delete c[v],p.pssh=new Uint8Array(n),p.keyId=l,d=c[u]=d.then(()=>this.generateRequestWithPreferredKeySession(g,i,n,"encrypted-event-key-match")),d.catch(B=>this.handleError(B));break}}if(!d){if(A!==a){this.log(`Ignoring "${t.type}" event with ${A} init data for selected key-system ${a}`);return}d=c[u]=this.getKeySystemSelectionPromise([A]).then(({keySystem:f,mediaKeys:g})=>{var p;this.throwIfDestroyed();const v=new Hn("ISO-23001-7",u,(p=Gl(f))!=null?p:"");return v.pssh=new Uint8Array(n),v.keyId=l,this.attemptSetMediaKeys(f,g).then(()=>{this.throwIfDestroyed();const B=this.createMediaKeySessionContext({decryptdata:v,keySystem:f,mediaKeys:g});return this.generateRequestWithPreferredKeySession(B,i,n,"encrypted-event-no-match")})}),d.catch(f=>this.handleError(f))}})}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){const e=this.media;this.unregisterListeners(),this.onMediaDetached(),this._clear(e);const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(I.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(I.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,n=t[e];if(n)return n.licenseUrl;if(e===Ke.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}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,n=t.map(o=>o.audioCodec).filter(i),s=t.map(o=>o.videoCodec).filter(i);return n.length+s.length===0&&s.push("avc1.42e01e"),new Promise((o,a)=>{const l=A=>{const u=A.shift();this.getMediaKeysPromise(u,n,s).then(c=>o({keySystem:u,mediaKeys:c})).catch(c=>{A.length?l(A):c instanceof Xt?a(c):a(new Xt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_NO_ACCESS,error:c,fatal:!0},c.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Ld===null&&self.location.protocol==="http:"&&(n=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(n))}return i(e,t)}getMediaKeysPromise(e,t,i){const n=ZC(e,t,i,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e];let o=s==null?void 0:s.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${rt(n)}`),o=this.requestMediaKeySystemAccess(e,n);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 A=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),a.mediaKeys=l.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),A.then(c=>c?this.setMediaKeysServerCertificate(u,e,c):u))),a.mediaKeys.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),a.mediaKeys})}return o.then(()=>s.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${ui.hexDump(e.keyId||[])}`);const n=i.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),n=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(i,s,t.pssh.buffer,"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 ui.hexDump(e.keyId)}updateKeySession(e,t){var i;const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyID ${ui.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])}
2511
+ transfer tracks: ${rt(n,(l,A)=>l==="initSegment"?void 0:A)}}`),!Yh(n,i)){t.mediaSource=null,t.tracks=void 0;const l=e.currentTime,A=this.details,u=Math.max(l,(A==null?void 0:A.fragments[0].start)||0);if(u-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(i)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(I.MEDIA_DETACHING,{}),this.onMediaAttaching(I.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,s.forEach(l=>{const A=l,u=n[A];if(u){const c=u.buffer;if(c){const h=this.fragmentTracker,d=u.id;if(h.hasFragments(d)||h.hasParts(d)){const p=Le.getBuffered(c);h.detectEvictedFragments(A,p,d,null,!0)}const f=AA(A),g=[A,c];this.sourceBuffers[f]=g,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(A),this.trackSourceBuffer(A,u)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:s,_objectUrl:o}=this;if(s){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([a])=>{a&&this.removeBuffer(a)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const a=s.readyState==="open";try{const l=s.sourceBuffers;for(let A=l.length;A--;)a&&l[A].abort(),s.removeSourceBuffer(l[A]);a&&s.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),i||(o&&self.URL.revokeObjectURL(o),this.mediaSrc===o?(n.removeAttribute("src"),this.appendSource&&Pf(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(I.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(s){this.warn(`onBufferReset ${e}`,s)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[AA(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new mT(this.tracks)}onBufferCodecs(e,t){const i=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);const s="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!s&&this.sourceBufferCount&&this.media&&n.some(a=>!i[a]);if(s||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${n}" SourceBuffers`);return}n.forEach(a=>{var l,A,u;const c=t[a],{id:h,codec:d,levelCodec:f,container:g,metadata:p,supplemental:v}=c;let B=i[a];const C=(l=this.transferData)==null||(A=l.tracks)==null?void 0:A[a],y=C!=null&&C.buffer?C:B,x=(y==null?void 0:y.pendingCodec)||(y==null?void 0:y.codec),w=y==null?void 0:y.levelCodec;B||(B=i[a]={buffer:void 0,listeners:[],codec:d,supplemental:v,container:g,levelCodec:f,metadata:p,id:h});const D=go(x,w),F=D==null?void 0:D.replace(Mf,"$1");let O=go(d,f);const M=(u=O)==null?void 0:u.replace(Mf,"$1");O&&D&&F!==M&&(a.slice(0,5)==="audio"&&(O=fo(O,this.appendSource)),this.log(`switching codec ${x} to ${O}`),O!==(B.pendingCodec||B.codec)&&(B.pendingCodec=O),B.container=g,this.appendChangeType(a,g,O))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&this.mediaSourceOpenOrEnded&&this.checkPendingTracks()}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const n=`${t};codecs=${i}`,s={label:`change-type=${n}`,execute:()=>{const o=this.tracks[e];if(o){const a=o.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),a.changeType(n),o.codec=i,o.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn(`Failed to change ${e} SourceBuffer type`,o)}};this.append(s,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,n=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,Ee.MAIN))==null?void 0:t.gap)===!0)return;const o={label:"block-audio",execute:()=>{var a;const l=this.tracks.video;(this.lastVideoAppendEnd>n||l!=null&&l.buffer&&Le.isBuffered(l.buffer,n)||((a=this.fragmentTracker.getAppendedFrag(n,Ee.MAIN))==null?void 0:a.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn("Error executing block-audio operation",a)}};this.blockedAudioAppend={op:o,frag:e},this.append(o,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:n,type:s,parent:o,frag:a,part:l,chunkMeta:A}=t,u=A.buffering[s],c=a.sn,h=self.performance.now();u.start=h;const d=a.stats.buffering,f=l?l.stats.buffering:null;d.start===0&&(d.start=h),f&&f.start===0&&(f.start=h);const g=i.audio;let p=!1;s==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(p=!this.lastMpegAudioChunk||A.id===1||this.lastMpegAudioChunk.sn!==A.sn,this.lastMpegAudioChunk=A);const v=this.tracks.video,B=v==null?void 0:v.buffer;if(B&&c!=="initSegment"){const x=l||a,w=this.blockedAudioAppend;if(s==="audio"&&o!=="main"&&!this.blockedAudioAppend){const F=x.start+x.duration*.05,O=B.buffered,M=this.currentOp("video");!O.length&&!M?this.blockAudio(x):!M&&!Le.isBuffered(B,F)&&this.lastVideoAppendEnd<F&&this.blockAudio(x)}else if(s==="video"){const D=x.end;if(w){const F=w.frag.start;(D>F||D<this.lastVideoAppendEnd||Le.isBuffered(B,F))&&this.unblockAudio()}this.lastVideoAppendEnd=D}}const C=(l||a).start,y={label:`append-${s}`,execute:()=>{if(u.executeStart=self.performance.now(),p){const x=this.tracks[s];if(x){const w=x.buffer;if(w){const D=C-w.timestampOffset;Math.abs(D)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${C} (delta: ${D}) sn: ${c})`),w.timestampOffset=C)}}}this.appendExecutor(n,s)},onStart:()=>{},onComplete:()=>{const x=self.performance.now();u.executeEnd=u.end=x,d.first===0&&(d.first=x),f&&f.first===0&&(f.first=x);const w={};this.sourceBuffers.forEach(([D,F])=>{D&&(w[D]=Le.getBuffered(F))}),this.appendErrors[s]=0,s==="audio"||s==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(I.BUFFER_APPENDED,{type:s,frag:a,part:l,chunkMeta:A,parent:a.type,timeRanges:w})},onError:x=>{var w;const D={type:Ie.MEDIA_ERROR,parent:a.type,details:V.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:a,part:l,chunkMeta:A,error:x,err:x,fatal:!1},F=(w=this.media)==null?void 0:w.error;if(x.code===DOMException.QUOTA_EXCEEDED_ERR)D.details=V.BUFFER_FULL_ERROR;else if(x.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!F)D.errorAction=$n(!0);else if(x.name===Ff&&this.sourceBufferCount===0)D.errorAction=$n(!0);else{const O=++this.appendErrors[s];this.warn(`Failed ${O}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${s}" sourceBuffer (${F||"no media error"})`),(O>=this.hls.config.appendErrorMaxRetry||F)&&(D.fatal=!0)}this.hls.trigger(I.ERROR,D)}};this.append(y,s,this.isPending(this.tracks[s]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(I.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:i,startOffset:n,endOffset:s}=t;i?this.append(this.getFlushOp(i,n,s),i):this.sourceBuffers.forEach(([o])=>{o&&this.append(this.getFlushOp(o,n,s),o)})}onFragParsed(e,t){const{frag:i,part:n}=t,s=[],o=n?n.elementaryStreams:i.elementaryStreams;o[Je.AUDIOVIDEO]?s.push("audiovideo"):(o[Je.AUDIO]&&s.push("audio"),o[Je.VIDEO]&&s.push("video"));const a=()=>{const l=self.performance.now();i.stats.buffering.end=l,n&&(n.stats.buffering.end=l);const A=n?n.stats:i.stats;this.hls.trigger(I.FRAG_BUFFERED,{frag:i,part:n,stats:A,id:i.type})};s.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(a,s).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t,i;return e&&(!((t=this.tracks[e])!=null&&t.ended)||((i=this.tracks[e])==null?void 0:i.ending))})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([o])=>{if(o){const a=this.tracks[o];(!t.type||t.type===o)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${o} buffer reached EOS`)))}});const n=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([o])=>{var a;return o&&!((a=this.tracks[o])!=null&&a.ended)})&&(n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:o}=this;if(!o||o.readyState!=="open"){o&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${o.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),o.endOfStream(),this.hls.trigger(I.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(I.BUFFERED_TO_END,void 0)))}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){const e=this.getDurationAndRange();e&&this.blockUntilOpen(()=>this.updateMediaSource(e))}onError(e,t){if(t.details===V.BUFFER_APPEND_ERROR&&t.frag){var i;const n=(i=t.errorAction)==null?void 0:i.nextAutoLevel;de(n)&&n!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;const n=e.config,s=i.currentTime,o=t.levelTargetDuration,a=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(de(a)&&a>=0){const l=Math.max(a,o),A=Math.floor(s/o)*o-l;this.flushBackBuffer(s,o,A)}if(de(n.frontBufferFlushThreshold)&&n.frontBufferFlushThreshold>0){const l=Math.max(n.maxBufferLength,n.frontBufferFlushThreshold),A=Math.max(l,o),u=Math.floor(s/o)*o+A;this.flushFrontBuffer(s,o,u)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([n,s])=>{if(s){const a=Le.getBuffered(s);if(a.length>0&&i>a.start(0)){var o;this.hls.trigger(I.BACK_BUFFER_REACHED,{bufferEnd:i});const l=this.tracks[n];if((o=this.details)!=null&&o.live)this.hls.trigger(I.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l!=null&&l.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([n,s])=>{if(s){const o=Le.getBuffered(s),a=o.length;if(a<2)return;const l=o.start(a-1),A=o.end(a-1);if(i>l||e>=l&&e<=A)return;this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||(i==null?void 0:i.readyState)!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&i.setLiveSeekableRange){const A=Math.max(0,t.fragmentStart),u=Math.max(A,n);return{duration:1/0,start:A,end:u}}return{duration:1/0}}const s=(e=this.overrides)==null?void 0:e.duration;if(s)return de(s)?{duration:s}:null;const o=this.media.duration,a=de(i.duration)?i.duration:0;return n>a&&n>o||!de(o)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:i}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(de(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${i}.`),n.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${rt(i)}`),this.tracksReady){var n;const s=(n=this.transferData)==null?void 0:n.tracks;s&&Object.keys(s).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,i])=>{if(t){const n=this.tracks[t];e[t]={buffer:i,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger(I.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const s in e){const o=s,a=e[o];if(this.isPending(a)){const l=this.getTrackCodec(a,o),A=`${a.container};codecs=${l}`;a.codec=l,this.log(`creating sourceBuffer(${A})${this.currentOp(o)?" Queued":""} ${rt(a)}`);try{const u=i.addSourceBuffer(A),c=AA(o),h=[o,u];t[c]=h,a.buffer=u}catch(u){var n;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(o),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[o],this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:o,mimeType:A,parent:a.id});return}this.trackSourceBuffer(o,a)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let n=e.codec;i&&(t==="video"||t==="audiovideo")&&Ql(i,"video")&&(n=hC(n,i));const s=go(n,e.levelCodec);return s?t.slice(0,5)==="audio"?fo(s,this.appendSource):s:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(s,o)=>{const a=o.removedRanges;a!=null&&a.length&&this.hls.trigger(I.BUFFER_FLUSHED,{type:s})})}get mediaSrc(){var e,t;const i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i==null?void 0:i.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${n}`,t),this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const s=this.currentOp(e);s&&s.onError(n)}removeExecutor(e,t,i){const{media:n,mediaSource:s}=this,o=this.tracks[e],a=o==null?void 0:o.buffer;if(!n||!s||!a){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const l=de(n.duration)?n.duration:1/0,A=de(s.duration)?s.duration:1/0,u=Math.max(0,t),c=Math.min(i,l,A);c>u&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${u},${c}] from the ${e} SourceBuffer`),a.remove(u,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],n=i==null?void 0:i.buffer;if(!n)throw new ET(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,n.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,n=t.map(o=>this.appendBlocker(o));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(o=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;const n=(i=this.tracks[t])==null?void 0:i.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const n=this.tracks[e];if(!n)return;const s=n.buffer;if(!s)return;const o=i.bind(this,e);n.listeners.push({event:t,listener:o}),s.addEventListener(t,o)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(n=>{i.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}}function Pf(r){const e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function vT(r,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}function AA(r){return r==="audio"?1:0}class cA{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.BUFFER_CODECS,this.onBufferCodecs,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.BUFFER_CODECS,this.onBufferCodecs,this),e.off(I.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,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&de(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((n,s)=>this.isLevelAllowed(n)&&s<=e);return this.clientRect=null,cA.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;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 Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const n=(a,l)=>l?a.width!==l.width||a.height!==l.height:!0;let s=e.length-1;const o=Math.max(t,i);for(let a=0;a<e.length;a+=1){const l=e[a];if((l.width>=o||l.height>=o)&&n(l,e[a+1])){s=a;break}}return s}}const Nt={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},yT={HLS:"h"},Xn={OBJECT:"CMCD-Object",REQUEST:"CMCD-Request",SESSION:"CMCD-Session",STATUS:"CMCD-Status"},CT={[Xn.OBJECT]:["br","d","ot","tb"],[Xn.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Xn.SESSION]:["cid","pr","sf","sid","st","v"],[Xn.STATUS]:["bs","rtp"]};class Wr{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Wr?i:new Wr(i))),this.value=e,this.params=t}}const BT="Dict";function TT(r){return Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":typeof r=="object"?JSON.stringify(r):String(r)}function bT(r,e,t,i){return new Error(`failed to ${r} "${TT(e)}" as ${t}`,{cause:i})}function mi(r,e,t){return bT("serialize",r,e,t)}class Nf{constructor(e){this.description=e}}const Of="Bare Item",ST="Boolean";function xT(r){if(typeof r!="boolean")throw mi(r,ST);return r?"?1":"?0"}const QT="Byte Sequence";function _T(r){if(ArrayBuffer.isView(r)===!1)throw mi(r,QT);return`:${wB(r)}:`}const wT="Integer";function RT(r){return r<-999999999999999||999999999999999<r}function Uf(r){if(RT(r))throw mi(r,wT);return r.toString()}function DT(r){return`@${Uf(r.getTime()/1e3)}`}const LT="Decimal";function kT(r){const e=hf(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw mi(r,LT);const t=e.toString();return t.includes(".")?t:`${t}.0`}const MT="String",FT=/[\x00-\x1f\x7f]+/;function PT(r){if(FT.test(r))throw mi(r,MT);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function NT(r){return r.description||r.toString().slice(7,-1)}const OT="Token";function Gf(r){const e=NT(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw mi(e,OT);return e}function uA(r){switch(typeof r){case"number":if(!de(r))throw mi(r,Of);return Number.isInteger(r)?Uf(r):kT(r);case"string":return PT(r);case"symbol":return Gf(r);case"boolean":return xT(r);case"object":if(r instanceof Date)return DT(r);if(r instanceof Uint8Array)return _T(r);if(r instanceof Nf)return Gf(r);default:throw mi(r,Of)}}const UT="Key";function hA(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw mi(r,UT);return r}function dA(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${hA(e)}`:`;${hA(e)}=${uA(t)}`).join("")}function $f(r){return r instanceof Wr?`${uA(r.value)}${dA(r.params)}`:uA(r)}function GT(r){return`(${r.value.map($f).join(" ")})${dA(r.params)}`}function $T(r,e={whitespace:!0}){if(typeof r!="object")throw mi(r,BT);const t=r instanceof Map?r.entries():Object.entries(r),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([n,s])=>{s instanceof Wr||(s=new Wr(s));let o=hA(n);return s.value===!0?o+=dA(s.params):(o+="=",Array.isArray(s.value)?o+=GT(s):o+=$f(s)),o}).join(`,${i}`)}function HT(r,e){return $T(r,e)}function YT(r){return r==="ot"||r==="sf"||r==="st"}function VT(r){return typeof r=="number"?de(r):r!=null&&r!==""&&r!==!1}const ko=r=>Math.round(r),KT=(r,e)=>(e!=null&&e.baseUrl&&(r=RB(r,e.baseUrl)),encodeURIComponent(r)),Mo=r=>ko(r/100)*100,WT={br:ko,d:ko,bl:Mo,dl:Mo,mtp:Mo,nor:KT,rtp:Mo,tb:ko};function qT(r,e){const t={};if(r==null||typeof r!="object")return t;const i=Object.keys(r).sort(),n=qe({},WT,e==null?void 0:e.formatters),s=e==null?void 0:e.filter;return i.forEach(o=>{if(s!=null&&s(o))return;let a=r[o];const l=n[o];l&&(a=l(a,e)),!(o==="v"&&a===1)&&(o=="pr"&&a===1||VT(a)&&(YT(o)&&typeof a=="string"&&(a=new Nf(a)),t[o]=a))}),t}function Hf(r,e={}){return r?HT(qT(r,e),qe({whitespace:!1},e)):""}function JT(r,e={}){const t={};if(!r)return t;const i=Object.entries(r),n=Object.entries(CT).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),s=i.reduce((o,a)=>{var l,A;const[u,c]=a,h=((l=n.find(d=>d[1].includes(u)))===null||l===void 0?void 0:l[0])||Xn.REQUEST;return(A=o[h])!==null&&A!==void 0||(o[h]={}),o[h][u]=c,o},{});return Object.entries(s).reduce((o,[a,l])=>(o[a]=Hf(l,e),o),t)}function jT(r,e,t){return qe(r,JT(e,t))}const XT="CMCD";function zT(r,e={}){if(!r)return"";const t=Hf(r,e);return`${XT}=${encodeURIComponent(t)}`}const Yf=/CMCD=[^&#]+/;function ZT(r,e,t){const i=zT(e,t);if(!i)return r;if(Yf.test(r))return r.replace(Yf,i);const n=r.includes("?")?"&":"?";return`${r}${n}${i}`}class eb{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.includeKeys=void 0,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=n=>{try{this.apply(n,{ot:Nt.MANIFEST,su:!this.initialized})}catch(s){this.hls.logger.warn("Could not generate manifest CMCD data.",s)}},this.applyFragmentData=n=>{try{const{frag:s,part:o}=n,a=this.hls.levels[s.level],l=this.getObjectType(s),A={d:(o||s).duration*1e3,ot:l};(l===Nt.VIDEO||l===Nt.AUDIO||l==Nt.MUXED)&&(A.br=a.bitrate/1e3,A.tb=this.getTopBandwidth(l)/1e3,A.bl=this.getBufferLength(l));const u=o?this.getNextPart(o):this.getNextFrag(s);u!=null&&u.url&&u.url!==s.url&&(A.nor=u.url),this.apply(n,A)}catch(s){this.hls.logger.warn("Could not generate segment CMCD data.",s)}},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||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHED,this.onMediaDetached,this),e.on(I.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHED,this.onMediaDetached,this),e.off(I.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,n;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:yT.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){qe(t,this.createData());const i=t.ot===Nt.INIT||t.ot===Nt.VIDEO||t.ot===Nt.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:n}=this;n&&(t=Object.keys(t).reduce((o,a)=>(n.includes(a)&&(o[a]=t[a]),o),{}));const s={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),jT(e.headers,t,s)):e.url=ZT(e.url,t,s)}getNextFrag(e){var t;const i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){const n=e.sn-i.startSN;return i.fragments[n+1]}}getNextPart(e){var t,i;const{index:n,fragment:s}=e,o=(t=this.hls.levels[s.level])==null||(i=t.details)==null?void 0:i.partList;if(o){const{sn:a}=s;for(let l=o.length-1;l>=0;l--){const A=o[l];if(A.index===n&&A.fragment.sn===a)return o[l+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Nt.TIMED_TEXT;if(e.sn==="initSegment")return Nt.INIT;if(t==="audio")return Nt.AUDIO;if(t==="main")return this.hls.audioTracks.length?Nt.VIDEO:Nt.MUXED}getTopBandwidth(e){let t=0,i;const n=this.hls;if(e===Nt.AUDIO)i=n.audioTracks;else{const s=n.maxAutoLevel,o=s>-1?s+1:n.levels.length;i=n.levels.slice(0,o)}for(const s of i)s.bitrate>t&&(t=s.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===Nt.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:Le.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(s){this.loader=void 0,this.loader=new i(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,o,a){t(s),this.loader.load(s,o,a)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new i(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,o,a){t(s),this.loader.load(s,o,a)}}}}const tb=3e5;class ib extends _i{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){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)===Rt.SendAlternateToPenaltyBox&&i.flags===ni.MoveAllAlternatesMatchingHost){const n=this.levels;let s=this._pathwayPriority,o=this.pathwayId;if(t.context){const{groupId:a,pathwayId:l,type:A}=t.context;a&&n?o=this.getPathwayForGroupId(a,A,o):l&&(o=l)}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!s&&n&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==o),i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${o} levels: ${n&&n.length} priorities: ${rt(s)} penalized: ${rt(this.penalizedPathways)}`)}}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}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const i=this.penalizedPathways,n=performance.now();Object.keys(i).forEach(s=>{n-i[s]>tb&&delete i[s]});for(let s=0;s<e.length;s++){const o=e[s];if(o in i)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,zd(t),this.hls.trigger(I.LEVELS_UPDATED,{levels:t});const A=this.hls.levels[a];l&&A&&this.levels&&(A.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&A.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${A.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,i){const n=this.getLevelsForPathway(i).concat(this.levels||[]);for(let s=0;s<n.length;s++)if(t===Me.AUDIO_TRACK&&n[s].hasAudioGroup(e)||t===Me.SUBTITLE_TRACK&&n[s].hasSubtitleGroup(e))return n[s].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},n={};e.forEach(s=>{const{ID:o,"BASE-ID":a,"URI-REPLACEMENT":l}=s;if(t.some(u=>u.pathwayId===o))return;const A=this.getLevelsForPathway(a).map(u=>{const c=new ot(u.attrs);c["PATHWAY-ID"]=o;const h=c.AUDIO&&`${c.AUDIO}_clone_${o}`,d=c.SUBTITLES&&`${c.SUBTITLES}_clone_${o}`;h&&(i[c.AUDIO]=h,c.AUDIO=h),d&&(n[c.SUBTITLES]=d,c.SUBTITLES=d);const f=Kf(u.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new Gn({attrs:c,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:f,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let p=1;p<u.audioGroups.length;p++)g.addGroupId("audio",`${u.audioGroups[p]}_clone_${o}`);if(u.subtitleGroups)for(let p=1;p<u.subtitleGroups.length;p++)g.addGroupId("text",`${u.subtitleGroups[p]}_clone_${o}`);return g});t.push(...A),Vf(this.audioTracks,i,l,o),Vf(this.subtitleTracks,n,l,o)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let n;try{n=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(n.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+u)}const s={responseType:"json",url:n.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},A={onSuccess:(u,c,h,d)=>{this.log(`Loaded steering manifest: "${n}"`);const f=u.data;if((f==null?void 0:f.VERSION)!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":g,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":v}=f;if(g)try{this.uri=new self.URL(g,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||h.url),p&&this.clonePathways(p);const B={steeringManifest:f,url:n.toString()};this.hls.trigger(I.STEERING_MANIFEST_LOADED,B),v&&this.updatePathwayPriority(v)},onError:(u,c,h,d)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${c.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let f=this.timeToLoad*1e3;if(u.code===429){const g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){const p=g.getResponseHeader("Retry-After");p&&(f=parseFloat(p)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,f)},onTimeout:(u,c,h)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(s,l,A)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const n=(i=this.hls)==null?void 0:i.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Vf(r,e,t,i){r&&Object.keys(e).forEach(n=>{const s=r.filter(o=>o.groupId===n).map(o=>{const a=qe({},o);return a.details=void 0,a.attrs=new ot(a.attrs),a.url=a.attrs.URI=Kf(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),a.groupId=a.attrs["GROUP-ID"]=e[n],a.attrs["PATHWAY-ID"]=i,a});r.push(...s)})}function Kf(r,e,t,i){const{HOST:n,PARAMS:s,[t]:o}=i;let a;e&&(a=o==null?void 0:o[e],a&&(r=a));const l=new self.URL(r);return n&&!a&&(l.host=n),s&&Object.keys(s).sort().forEach(A=>{A&&l.searchParams.set(A,s[A])}),l.href}class qr extends _i{constructor(e){super("eme",e.logger),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=qr.CDMCleanupPromise?[qr.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:i,initData:n}=t,s=`"${t.type}" event: init data type: "${i}"`;if(this.debug(s),n!==null){if(!this.keyFormatPromise){let o=Object.keys(this.keySystemAccessPromises);o.length||(o=bo(this.config));const a=o.map(Gl).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(a)}this.keyFormatPromise.then(o=>{const a=Ol(o);let l,A;if(i==="sinf"){if(a!==Ke.FAIRPLAY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${a}`);return}const f=It(new Uint8Array(n));try{const g=Pl(JSON.parse(f).sinf),p=Zh(g);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(p.subarray(8,24)),A=Ke.FAIRPLAY}catch(g){this.warn(`${s} Failed to parse sinf: ${g}`);return}}else{if(a!==Ke.WIDEVINE&&a!==Ke.PLAYREADY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${a}`);return}const f=lC(n),g=f.filter(v=>!!v.systemId&&Ul(v.systemId)===a);g.length>1&&this.warn(`${s} Using first of ${g.length} pssh found for selected key-system ${a}`);const p=g[0];if(!p){f.length===0||f.some(v=>!v.systemId)?this.warn(`${s} contains incomplete or invalid pssh data`):this.log(`ignoring ${s} for ${f.map(v=>Ul(v.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(A=Ul(p.systemId),p.version===0&&p.data)if(A===Ke.WIDEVINE){const v=p.data.length-22;l=new Uint8Array(p.data.subarray(v,v+16))}else A===Ke.PLAYREADY&&(l=kd(p.data))}if(!A||!l)return;const u=ui.hexDump(l),{keyIdToKeySessionPromise:c,mediaKeySessions:h}=this;let d=c[u];for(let f=0;f<h.length;f++){const g=h[f],p=g.decryptdata;if(!p.keyId)continue;const v=ui.hexDump(p.keyId);if(u===v||p.uri.replace(/-/g,"").indexOf(u)!==-1){if(d=c[v],p.pssh)break;delete c[v],p.pssh=new Uint8Array(n),p.keyId=l,d=c[u]=d.then(()=>this.generateRequestWithPreferredKeySession(g,i,n,"encrypted-event-key-match")),d.catch(B=>this.handleError(B));break}}if(!d){if(A!==a){this.log(`Ignoring "${t.type}" event with ${A} init data for selected key-system ${a}`);return}d=c[u]=this.getKeySystemSelectionPromise([A]).then(({keySystem:f,mediaKeys:g})=>{var p;this.throwIfDestroyed();const v=new Hn("ISO-23001-7",u,(p=Gl(f))!=null?p:"");return v.pssh=new Uint8Array(n),v.keyId=l,this.attemptSetMediaKeys(f,g).then(()=>{this.throwIfDestroyed();const B=this.createMediaKeySessionContext({decryptdata:v,keySystem:f,mediaKeys:g});return this.generateRequestWithPreferredKeySession(B,i,n,"encrypted-event-no-match")})}),d.catch(f=>this.handleError(f))}})}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){const e=this.media;this.unregisterListeners(),this.onMediaDetached(),this._clear(e);const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(I.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(I.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,n=t[e];if(n)return n.licenseUrl;if(e===Ke.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}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,n=t.map(o=>o.audioCodec).filter(i),s=t.map(o=>o.videoCodec).filter(i);return n.length+s.length===0&&s.push("avc1.42e01e"),new Promise((o,a)=>{const l=A=>{const u=A.shift();this.getMediaKeysPromise(u,n,s).then(c=>o({keySystem:u,mediaKeys:c})).catch(c=>{A.length?l(A):c instanceof Xt?a(c):a(new Xt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_NO_ACCESS,error:c,fatal:!0},c.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Ld===null&&self.location.protocol==="http:"&&(n=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(n))}return i(e,t)}getMediaKeysPromise(e,t,i){const n=ZC(e,t,i,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e];let o=s==null?void 0:s.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${rt(n)}`),o=this.requestMediaKeySystemAccess(e,n);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 A=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),a.mediaKeys=l.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),A.then(c=>c?this.setMediaKeysServerCertificate(u,e,c):u))),a.mediaKeys.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),a.mediaKeys})}return o.then(()=>s.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${ui.hexDump(e.keyId||[])}`);const n=i.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),n=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(i,s,t.pssh.buffer,"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 ui.hexDump(e.keyId)}updateKeySession(e,t){var i;const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyID ${ui.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])}
2512
2512
  } (data length: ${t&&t.byteLength})`),n.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 n=bo(this.config),s=e.map(Ol).filter(o=>!!o&&n.indexOf(o)!==-1);return this.getKeySystemSelectionPromise(s).then(({keySystem:o})=>{const a=Gl(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),n=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);let s=this.keyIdToKeySessionPromise[i];return s||(s=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(a,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:a,mediaKeys:l,decryptdata:t}))))),(this.keyIdToKeySessionPromise[i]=s.then(a=>{const l="cenc",A=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(a,l,A,"playlist-key")})).catch(a=>this.handleError(a))),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Xt?this.hls.trigger(I.ERROR,e.data):this.hls.trigger(I.ERROR,{type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const n=Ol(e.keyFormat),s=n?[n]:bo(this.config);return this.attemptKeySystemAccess(s)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=bo(this.config)),e.length===0)throw new Xt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${rt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=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(n),n.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(s=>i.indexOf(s)===-1)})}generateRequestWithPreferredKeySession(e,t,i,n){var s,o;const a=(s=this.config.drmSystems)==null||(o=s[e.keySystem])==null?void 0:o.generateRequest;if(a)try{const f=a.call(this.hls,t,i,e);if(!f)throw new Error("Invalid response from configured generateRequest filter");t=f.initDataType,i=f.initData?f.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(f){var l;if(this.warn(f.message),(l=this.hls)!=null&&l.config.debug)throw f}if(i===null)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const A=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${n}": ${A} (init data type: ${t} length: ${i?i.byteLength:null})`);const u=new ql,c=e._onmessage=f=>{const g=e.mediaKeysSession;if(!g){u.emit("error",new Error("invalid state"));return}const{messageType:p,message:v}=f;this.log(`"${p}" message event for session "${g.sessionId}" message size: ${v.byteLength}`),p==="license-request"||p==="license-renewal"?this.renewLicense(e,v).catch(B=>{u.eventNames().length?u.emit("error",B):this.handleError(B)}):p==="license-release"?e.keySystem===Ke.FAIRPLAY&&(this.updateKeySession(e,Nl("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${p}"`)},h=e._onkeystatuseschange=f=>{if(!e.mediaKeysSession){u.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const p=e.keyStatus;u.emit("keyStatus",p),p==="expired"&&(this.warn(`${e.keySystem} expired for key ${A}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",c),e.mediaKeysSession.addEventListener("keystatuseschange",h);const d=new Promise((f,g)=>{u.on("error",g),u.on("keyStatus",p=>{p.startsWith("usable")?f():p==="output-restricted"?g(new Xt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):p==="internal-error"?g(new Xt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${p}"`)):p==="expired"?g(new Error("key expired while generating request")):this.warn(`unhandled key status change "${p}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var f;this.log(`Request generated for key-session "${(f=e.mediaKeysSession)==null?void 0:f.sessionId}" keyId: ${A}`)}).catch(f=>{throw new Xt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_NO_SESSION,error:f,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>d).catch(f=>{throw u.removeAllListeners(),this.removeSession(e),f}).then(()=>(u.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{if(typeof i=="string"&&typeof t=="object"){const n=i;i=t,t=n}this.log(`key status change "${t}" for keyStatuses keyId: ${ui.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${ui.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,i=t.loader,n=new i(t),s=this.getServerCertificateUrl(e);return s?(this.log(`Fetching server certificate for "${e}"`),new Promise((o,a)=>{const l={responseType:"arraybuffer",url:s},A=t.certLoadPolicy.default,u={loadPolicy:A,timeout:A.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,d,f,g)=>{o(h.data)},onError:(h,d,f,g)=>{a(new Xt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:Ve({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${s}). Status: ${h.code} (${h.text})`))},onTimeout:(h,d,f)=>{a(new Xt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${s})`))},onAbort:(h,d,f)=>{a(new Error("aborted"))}};n.load(l,u,c)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((n,s)=>{e.setServerCertificate(i).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),n(e)}).catch(o=>{s(new Xt({type:Ie.KEY_SYSTEM_ERROR,details:V.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(n=>{throw new Xt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:n,fatal:!0},n.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const n=new DOMParser().parseFromString(i,"application/xml"),s=n.querySelectorAll("HttpHeader");if(s.length>0){let u;for(let c=0,h=s.length;c<h;c++){var o,a;u=s[c];const d=(o=u.querySelector("name"))==null?void 0:o.textContent,f=(a=u.querySelector("value"))==null?void 0:a.textContent;d&&f&&e.setRequestHeader(d,f)}}const l=n.querySelector("Challenge"),A=l==null?void 0:l.textContent;if(!A)throw new Error("Cannot find <Challenge> in key message");return Nl(atob(A))}setupLicenseXHR(e,t,i,n){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,t,i,n)}).catch(o=>{if(!i.decryptdata)throw o;return e.open("POST",t,!0),s.call(this.hls,e,t,i,n)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((n,s)=>{const o=this.getLicenseServerUrlOrThrow(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 s(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 A=this.config.licenseResponseCallback;if(A)try{l=A.call(this.hls,a,o,e)}catch(u){this.error(u)}n(l)}else{const l=i.errorRetry,A=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>A||a.status>=400&&a.status<500)s(new Xt({type:Ie.KEY_SYSTEM_ERROR,details:V.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 u=A-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(n,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,o,e,t).then(({xhr:l,licenseChallenge:A})=>{e.keySystem==Ke.PLAYREADY&&(A=this.unpackPlayReadyKeyMessage(l,A)),l.send(A)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.removeEventListener("encrypted",this.onMediaEncrypted),i.removeEventListener("waitingforkey",this.onWaitingForKey),i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null)}_clear(e){var t;const i=this.mediaKeySessions;this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Hn.clearKeyUriToKeyIdMap();const n=i.length;qr.CDMCleanupPromise=Promise.all(i.map(s=>this.removeSession(s)).concat(e==null||(t=e.setMediaKeys(null))==null?void 0:t.catch(s=>{var o;this.log(`Could not clear media keys: ${s}`),(o=this.hls)==null||o.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${s}`)})}))).then(()=>{n&&(this.log("finished closing key sessions and clearing media keys"),i.length=0)}).catch(s=>{var o;this.log(`Could not close sessions and clear media keys: ${s}`),(o=this.hls)==null||o.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${s}`)})})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((n,s)=>(n.indexOf(s.keyFormat)===-1&&n.push(s.keyFormat),n),[]);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}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);const{drmSystemOptions:s}=this.config;return(tB(s)?new Promise((a,l)=>{self.setTimeout(()=>l(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(a)}):Promise.resolve()).catch(a=>{var l;this.log(`Could not remove session: ${a}`),(l=this.hls)==null||l.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${a}`)})}).then(()=>t.close()).catch(a=>{var l;this.log(`Could not close session: ${a}`),(l=this.hls)==null||l.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${a}`)})})}}}qr.CDMCleanupPromise=void 0;class Xt 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}}class rb{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(I.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(I.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(I.MEDIA_DETACHING,this.onMediaDetaching,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 n=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=n,n&&typeof n.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){const n=performance.now();if(t){if(this.lastTime){const s=n-this.lastTime,o=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,l=1e3*o/s,A=this.hls;if(A.trigger(I.FPS_DROP,{currentDropped:o,currentDecoded:a,totalDroppedFrames:i}),l>0&&o>A.config.fpsDroppedMonitoringThreshold*a){let u=A.currentLevel;A.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(A.autoLevelCapping===-1||A.autoLevelCapping>=u)&&(u=u-1,A.trigger(I.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:A.currentLevel}),A.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=n,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)}}function Wf(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 qf(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){Ue.debug(`[texttrack-utils]: ${i}`);try{const n=new self.TextTrackCue(e.startTime,e.endTime,e.text);n.id=e.id,r.addCue(n)}catch(n){Ue.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(r.mode=t)}function Jr(r,e){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues)for(let i=r.cues.length;i--;)e&&r.cues[i].removeEventListener("enter",e),r.removeCue(r.cues[i]);t==="disabled"&&(r.mode=t)}function fA(r,e,t,i){const n=r.mode;if(n==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){const s=sb(r.cues,e,t);for(let o=0;o<s.length;o++)(!i||i(s[o]))&&r.removeCue(s[o])}n==="disabled"&&(r.mode=n)}function nb(r,e){if(e<=r[0].startTime)return 0;const t=r.length-1;if(e>r[t].endTime)return-1;let i=0,n=t,s;for(;i<=n;)if(s=Math.floor((n+i)/2),e<r[s].startTime)n=s-1;else if(e>r[s].startTime&&i<t)i=s+1;else return s;return r[i].startTime-e<e-r[n].startTime?i:n}function sb(r,e,t){const i=[],n=nb(r,e);if(n>-1)for(let s=n,o=r.length;s<o;s++){const a=r[s];if(a.startTime>=e&&a.endTime<=t)i.push(a);else if(a.startTime>t)return i}return i}function Fo(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 ob extends aA{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=Fo(this.media.textTracks);for(let s=0;s<i.length;s++)if(i[s].mode==="hidden")t=i[s];else if(i[s].mode==="showing"){t=i[s];break}const n=this.findTrackForTextTrack(t);this.subtitleTrack!==n&&this.setSubtitleTrack(n)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(I.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const n=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,n)return;Fo(i.textTracks).forEach(o=>{Jr(o)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:n,details:s}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==n){this.warn(`Subtitle track with id:${i} and group:${n} not found in active group ${o==null?void 0:o.groupId}`);return}const a=o.details;o.details=t.details,this.log(`Subtitle track ${i} "${o.name}" lang:${o.lang} group:${n} 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)return;const i=t.subtitleGroups||null,n=this.groupIds;let s=this.currentTrack;if(!i||(n==null?void 0:n.length)!==(i==null?void 0:i.length)||i!=null&&i.some(o=>(n==null?void 0:n.indexOf(o))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(u=>!i||i.indexOf(u.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(u=>u.default)&&(this.selectDefaultTrack=!1),o.forEach((u,c)=>{u.id=c});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const a=this.hls.config.subtitlePreference;if(!s&&a){this.selectDefaultTrack=!1;const u=fi(a,o);if(u>-1)s=o[u];else{const c=fi(a,this.tracks);s=this.tracks[c]}}let l=this.findTrackId(s);l===-1&&s&&(l=this.findTrackId(null));const A={subtitleTracks:o};this.log(`Updating subtitle tracks, ${o.length} track(s) found in "${i==null?void 0:i.join(",")}" group-id`),this.hls.trigger(I.SUBTITLE_TRACKS_UPDATED,A),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let n=0;n<t.length;n++){const s=t[n];if(!(i&&!s.default||!i&&!e)&&(!e||yr(s,e)))return n}if(e){for(let n=0;n<t.length;n++){const s=t[n];if(jn(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(let n=0;n<t.length;n++){const s=t[n];if(jn(e.attrs,s.attrs,["LANGUAGE"]))return n}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const n=t[i];if(lA(n,e))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Me.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&yr(e,i))return i;const n=fi(e,this.tracksInGroup);if(n>-1){const s=this.tracksInGroup[n];return this.setSubtitleTrack(n),s}else{if(i)return null;{const s=fi(e,t);if(s>-1)return t[s]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,n=e.groupId,s=this.getUrlWithDirectives(e.url,t),o=e.details,a=o==null?void 0:o.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${s}`),this.hls.trigger(I.SUBTITLE_TRACK_LOADING,{url:s,id:i,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Fo(e.textTracks),i=this.currentTrack;let n;if(i&&(n=t.filter(s=>lA(i,s))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(s=>{s.mode!=="disabled"&&s!==n&&(s.mode="disabled")}),n){const s=this.subtitleDisplay?"showing":"hidden";n.mode!==s&&(n.mode=s)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!de(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e]||null;if(this.trackId=e,this.currentTrack=n,this.toggleTrackModes(),!n){this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{id:e});return}const s=!!n.details&&!n.details.live;if(e===this.trackId&&n===i&&s)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:o,groupId:a="",name:l,type:A,url:u}=n;this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{id:o,groupId:a,name:l,type:A,url:u});const c=this.switchParams(n.url,i==null?void 0:i.details,n.details);this.loadPlaylist(c)}}function zn(r){let e=5381,t=r.length;for(;t;)e=e*33^r.charCodeAt(--t);return(e>>>0).toString()}const jr=.025;let Po=function(r){return r[r.Point=0]="Point",r[r.Range=1]="Range",r}({});function ab(r,e,t){return`${r.identifier}-${t+1}-${zn(e)}`}class lb{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){if(e>=this.assetList.length)return!0;const t=this.playoutLimit;return e<=0||isNaN(t)?!1:this.assetList[e].startOffset>t}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return gA(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,i=gA(t,e);return t-i<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=de(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return gA(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<jr))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?Po.Range:Po.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return Ab(this)}}function gA(r,e){return r-e.start<e.duration/2&&!(Math.abs(r-(e.start+e.duration))<jr)?e.start:e.start+e.duration}function Jf(r,e,t){const i=new self.URL(r,t);return i.protocol!=="data:"&&i.searchParams.set("_HLS_primary_id",e),i}function Ab(r){return`["${r.identifier}" ${r.cue.pre?"<pre>":r.cue.post?"<post>":""}${r.timelineStart.toFixed(2)}-${r.resumeTime.toFixed(2)}]`}function pA(r){const e=r.timelineStart,t=r.duration||0;return`["${r.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class cb{constructor(e,t,i,n){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{const A=this.interstitial.playoutLimit,u=this.currentTime;this.startOffset+u>=A&&this.hls.trigger(I.PLAYOUT_LIMIT_REACHED,{})};const s=this.hls=new e(t);this.interstitial=i,this.assetItem=n;let o=n.uri;try{o=Jf(o,s.sessionId).href}catch{}s.loadSource(o);const a=()=>{this.hasDetails=!0};s.once(I.LEVEL_LOADED,a),s.once(I.AUDIO_TRACK_LOADED,a),s.once(I.SUBTITLE_TRACK_LOADED,a),s.on(I.MEDIA_ATTACHING,(l,{media:A})=>{this.removeMediaListeners(),this.mediaAttached=A,this.interstitial.playoutLimit&&A.addEventListener("timeupdate",this.checkPlayout)})}bufferedInPlaceToEnd(e){var t;if(!this.interstitial.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e||!this._bufferedEosTime)return!1;const i=this.timelineOffset,n=Le.bufferInfo(e,i,0);return this.getAssetTime(n.end)>=this._bufferedEosTime-.02}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=Le.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;return e||0}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const i=e-t;if(Math.abs(i)>11111111111111112e-21){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){this.hls.attachMedia(e)}detachMedia(){this.removeMediaListeners(),this.mediaAttached=null,this.hls.detachMedia()}resumeBuffering(){this.hls.resumeBuffering()}pauseBuffering(){this.hls.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls.transferMedia()}on(e,t,i){this.hls.on(e,t)}once(e,t,i){this.hls.once(e,t)}off(e,t,i){this.hls.off(e,t)}toString(){var e,t;return`HlsAssetPlayer: ${pA(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${(t=this.interstitial)!=null&&t.appendInPlace?"append-in-place":""}`}}const jf=.033;class ub extends _i{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,n)=>e<=n.startOffset&&t>n.startOffset?(delete n.error,i+1):i,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const n=this.items;if(n)for(n[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(s=n[i])!=null&&s.event;){var s;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let n=0;n<i.length;n++){let s=i[n];if(t&&t!=="primary"&&(s=s[t]),e===s.start||e>s.start&&e<s.end)return n}return-1}findJumpRestrictedIndex(e,t){const i=this.items;if(i)for(let n=e;n<=t&&i[n];n++){const s=i[n].event;if(s!=null&&s.restrictions.jump&&!s.appendInPlace)return n}return-1}findEventIndex(e){const t=this.items;if(t)for(let n=t.length;n--;){var i;if(((i=t[n].event)==null?void 0:i.identifier)===e)return n}return-1}findAssetIndex(e,t){const i=e.assetList,n=i.length;if(n>1)for(let s=0;s<n;s++){const o=i[s];if(!o.error){const a=o.timelineStart;if(t===a||t>a&&t<a+(o.duration||0))return s}}return 0}get assetIdAtEnd(){var e,t;const i=(e=this.items)==null||(t=e[this.length-1])==null?void 0:t.event;if(i){const n=i.assetList,s=n[n.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t){const i=e.main.details,{dateRanges:n}=i,s=this.events,o=this.parseDateRanges(n,{url:i.url},t),a=Object.keys(n),l=s?s.filter(A=>!a.includes(A.identifier)):[];o.length&&o.sort((A,u)=>{const c=A.cue.pre,h=A.cue.post,d=u.cue.pre,f=u.cue.post;if(c&&!d)return-1;if(d&&!c||h&&!f)return 1;if(f&&!h)return-1;if(!c&&!d&&!h&&!f){const g=A.startTime,p=u.startTime;if(g!==p)return g-p}return A.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=o,l.forEach(A=>{this.removeEvent(A)}),this.updateSchedule(e,l)}updateSchedule(e,t=[]){const i=this.events||[];if(i.length||t.length||this.length<2){const n=this.items,s=this.parseSchedule(i,e);(t.length||(n==null?void 0:n.length)!==s.length||s.some((a,l)=>Math.abs(a.playout.start-n[l].playout.start)>.005||Math.abs(a.playout.end-n[l].playout.end)>.005))&&(this.items=s,this.onScheduleUpdate(t,n))}}parseDateRanges(e,t,i){const n=[],s=Object.keys(e);for(let o=0;o<s.length;o++){const a=s[o],l=e[a];if(l.isInterstitial){let A=this.eventMap[a];A?A.setDateRange(l):(A=new lb(l,t),this.eventMap[a]=A,i===!1&&(A.appendInPlace=i)),n.push(A)}}return n}parseSchedule(e,t){const i=[],n=t.main.details,s=n.live?1/0:n.edge;let o=0;if(e=e.filter(l=>!l.error&&!(l.cue.once&&l.hasPlayed)),e.length){this.resolveOffsets(e,t);let l=0,A=0;if(e.forEach((u,c)=>{const h=u.cue.pre,d=u.cue.post,f=e[c-1]||null,g=u.appendInPlace,p=d?s:u.startOffset,v=u.duration,B=u.timelineOccupancy===Po.Range?v:0,C=u.resumptionOffset,y=(f==null?void 0:f.startTime)===p,x=p+u.cumulativeDuration;let w=g?x+v:p+C;if(h||!d&&p<=0){const F=A;A+=B,u.timelineStart=x;const O=o;o+=v,i.push({event:u,start:x,end:w,playout:{start:O,end:o},integrated:{start:F,end:A}})}else if(p<=s){if(!y){const M=p-l;if(M>jf){const j=l,X=A;A+=M;const le=o;o+=M;const oe={previousEvent:e[c-1]||null,nextEvent:u,start:j,end:j+M,playout:{start:le,end:o},integrated:{start:X,end:A}};i.push(oe)}else M>0&&f&&(f.cumulativeDuration+=M,i[i.length-1].end=p)}d&&(w=x),u.timelineStart=x;const F=A;A+=B;const O=o;o+=v,i.push({event:u,start:x,end:w,playout:{start:O,end:o},integrated:{start:F,end:A}})}else return;const D=u.resumeTime;d||D>s?l=s:l=D}),l<s){var a;const u=l,c=A,h=s-l;A+=h;const d=o;o+=h,i.push({previousEvent:((a=i[i.length-1])==null?void 0:a.event)||null,nextEvent:null,start:l,end:u+h,playout:{start:d,end:o},integrated:{start:c,end:A}})}this.setDurations(s,o,A)}else i.push({previousEvent:null,nextEvent:null,start:0,end:s,playout:{start:0,end:s},integrated:{start:0,end:s}}),this.setDurations(s,s,s);return i}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){const i=t.main.details,n=i.live?1/0:i.edge;let s=0,o=-1;e.forEach((a,l)=>{const A=a.cue.pre,u=a.cue.post,c=A?0:u?n:a.startTime;this.updateAssetDurations(a),o===c?a.cumulativeDuration=s:(s=0,o=c),!u&&a.snapOptions.in&&(a.resumeAnchor=Br(null,i.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)),!a.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<jf&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`));const d=de(a.resumeOffset)?a.resumeOffset:a.duration;s+=d})}primaryCanResumeInPlaceAt(e,t){const i=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(i-n)>jr?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${n}`),!1):t?!Object.keys(t).some(o=>{const a=t[o].details,l=a.edge;if(i>=l)return this.log(`"${e.identifier}" resumption ${i} past ${o} playlist end ${l}`),!1;const A=Br(null,a.fragments,i);if(!A)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${o} playlist (${a.fragStart}-${a.fragmentEnd})`),!0;const u=o==="audio"?.175:0;return Math.abs(A.start-i)<jr+u||Math.abs(A.end-i)<jr+u?!1:(this.log(`"${e.identifier}" resumption ${i} not aligned with ${o} fragment bounds (${A.start}-${A.end} sn: ${A.sn} cc: ${A.cc})`),!0)}):(this.log(`"${e.identifier}" resumption ${i} can not be aligned with media (none selected)`),!1)}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let i=0,n=!1,s=!1;e.assetList.forEach((o,a)=>{const l=t+i;o.startOffset=i,o.timelineStart=l,n||(n=o.duration===null),s||(s=!!o.error);const A=o.error?0:o.duration||0;i+=A}),n&&!s?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function rr(r){return`[${r.event?'"'+r.event.identifier+'"':"primary"}: ${r.start.toFixed(2)}-${r.end.toFixed(2)}]`}class hb{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const i=e.assetListUrl;let n;try{n=Jf(i,this.hls.sessionId,e.baseUrl)}catch(h){const d=this.assignAssetListError(e,V.ASSET_LIST_LOAD_ERROR,h,i);this.hls.trigger(I.ERROR,d);return}t&&n.protocol!=="data:"&&n.searchParams.set("_HLS_start_offset",""+t);const s=this.hls.config,o=s.loader,a=new o(s),l={responseType:"json",url:n.href},A=s.interstitialAssetListLoadPolicy.default,u={loadPolicy:A,timeout:A.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,d,f,g)=>{const p=h.data,v=p==null?void 0:p.ASSETS;if(!Array.isArray(v)){const B=this.assignAssetListError(e,V.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),f.url,d,g);this.hls.trigger(I.ERROR,B);return}e.assetListResponse=p,this.hls.trigger(I.ASSET_LIST_LOADED,{event:e,assetListResponse:p,networkDetails:g})},onError:(h,d,f,g)=>{const p=this.assignAssetListError(e,V.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${d.url})`),d.url,g,f);this.hls.trigger(I.ERROR,p)},onTimeout:(h,d,f)=>{const g=this.assignAssetListError(e,V.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${d.url})`),d.url,h,f);this.hls.trigger(I.ERROR,g)}};return a.load(l,u,c),this.hls.trigger(I.ASSET_LIST_LOADING,{event:e}),a}assignAssetListError(e,t,i,n,s,o){return e.error=i,{type:Ie.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:i,networkDetails:o,stats:s}}}function Li(r,e,t){Ei(r,e,t),r.addEventListener(e,t)}function Ei(r,e,t){r.removeEventListener(e,t)}function Xf(r){r==null||r.play().catch(()=>{})}class db extends _i{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;const n=i-this.timelinePos;if(Math.abs(n)<1/7056e5)return;const o=n<=-.01;this.timelinePos=i,this.bufferedPos=i;const a=this.playingItem;if(!a){this.checkBuffer();return}if(o&&this.schedule.resetErrorsInRange(i,i-n)&&this.updateSchedule(),this.checkBuffer(),o&&i<a.start||i>=a.end){var l;const h=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(a)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!o){const d=this.findItemIndex(a);if(h>d){const f=this.schedule.findJumpRestrictedIndex(d+1,h);if(f>d){this.setSchedulePosition(f);return}}}this.setSchedulePosition(h);return}const A=this.playingAsset;if(!A){if(this.playingLastItem&&this.isInterstitial(a)){const h=a.event.assetList[0];h&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,h))}return}const u=A.timelineStart,c=A.duration||0;(o&&i<u||i>=u+c)&&this.setScheduleToAssetAtTime(i,A)},this.onTimeupdate=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;const n=this.playingItem;if(!n||this.playingLastItem)return;if(i>=n.end){this.timelinePos=n.end;const a=this.findItemIndex(n);this.setSchedulePosition(a+1)}const s=this.playingAsset;if(!s)return;const o=s.timelineStart+(s.duration||0);i>=o&&this.setScheduleToAssetAtTime(i,s)},this.onScheduleUpdate=(i,n)=>{const s=this.schedule,o=this.playingItem,a=s.events||[],l=s.items||[],A=s.durations,u=i.map(d=>d.identifier),c=!!(a.length||u.length);if(c&&this.log(`INTERSTITIALS_UPDATED (${a.length}): ${a}
2513
2513
  Schedule: ${l.map(d=>rr(d))}`),u.length&&this.log(`Removed events ${u}`),this.playerQueue.forEach(d=>{if(d.interstitial.appendInPlace){const f=d.assetItem.timelineStart,g=d.timelineOffset-f;if(g)try{d.timelineOffset=f}catch(p){Math.abs(g)>jr&&this.warn(`${p} ("${d.assetId}" ${d.timelineOffset}->${f})`)}}}),o){const d=this.updateItem(o,this.timelinePos);this.itemsMatch(o,d)&&(this.playingItem=d,this.waitingItem=this.endedItem=null)}else this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const h=this.bufferingItem;if(h){const d=this.updateItem(h,this.bufferedPos);this.itemsMatch(h,d)?this.bufferingItem=d:h.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(h.event,null))}if(i.forEach(d=>{d.assetList.forEach(f=>{this.clearAssetPlayer(f.identifier,null)})}),c||n){if(this.hls.trigger(I.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:l.slice(0),durations:A,removedIds:u}),this.isInterstitial(o)&&u.includes(o.event.identifier)){this.warn(`Interstitial "${o.event.identifier}" removed while playing`),this.primaryFallback(o.event);return}this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new hb(e),this.schedule=new ub(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(I.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(I.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(I.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(I.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(I.BUFFER_APPENDED,this.onBufferAppended,this),e.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(I.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(I.MEDIA_ENDED,this.onMediaEnded,this),e.on(I.ERROR,this.onError,this),e.on(I.DESTROYING,this.onDestroying,this)}unregisterListeners(){const e=this.hls;e&&(e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(I.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(I.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(I.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(I.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(I.BUFFER_CODECS,this.onBufferCodecs,this),e.off(I.BUFFER_APPENDED,this.onBufferAppended,this),e.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(I.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(I.MEDIA_ENDED,this.onMediaEnded,this),e.off(I.ERROR,this.onError,this),e.off(I.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.manager=null,this.hls=this.HlsPlayerClass=this.schedule=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Ei(e,"play",this.onPlay),Ei(e,"pause",this.onPause),Ei(e,"seeking",this.onSeeking),Ei(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;Li(i,"seeking",this.onSeeking),Li(i,"timeupdate",this.onTimeupdate),Li(i,"play",this.onPlay),Li(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!n){this.clearScheduleState();const s=this.findItemIndex(i);this.setSchedulePosition(s)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const i=!!t.transferMedia,n=this.media;if(this.media=null,!i&&(n&&this.removeMediaListeners(n),this.detachedData)){const s=this.getBufferingPlayer();s&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,s.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.manager){if(!this.hls)return null;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=c=>c&&e.getAssetPlayer(c.identifier),n=(c,h,d,f,g)=>{if(c){let p=c[h].start;const v=c.event;if(v){if(h==="playout"||v.timelineOccupancy!==Po.Point){const B=i(d);(B==null?void 0:B.interstitial)===v&&(p+=B.assetItem.startOffset+B[g])}}else{const B=f==="bufferedPos"?o():e[f];p+=B-c.start}return p}return 0},s=(c,h)=>{if(c!==0&&h!=="primary"&&e.schedule.length){var d;const f=e.schedule.findItemIndexAtTime(c),g=(d=e.schedule.items)==null?void 0:d[f];if(g){const p=g[h].start-g.start;return c+p}}return c},o=()=>{const c=e.bufferedPos;return c===Number.MAX_VALUE?a("primary"):Math.max(c,0)},a=c=>{var h;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:e.schedule.durations[c]},l=(c,h)=>{var d,f;const g=e.effectivePlayingItem;if(g!=null&&(d=g.event)!=null&&d.restrictions.skip)return;e.log(`seek to ${c} "${h}"`);const p=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(c,h),B=(f=e.schedule.items)==null?void 0:f[v],C=e.getBufferingPlayer(),y=C==null?void 0:C.interstitial,x=y==null?void 0:y.appendInPlace,w=p&&e.itemsMatch(p,B);if(p&&(x||w)){const F=i(e.playingAsset),O=(F==null?void 0:F.media)||e.primaryMedia;if(O){const M=h==="primary"?O.currentTime:n(p,h,e.playingAsset,"timelinePos","currentTime"),j=c-M,X=(x?M:O.currentTime)+j;if(X>=0&&(!F||x||X<=F.duration)){O.currentTime=X;return}}}if(B){let F=c;if(h!=="primary"){const M=B[h].start,j=c-M;F=B.start+j}const O=!e.isInterstitial(B);if((!e.isInterstitial(p)||p.event.appendInPlace)&&(O||B.event.appendInPlace)){const M=e.media||(x?C==null?void 0:C.media:null);M&&(M.currentTime=F)}else if(p){const M=e.findItemIndex(p);if(v>M){const X=e.schedule.findJumpRestrictedIndex(M+1,v);if(X>M){e.setSchedulePosition(X);return}}let j=0;if(O)e.timelinePos=F,e.checkBuffer();else{var D;const X=B==null||(D=B.event)==null?void 0:D.assetList;if(X){const le=c-(B[h]||B).start;for(let oe=X.length;oe--;){const L=X[oe];if(L.duration&&le>=L.startOffset&&le<L.startOffset+L.duration){j=oe;break}}}}e.setSchedulePosition(v,j)}}},A=()=>{const c=e.effectivePlayingItem;if(e.isInterstitial(c))return c;const h=t();return e.isInterstitial(h)?h:null},u={get currentTime(){const c=A(),h=e.effectivePlayingItem;return h&&h===c?n(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(c){const h=A(),d=e.effectivePlayingItem;d&&d===h&&l(c+d.playout.start,"playout")},get duration(){const c=A();return c?c.playout.end-c.playout.start:0},get assetPlayers(){var c;const h=(c=A())==null?void 0:c.event.assetList;return h?h.map(d=>e.getAssetPlayer(d.identifier)):[]},get playingIndex(){var c;const h=(c=A())==null?void 0:c.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return A()}};this.manager={get events(){var c,h;return((c=e.schedule)==null||(h=c.events)==null?void 0:h.slice(0))||[]},get schedule(){var c,h;return((c=e.schedule)==null||(h=c.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return A()?u:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const c=t();return e.findItemIndex(c)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const c=e.effectivePlayingItem;return e.findItemIndex(c)},primary:{get bufferedEnd(){return o()},get currentTime(){const c=e.timelinePos;return c>0?c:0},set currentTime(c){l(c,"primary")},get duration(){return a("primary")},get seekableStart(){var c;return((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0}},integrated:{get bufferedEnd(){return n(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return n(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(c){l(c,"integrated")},get duration(){return a("integrated")},get seekableStart(){var c;return s(((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0,"integrated")}},skip:()=>{const c=e.effectivePlayingItem,h=c==null?void 0:c.event;if(h&&!h.restrictions.skip){const d=e.findItemIndex(c);if(h.appendInPlace){const f=c.playout.start+c.event.duration;l(f+.001,"playout")}else e.advanceAfterAssetEnded(h,d,1/0)}}}}return this.manager}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t,i;if(this.mediaSelection===null)return;const n=this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&!n.event.appendInPlace)return;let s=this.media;!s&&(e=this.bufferingItem)!=null&&(t=e.event)!=null&&t.appendInPlace&&(s=this.primaryMedia);const o=(i=s)==null?void 0:i.currentTime;if(!(o===void 0||!de(o)))return o}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const i=e.interstitial.appendInPlace,n=e.media;if(i&&n===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&n){this.detachedData={media:n};return}const s=e.transferMedia();this.log(`transfer MediaSource from ${e} ${rt(s)}`),this.detachedData=s}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(e,t){var i,n;if(e.media===t)return;let s=null;const o=this.hls,a=e!==o,l=a&&e.interstitial.appendInPlace,A=(i=this.detachedData)==null?void 0:i.mediaSource;let u;if(o.media)l&&(s=o.transferMedia(),this.detachedData=s),u="Primary";else if(A){const d=this.getBufferingPlayer();d?(s=d.transferMedia(),u=`${d}`):u="detached MediaSource"}else u="detached media";if(!s){if(A)s=this.detachedData,this.log(`using detachedData: MediaSource ${rt(s)}`);else if(!this.detachedData||o.media===t){const d=this.playerQueue;d.length>1&&d.forEach(f=>{if(a&&f.interstitial.appendInPlace!==l){const g=f.interstitial;this.clearInterstitial(f.interstitial,null),g.appendInPlace=!1,g.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${g}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const c=s&&"mediaSource"in s&&((n=s.mediaSource)==null?void 0:n.readyState)!=="closed",h=c&&s?s:t;if(this.log(`${c?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${u}`),h===s){const d=a&&e.assetId===this.schedule.assetIdAtEnd;h.overrides={duration:this.schedule.duration,endOfStream:!a||d,cueRemoval:!a}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const i=this.timelinePos,n=this.effectivePlayingItem;if(i===-1){const s=this.hls.startPosition;if(this.timelinePos=s,t.length&&t[0].cue.pre){const o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(s>=0||!this.primaryLive){const o=this.timelinePos=s>0?s:0,a=e.findItemIndexAtTime(o);this.setSchedulePosition(a)}}else if(n&&!this.playingItem){const s=e.findItemIndex(n);this.setSchedulePosition(s)}}advanceAfterAssetEnded(e,t,i){const n=i+1;if(!e.isAssetPastPlayoutLimit(n)&&!e.assetList[n].error)this.setSchedulePosition(t,n);else{const s=this.schedule.items;if(s){const o=t+1,a=s.length;if(o>=a){this.setSchedulePosition(-1);return}const l=e.resumeTime;this.timelinePos<l&&(this.timelinePos=l,this.checkBuffer()),this.setSchedulePosition(o)}}}setScheduleToAssetAtTime(e,t){const i=this.schedule,n=t.parentIdentifier,s=i.getEvent(n);if(s){const o=i.findEventIndex(n),a=i.findAssetIndex(s,e);this.setSchedulePosition(o,a)}}setSchedulePosition(e,t){const i=this.schedule.items;if(!i||this.playbackDisabled)return;this.log(`setSchedulePosition ${e}, ${t}`);const n=e>=0?i[e]:null,s=this.playingItem,o=this.playingLastItem;if(this.isInterstitial(s)){var a;const A=s.event,u=this.playingAsset,c=u==null?void 0:u.identifier,h=c?this.getAssetPlayer(c):null;if(h&&c&&(!this.eventItemsMatch(s,n)||t!==void 0&&c!==((a=A.assetList)==null?void 0:a[t].identifier))){var l;const d=A.findAssetIndex(u);this.log(`INTERSTITIAL_ASSET_ENDED ${d+1}/${A.assetList.length} ${pA(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(I.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:d,event:A,schedule:i.slice(0),scheduleIndex:e,player:h}),this.retreiveMediaSource(c,n),h.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&h.detachMedia()}if(!this.eventItemsMatch(s,n)&&(this.endedItem=s,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${A} ${rr(s)}`),A.hasPlayed=!0,this.hls.trigger(I.INTERSTITIAL_ENDED,{event:A,schedule:i.slice(0),scheduleIndex:e}),A.cue.once)){this.updateSchedule();const d=this.schedule.items;if(n&&d){const f=this.schedule.findItemIndex(n);this.advanceSchedule(f,d,t,s,o)}return}}this.advanceSchedule(e,i,t,s,o)}advanceSchedule(e,t,i,n,s){const o=e>=0?t[e]:null,a=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(A=>{const u=A.interstitial,c=this.schedule.findEventIndex(u.identifier);(c<e||c>e+1)&&this.clearInterstitial(u,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const A=o.event;i===void 0&&(i=this.schedule.findAssetIndex(A,this.timelinePos));const u=this.waitingItem;this.assetsBuffered(o,a)||this.setBufferingItem(o);let c=this.preloadAssets(A,i);if(this.eventItemsMatch(o,u||n)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${rr(o)} ${A.appendInPlace?"append in place":""}`),this.hls.trigger(I.INTERSTITIAL_STARTED,{event:A,schedule:t.slice(0),scheduleIndex:e})),!A.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${A}`);return}if(A.assetListLoader&&(A.assetListLoader.destroy(),A.assetListLoader=void 0),!a){this.log(`Waiting for attachMedia to start Interstitial ${A}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const h=A.assetList[i];if(!h){const d=t[e+1],f=this.media;d&&f&&!this.isInterstitial(d)&&f.currentTime<d.start&&(f.currentTime=this.timelinePos=d.start),this.advanceAfterAssetEnded(A,e,i||0);return}if(c||(c=this.getAssetPlayer(h.identifier)),c===null||c.destroyed){const d=A.assetList.length;this.warn(`asset ${i+1}/${d} player destroyed ${A}`),c=this.createAssetPlayer(A,h,i)}if(!this.eventItemsMatch(o,this.bufferingItem)&&A.appendInPlace&&this.isAssetBuffered(h))return;this.startAssetPlayer(c,i,t,e,a),this.shouldPlay&&Xf(c.media)}else o!==null?(this.resumePrimary(o,e,n),this.shouldPlay&&Xf(this.hls.media)):s&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(this.schedule.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e,t;return(e=this.mediaSelection)==null||(t=e.main)==null?void 0:t.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${rr(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.timelinePos=o),this.attachPrimary(o,e)}if(!i)return;const s=this.schedule.items;s&&(this.log(`resumed ${rr(e)}`),this.hls.trigger(I.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const n=this.primaryDetails;if(t===0)return this.hls.startPosition;if(n&&(i<n.fragmentStart||i>n.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:Le.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const n=this.primaryMedia;if(!n)return;const s=this.hls;s.media?this.checkBuffer():(this.transferMediaTo(s,n),i&&this.startLoadingPrimaryAt(e,i)),i||(this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs((((i=n.mainForwardBufferInfo)==null?void 0:i.start)||n.media.currentTime)-e)>.5?n.startLoad(e,t):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){this.stopLoad(),this.schedule.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(I.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(I.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1)return;const i=this.hls.levels[t.level],n=Ve(Ve({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Ve(Ve({},this.altSelection),{},{audio:i});return}const s=Ve(Ve({},n),{},{audio:i});this.mediaSelection=s}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Ve(Ve({},this.altSelection),{},{subtitles:i});return}const s=Ve(Ve({},n),{},{subtitles:i});this.mediaSelection=s}onAudioTrackSwitching(e,t){const i=pd(t);this.playerQueue.forEach(n=>n.hls.setAudioOption(t)||n.hls.setAudioOption(i))}onSubtitleTrackSwitch(e,t){const i=pd(t);this.playerQueue.forEach(n=>n.hls.setSubtitleOption(t)||t.id!==-1&&n.hls.setSubtitleOption(i))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const n=this.timelinePos;this.bufferedPos=n,this.checkBuffer()}}onBufferedToEnd(e){const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let n=0;n<t.length;n++){const s=t[n];if(s.cue.post){var i;const o=this.schedule.findEventIndex(s.identifier),a=(i=this.schedule.items)==null?void 0:i[o];this.isInterstitial(a)&&this.eventItemsMatch(a,this.bufferingItem)&&this.bufferedToItem(a,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}updateItem(e,t){const i=this.schedule.items;if(e&&i){const n=this.findItemIndex(e,t);return i[n]||null}return null}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findItemIndex(e,t){return e?this.schedule.findItemIndex(e,t):-1}updateSchedule(){const e=this.mediaSelection;e&&this.schedule.updateSchedule(e,[])}checkBuffer(e){const t=this.schedule.items;if(!t)return;const i=Le.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,t,e)}updateBufferedPos(e,t,i){const n=this.schedule,s=this.bufferingItem;if(this.bufferedPos>e)return;if(t.length===1&&this.itemsMatch(t[0],s)){this.bufferedPos=e;return}const o=this.playingItem,a=this.findItemIndex(o);let l=n.findItemIndexAtTime(e);if(this.bufferedPos<e){var A,u;const c=this.findItemIndex(s),h=Math.min(c+1,t.length-1),d=t[h];if((l===-1&&s&&e>=s.end||(A=d.event)!=null&&A.appendInPlace&&e+.01>=d.start)&&(l=h),h-a>1&&(s==null||(u=s.event)==null?void 0:u.appendInPlace)===!1)return;if(this.bufferedPos=e,l>c&&l>a)this.bufferedToItem(d);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else i&&o&&!this.itemsMatch(o,s)&&(l===a?this.bufferedToItem(o):l===a+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(n=>{const s=this.getAssetPlayer(n.identifier);return!(s!=null&&s.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(this.itemsMatch(e,t))this.bufferingItem!==e&&(this.bufferingItem=e);else{const{items:n,events:s}=i;if(!n||!s)return t;const o=this.isInterstitial(e),a=this.getBufferingPlayer();if(this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos)),!this.playbackDisabled){const l=a?a.remaining:t?t.end-this.timelinePos:0;this.log(`buffered to boundary ${rr(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),o?e.event.assetList.forEach(A=>{const u=this.getAssetPlayer(A.identifier);u&&u.resumeBuffering()}):(this.hls.resumeBuffering(),this.playerQueue.forEach(A=>A.pauseBuffering()))}this.hls.trigger(I.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:s.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;const n=this.detachedData;n?n.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,n=i.assetList.length===0&&!i.assetListLoader,s=i.cue.once;if(n||!s){const o=this.preloadAssets(i,t);if(o!=null&&o.interstitial.appendInPlace){const a=i.assetList[t],l=this.primaryMedia;a&&l&&this.bufferAssetPlayer(o,l)}}}preloadAssets(e,t){const i=e.assetUrl,n=e.assetList.length,s=n===0&&!e.assetListLoader,o=e.cue.once;if(s){const l=e.timelineStart;if(e.appendInPlace){var a;const h=this.playingItem;!this.isInterstitial(h)&&(h==null||(a=h.nextEvent)==null?void 0:a.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let A,u=0;if(!this.playingItem&&this.primaryLive&&(u=this.hls.startPosition,u===-1&&(u=this.hls.liveSyncPosition||0)),u&&!(e.cue.pre||e.cue.post)){const h=u-l;h>0&&(A=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:n} ${e}${A?` live-start: ${u} start-offset: ${A}`:""}`),i)return this.createAsset(e,0,0,l,e.duration,i);const c=this.assetListLoader.loadAssetList(e,A);c&&(e.assetListLoader=c)}else if(!o&&n){for(let l=t;l<n;l++){const A=e.assetList[l],u=this.getAssetPlayerQueueIndex(A.identifier);(u===-1||this.playerQueue[u].destroyed)&&!A.error&&this.createAssetPlayer(e,A,l)}return this.getAssetPlayer(e.assetList[t].identifier)}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(n=>{this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,n,s,o){const a={parentIdentifier:e.identifier,identifier:ab(e,o,t),duration:s,startOffset:i,timelineStart:n,uri:o};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,i){this.log(`create HLSAssetPlayer for ${pA(t)}`);const n=this.hls,s=n.userConfig;let o=s.videoPreference;const a=n.loadLevelObj||n.levels[n.currentLevel];(o||a)&&(o=qe({},o),a.videoCodec&&(o.videoCodec=a.videoCodec),a.videoRange&&(o.allowedVideoRanges=[a.videoRange]));const l=n.audioTracks[n.audioTrack],A=n.subtitleTracks[n.subtitleTrack];let u=0;if(this.primaryLive||e.appendInPlace){const C=this.timelinePos-t.timelineStart;if(C>1){const y=t.duration;y&&C<y&&(u=C)}}const c=t.identifier,h=Ve(Ve({},s),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:l||s.audioPreference,subtitlePreference:A||s.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(h.timelineOffset=t.timelineStart));const d=h.cmcd;d!=null&&d.sessionId&&d.contentId&&(h.cmcd=qe({},d,{contentId:zn(t.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${e} and asset ${c}`);const f=new cb(this.HlsPlayerClass,h,e,t);this.playerQueue.push(f),e.assetList[i]=t;const g=C=>{if(C.live){const w=new Error(`Interstitials MUST be VOD assets ${e}`),D={fatal:!0,type:Ie.OTHER_ERROR,details:V.INTERSTITIAL_ASSET_ITEM_ERROR,error:w};this.handleAssetItemError(D,e,this.schedule.findEventIndex(e.identifier),i,w.message);return}const y=C.edge-C.fragmentStart,x=t.duration;(x===null||y>x)&&(this.log(`Interstitial asset "${c}" duration change ${x} > ${y}`),t.duration=y,this.updateSchedule())};f.on(I.LEVEL_UPDATED,(C,{details:y})=>g(y)),f.on(I.LEVEL_PTS_UPDATED,(C,{details:y})=>g(y));const p=(C,y)=>{const x=this.getAssetPlayer(c);if(x&&y.tracks){x.off(I.BUFFER_CODECS,p),x.tracks=y.tracks;const w=this.primaryMedia;this.bufferingAsset===x.assetItem&&w&&!x.media&&this.bufferAssetPlayer(x,w)}};f.on(I.BUFFER_CODECS,p);const v=()=>{var C;const y=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${y}`),!y)return;const x=this.schedule.findEventIndex(e.identifier),w=e.findAssetIndex(t),D=w+1,F=(C=this.schedule.items)==null?void 0:C[x];if(this.isInterstitial(F))if(w!==-1&&!e.isAssetPastPlayoutLimit(D)&&!e.assetList[D].error)this.bufferedToItem(F,D);else{var O;const M=(O=this.schedule.items)==null?void 0:O[x+1];M&&this.bufferedToItem(M)}};f.on(I.BUFFERED_TO_END,v);const B=C=>()=>{if(!this.getAssetPlayer(c))return;this.shouldPlay=!0;const x=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,x,C)};return f.once(I.MEDIA_ENDED,B(i)),f.once(I.PLAYOUT_LIMIT_REACHED,B(1/0)),f.on(I.ERROR,(C,y)=>{const x=this.getAssetPlayer(c);if(y.details===V.BUFFER_STALLED_ERROR){if(x!=null&&x.media){const w=x.currentTime,D=x.duration-w;w&&e.appendInPlace&&D/x.media.playbackRate<.5?(this.log(`Advancing buffer past end of asset ${c} ${e} at ${x.media.currentTime}`),v()):(this.warn(`Stalled at ${w} of ${w+D} in asset ${c} ${e}`),this.onTimeupdate(),this.checkBuffer(!0))}return}this.handleAssetItemError(y,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${y.error} ${e}`)}),f.on(I.DESTROYING,()=>{if(!this.getAssetPlayer(c))return;const y=new Error(`Asset player destroyed unexpectedly ${c}`),x={fatal:!0,type:Ie.OTHER_ERROR,details:V.INTERSTITIAL_ASSET_ITEM_ERROR,error:y};this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),i,y.message)}),this.hls.trigger(I.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:f}),f}clearInterstitial(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)}),e.reset()}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(i!==-1){this.log(`clearAssetPlayer "${e}" toSegment: ${t&&rr(t)}`);const n=this.playerQueue[i];this.transferMediaFromPlayer(n,t),this.playerQueue.splice(i,1),n.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,n,s){const{interstitial:o,assetItem:a,assetId:l}=e,A=o.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(!u||u.identifier!==l)&&(u&&(this.clearAssetPlayer(u.identifier,i[n]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${A} ${e}`),this.hls.trigger(I.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:o,schedule:i.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,s)}bufferAssetPlayer(e,t){var i,n;const{interstitial:s,assetItem:o,assetId:a}=e,l=this.schedule.findEventIndex(s.identifier),A=(i=this.schedule.items)==null?void 0:i[l];if(!A)return;this.setBufferingItem(A),this.bufferingAsset=o;const u=this.getBufferingPlayer();if(u===e)return;const c=s.appendInPlace;if(c&&(u==null?void 0:u.interstitial.appendInPlace)===!1)return;const h=(u==null?void 0:u.tracks)||((n=this.detachedData)==null?void 0:n.tracks)||this.requiredTracks;if(c&&o!==this.playingAsset){if(!e.tracks)return;if(h&&!Yh(h,e.tracks)){const d=new Error(`Asset "${a}" SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),f={fatal:!0,type:Ie.OTHER_ERROR,details:V.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},g=s.findAssetIndex(o);this.handleAssetItemError(f,s,l,g,d.message);return}}this.transferMediaTo(e,t)}handleAssetItemError(e,t,i,n,s){if(e.details===V.BUFFER_STALLED_ERROR)return;const o=t.assetList[n]||null;let a=null;if(o){const c=this.getAssetPlayerQueueIndex(o.identifier);a=this.playerQueue[c]||null}const l=this.schedule.items,A=qe({},e,{fatal:!1,errorAction:$n(!0),asset:o,assetListIndex:n,event:t,schedule:l,scheduleIndex:i,player:a});if(this.warn(`Asset item error: ${e.error}`),this.hls.trigger(I.INTERSTITIAL_ASSET_ERROR,A),!e.fatal)return;const u=new Error(s);o&&(this.playingAsset!==o&&this.clearAssetPlayer(o.identifier,null),o.error=u),t.assetList.some(c=>!c.error)?t.appendInPlace&&(t.error=u):t.error=u,this.primaryFallback(t)}primaryFallback(e){const t=e.timelineStart,i=this.effectivePlayingItem;if(this.updateSchedule(),i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${i?rr(i):"<none>"} error: ${e.error}`),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t));let n=this.timelinePos;n===-1&&(n=this.hls.startPosition);const s=this.updateItem(i,n);if(this.itemsMatch(i,s))this.clearInterstitial(e,null);else{const o=this.schedule.findItemIndexAtTime(n);this.setSchedulePosition(o)}}else this.checkStart()}onAssetListLoaded(e,t){var i;const n=t.event,s=n.identifier,o=t.assetListResponse.ASSETS;if(!this.schedule.hasEvent(s))return;const a=n.timelineStart,l=n.duration;let A=0;o.forEach((f,g)=>{const p=parseFloat(f.DURATION);this.createAsset(n,g,A,a+A,p,f.URI),A+=p}),n.duration=A,this.log(`Loaded asset-list with duration: ${A} (was: ${l}) ${n}`);const u=this.waitingItem,c=(u==null?void 0:u.event.identifier)===s;this.updateSchedule();const h=(i=this.bufferingItem)==null?void 0:i.event;if(c){var d;const f=this.schedule.findEventIndex(s),g=(d=this.schedule.items)==null?void 0:d[f];if(g){if(!this.playingItem&&this.timelinePos>g.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==f){n.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${n}`),this.primaryFallback(n);return}this.setBufferingItem(g)}this.setSchedulePosition(f)}else if((h==null?void 0:h.identifier)===s&&h.appendInPlace){const f=n.assetList[0],g=this.getAssetPlayer(f.identifier),p=this.primaryMedia;f&&g&&p&&this.bufferAssetPlayer(g,p)}}onError(e,t){switch(t.details){case V.ASSET_LIST_PARSING_ERROR:case V.ASSET_LIST_LOAD_ERROR:case V.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&this.primaryFallback(i);break}case V.BUFFER_STALLED_ERROR:{this.onTimeupdate(),this.checkBuffer(!0);break}}}}const zf=500;class fb extends Kl{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",Ee.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(I.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(I.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Z.IDLE,this.setInterval(zf),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:n}=t;if(Ct(i)&&(this.fragPrevious=i),this.state=Z.IDLE,!n)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let o;const a=i.start;for(let A=0;A<s.length;A++)if(a>=s[A].start&&a<=s[A].end){o=s[A];break}const l=i.start+i.duration;o?o.end=l:(o={start:a,end:l},s.push(o)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:n}=t;if(i===0&&n!==Number.POSITIVE_INFINITY){const s=n-1;if(s<=0)return;t.endOffsetSubtitles=Math.max(0,s),this.tracksBuffered.forEach(o=>{for(let a=0;a<o.length;){if(o[a].end<=s){o.shift();continue}else if(o[a].start<s)o[a].start=s;else break;a++}}),this.fragmentTracker.removeFragmentsInRange(i,s,Ee.SUBTITLE)}}onError(e,t){const i=t.frag;(i==null?void 0:i.type)===Ee.SUBTITLE&&(t.details===V.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Z.STOPPED&&(this.state=Z.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&kf(this.levels,t)){this.levels=t.map(i=>new Gn(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const n=new Gn(i);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Ee.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}const n=this.levels[this.currentTrackId];n!=null&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.state!==Z.STOPPED&&this.setInterval(zf)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:n,levels:s}=this,{details:o,id:a}=t;if(!s){this.warn(`Subtitle tracks were reset while loading level ${a}`);return}const l=s[a];if(a>=s.length||!l)return;this.log(`Subtitle track ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""},duration:${o.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let A=0;if(o.live||(i=l.details)!=null&&i.live){const c=this.mainDetails;if(o.deltaUpdateFailed||!c)return;const h=c.fragments[0];if(!l.details)o.hasProgramDateTime&&c.hasProgramDateTime?(xo(o,c),A=o.fragmentStart):h&&(A=h.start,Vl(o,A));else{var u;A=this.alignPlaylists(o,l.details,(u=this.levelLastLoaded)==null?void 0:u.details),A===0&&h&&(A=h.start,Vl(o,A))}}l.details=o,this.levelLastLoaded=l,a===n&&(this.hls.trigger(I.SUBTITLE_TRACK_UPDATED,{details:o,id:a,groupId:t.groupId}),this.tick(),o.live&&!this.fragCurrent&&this.media&&this.state===Z.IDLE&&(Br(null,o.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,n=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&n!=null&&n.key&&n.iv&&Hr(n.method)){const o=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,Fl(n.method)).catch(a=>{throw s.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t}),a}).then(a=>{const l=performance.now();s.trigger(I.FRAG_DECRYPTED,{frag:t,payload:a,stats:{tstart:o,tdecrypt:l}})}).catch(a=>{this.warn(`${a.name}: ${a.message}`),this.state=Z.IDLE})}}doTick(){if(!this.media){this.state=Z.IDLE;return}if(this.state===Z.IDLE){const{currentTrackId:e,levels:t}=this,i=t==null?void 0:t[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;const{config:n}=this,s=this.getLoadPosition(),o=Le.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,n.maxBufferHole),{end:a,len:l}=o,A=i.details,u=this.hls.maxBufferLength+A.levelTargetDuration;if(l>u)return;const c=A.fragments,h=c.length,d=A.edge;let f=null;const g=this.fragPrevious;if(a<d){const B=n.maxFragLookUpTolerance,C=a>d-B?0:B;f=Br(g,c,Math.max(c[0].start,a),C),!f&&g&&g.start<c[0].start&&(f=c[0])}else f=c[h-1];if(f=this.filterReplacedPrimary(f,i.details),!f)return;const p=f.sn-A.startSN,v=c[p-1];if(v&&v.cc===f.cc&&this.fragmentTracker.getState(v)===vt.NOT_LOADED&&(f=v),this.fragmentTracker.getState(f)===vt.NOT_LOADED){const B=this.mapToInitFragWhenRequired(f);B&&this.loadFragment(B,i,a)}}}loadFragment(e,t,i){Ct(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new gb(this.tracksBuffered[this.currentTrackId]||[])}}class gb{constructor(e){this.buffered=void 0;const t=(i,n,s)=>{if(n=n>>>0,n>s-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${s})`);return e[n][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}const pb={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},Zf=r=>String.fromCharCode(pb[r]||r),si=15,ki=100,mb={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Eb={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Ib={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},vb={25:2,26:4,29:6,30:8,31:10,27:13,28:15},yb=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Cb{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;Ue.log(`${this.time} [${e}] ${i}`)}}}const Tr=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class eg{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!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 n=t[i];e.hasOwnProperty(n)&&(this[n]=e[n])}}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 Bb{constructor(){this.uchar=" ",this.penState=new eg}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 Tb{constructor(e){this.chars=[],this.pos=0,this.currPenState=new eg,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<ki;t++)this.chars.push(new Bb);this.logger=e}equals(e){for(let t=0;t<ki;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<ki;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<ki;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>ki&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ki)}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=Zf(e);if(this.pos>=ki){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<ki;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<ki;i++){const n=this.chars[i].uchar;n!==" "&&(t=!1),e.push(n)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class mA{constructor(e){this.rows=[],this.currRow=si-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<si;t++)this.rows.push(new Tb(e));this.logger=e}reset(){for(let e=0;e<si;e++)this.rows[e].clear();this.currRow=si-1}equals(e){let t=!0;for(let i=0;i<si;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<si;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<si;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 = "+rt(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<si;a++)this.rows[a].clear();const s=this.currRow+1-this.nrRollUpRows,o=this.lastOutputScreen;if(o){const a=o.rows[s].cueStartTime,l=this.logger.time;if(a!==null&&l!==null&&a<l)for(let A=0;A<this.nrRollUpRows;A++)this.rows[t-this.nrRollUpRows+A+1].copy(o.rows[s+A])}}this.currRow=t;const i=this.rows[this.currRow];if(e.indent!==null){const s=e.indent,o=Math.max(s-1,0);i.setCursor(e.indent),e.color=i.chars[o].penState.foreground}const n={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(n)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+rt(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="",n=-1;for(let s=0;s<si;s++){const o=this.rows[s].getTextString();o&&(n=s+1,e?t.push("Row "+n+": '"+o+"'"):t.push(o.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
2514
2514
  `)),i}getTextAndFormat(){return this.rows}}class tg{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 mA(i),this.nonDisplayedMemory=new mA(i),this.lastOutputScreen=new mA(i),this.currRollUpRow=this.displayedMemory.rows[si-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[si-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,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[i]}this.logger.log(2,"MIDROW: "+rt(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 ig{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Sb(),this.logger=void 0;const n=this.logger=new Cb;this.channels=[null,new tg(e,t,n),new tg(e+1,i,n)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){const n=t[i]&127,s=t[i+1]&127;let o=!1,a=null;if(n===0&&s===0)continue;this.logger.log(3,()=>"["+Tr([t[i],t[i+1]])+"] -> ("+Tr([n,s])+")");const l=this.cmdHistory;if(n>=16&&n<=31){if(bb(n,s,l)){No(null,null,l),this.logger.log(3,()=>"Repeated command ("+Tr([n,s])+") is dropped");continue}No(n,s,this.cmdHistory),o=this.parseCmd(n,s),o||(o=this.parseMidrow(n,s)),o||(o=this.parsePAC(n,s)),o||(o=this.parseBackgroundAttributes(n,s))}else No(null,null,l);if(!o&&(a=this.parseChars(n,s),a)){const u=this.currentChannel;u&&u>0?this.channels[u].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!o&&!a&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Tr([n,s])+" orig: "+Tr([t[i],t[i+1]]))}}parseCmd(e,t){const i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(i||n))return!1;const s=e===20||e===21||e===23?1:2,o=this.channels[s];return e===20||e===21||e===28||e===29?t===32?o.ccRCL():t===33?o.ccBS():t===34?o.ccAOF():t===35?o.ccAON():t===36?o.ccDER():t===37?o.ccRU(2):t===38?o.ccRU(3):t===39?o.ccRU(4):t===40?o.ccFON():t===41?o.ccRDC():t===42?o.ccTR():t===43?o.ccRTD():t===44?o.ccEDM():t===45?o.ccCR():t===46?o.ccENM():t===47&&o.ccEOC():o.ccTO(t-32),this.currentChannel=s,!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 n=this.channels[i];return n?(n.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Tr([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const n=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,s=(e===16||e===24)&&t>=64&&t<=95;if(!(n||s))return!1;const o=e<=23?1:2;t>=64&&t<=95?i=o===1?mb[e]:Ib[e]:i=o===1?Eb[e]:vb[e];const a=this.channels[o];return a?(a.setPAC(this.interpretPAC(i,t)),this.currentChannel=o,!0):!1}interpretPAC(e,t){let i;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,n.underline=(i&1)===1,i<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(n.italics=!0,n.color="white"):n.indent=Math.floor((i-16)/2)*4,n}parseChars(e,t){let i,n=null,s=null;if(e>=25?(i=2,s=e-8):(i=1,s=e),s>=17&&s<=19){let o;s===17?o=t+80:s===18?o=t+112:o=t+144,this.logger.log(2,()=>"Special char '"+Zf(o)+"' in channel "+i),n=[o]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+Tr(n).join(",")),n}parseBackgroundAttributes(e,t){const i=(e===16||e===24)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=45&&t<=47;if(!(i||n))return!1;let s;const o={};e===16||e===24?(s=Math.floor((t-32)/2),o.background=yb[s],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),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}No(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const i=this.channels[t];i&&i.cueSplitAtTime(e)}}}function No(r,e,t){t.a=r,t.b=e}function bb(r,e,t){return t.a===r&&t.b===e}function Sb(){return{a:null,b:null}}var EA=function(){if(Bo!=null&&Bo.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 A=l.toLowerCase();return~a.indexOf(A)?A:!1}function i(a){return t(r,a)}function n(a){return t(e,a)}function s(a,...l){let A=1;for(;A<arguments.length;A++){const u=arguments[A];for(const c in u)a[c]=u[c]}return a}function o(a,l,A){const u=this,c={enumerable:!0};u.hasBeenReset=!1;let h="",d=!1,f=a,g=l,p=A,v=null,B="",C=!0,y="auto",x="start",w=50,D="middle",F=50,O="middle";Object.defineProperty(u,"id",s({},c,{get:function(){return h},set:function(M){h=""+M}})),Object.defineProperty(u,"pauseOnExit",s({},c,{get:function(){return d},set:function(M){d=!!M}})),Object.defineProperty(u,"startTime",s({},c,{get:function(){return f},set:function(M){if(typeof M!="number")throw new TypeError("Start time must be set to a number.");f=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",s({},c,{get:function(){return g},set:function(M){if(typeof M!="number")throw new TypeError("End time must be set to a number.");g=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",s({},c,{get:function(){return p},set:function(M){p=""+M,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",s({},c,{get:function(){return v},set:function(M){v=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",s({},c,{get:function(){return B},set:function(M){const j=i(M);if(j===!1)throw new SyntaxError("An invalid or illegal string was specified.");B=j,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",s({},c,{get:function(){return C},set:function(M){C=!!M,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",s({},c,{get:function(){return y},set:function(M){if(typeof M!="number"&&M!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");y=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",s({},c,{get:function(){return x},set:function(M){const j=n(M);if(!j)throw new SyntaxError("An invalid or illegal string was specified.");x=j,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",s({},c,{get:function(){return w},set:function(M){if(M<0||M>100)throw new Error("Position must be between 0 and 100.");w=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",s({},c,{get:function(){return D},set:function(M){const j=n(M);if(!j)throw new SyntaxError("An invalid or illegal string was specified.");D=j,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",s({},c,{get:function(){return F},set:function(M){if(M<0||M>100)throw new Error("Size must be between 0 and 100.");F=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",s({},c,{get:function(){return O},set:function(M){const j=n(M);if(!j)throw new SyntaxError("An invalid or illegal string was specified.");O=j,this.hasBeenReset=!0}})),u.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o}();class xb{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function rg(r){function e(i,n,s,o){return(i|0)*3600+(n|0)*60+(s|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 Qb{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 n=0;n<i.length;++n)if(t===i[n]){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 ng(r,e,t,i){const n=i?r.split(i):[r];for(const s in n){if(typeof n[s]!="string")continue;const o=n[s].split(t);if(o.length!==2)continue;const a=o[0],l=o[1];e(a,l)}}const IA=new EA(0,0,""),Oo=IA.align==="middle"?"middle":"center";function _b(r,e,t){const i=r;function n(){const a=rg(r);if(a===null)throw new Error("Malformed timestamp: "+i);return r=r.replace(/^[^\sa-zA-Z-]+/,""),a}function s(a,l){const A=new Qb;ng(a,function(h,d){let f;switch(h){case"region":for(let g=t.length-1;g>=0;g--)if(t[g].id===d){A.set(h,t[g].region);break}break;case"vertical":A.alt(h,d,["rl","lr"]);break;case"line":f=d.split(","),A.integer(h,f[0]),A.percent(h,f[0])&&A.set("snapToLines",!1),A.alt(h,f[0],["auto"]),f.length===2&&A.alt("lineAlign",f[1],["start",Oo,"end"]);break;case"position":f=d.split(","),A.percent(h,f[0]),f.length===2&&A.alt("positionAlign",f[1],["start",Oo,"end","line-left","line-right","auto"]);break;case"size":A.percent(h,d);break;case"align":A.alt(h,d,["start",Oo,"end","left","right"]);break}},/:/,/\s/),l.region=A.get("region",null),l.vertical=A.get("vertical","");let u=A.get("line","auto");u==="auto"&&IA.line===-1&&(u=-1),l.line=u,l.lineAlign=A.get("lineAlign","start"),l.snapToLines=A.get("snapToLines",!0),l.size=A.get("size",100),l.align=A.get("align",Oo);let c=A.get("position","auto");c==="auto"&&IA.position===50&&(c=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=c}function o(){r=r.replace(/^\s+/,"")}if(o(),e.startTime=n(),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=n(),o(),s(r,e)}function sg(r){return r.replace(/<br(?: \/)?>/gi,`
@@ -3907,7 +3907,7 @@ Schedule: ${l.map(d=>rr(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3907
3907
  top: 0;
3908
3908
  left: 0;
3909
3909
  }
3910
- `],ct([te({type:Boolean})],nt.prototype,"debug",2),ct([te({type:Object})],nt.prototype,"config",2),ct([te({type:String,attribute:"language"})],nt.prototype,"propLanguage",2),ct([te({type:Number,attribute:"aspectratio"})],nt.prototype,"propAspectRatio",2),ct([te({type:String})],nt.prototype,"preload",2),ct([te({type:Boolean})],nt.prototype,"autoplay",2),ct([te({type:Boolean})],nt.prototype,"loading",2),ct([te({type:Boolean})],nt.prototype,"disabled",2),ct([te({type:Array})],nt.prototype,"controls",2),ct([te({attribute:!1})],nt.prototype,"dataResolver",2),ct([te({attribute:!1})],nt.prototype,"languageResolver",2),ct([ht()],nt.prototype,"_pageHidden",2),ct([ht()],nt.prototype,"_aspectRatio",2),ct([ht()],nt.prototype,"_processing",2),ct([ht()],nt.prototype,"_waiting",2),ct([ht()],nt.prototype,"_errors",2),ct([ht()],nt.prototype,"_seeking",2),ct([ht()],nt.prototype,"_language",2),ct([ht()],nt.prototype,"_languages",2),ct([ht()],nt.prototype,"_captions",2),ct([ht()],nt.prototype,"_fullscreen",2),nt=ct([Mt("vmp-media-player")],nt);var iQ=Object.defineProperty,rQ=Object.getOwnPropertyDescriptor,Rt=(r,e,t,i)=>{for(var n=i>1?void 0:i?rQ(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&iQ(e,t,n),n};Pe.PlayerEmbed=class extends Si{constructor(){super(...arguments),this.env="prod",this.apiKey="",this.disableTracking=!1,this.trackingSource="embedded_player",this.preload="auto",this.autoplay=!1,this.aspectRatio=0,this.eventController=new Tp(this,["durationchange","ended","error","loadeddata","pause","stalled","play","playing","ratechange","scenechange","scenesupdate","seeking","seeked","timeupdate","volumechange","processing","waiting","video:loadeddata","video:seeking","video:seeked","video:play","video:playing","video:pause","video:stalled","video:timeupdate","video:ended","video:error"]),this._fetcherController=new qp(this),this._trackingController=new Cy(this),this._mediaPlayerRef=bt()}get fetching(){return this._fetcherController.fetching}get waiting(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.waiting}get initialised(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.initialised}get seeking(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.seeking}get paused(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.paused}get captions(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.captions}get fullscreen(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.fullscreen}get duration(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.duration}set currentTime(e){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.currentTime=e)}get currentTime(){var e;return((e=this._mediaPlayerRef.value)==null?void 0:e.currentTime)??0}set playbackRate(e){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.playbackRate=e)}get playbackRate(){var e;return((e=this._mediaPlayerRef.value)==null?void 0:e.playbackRate)??1}set volume(e){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.volume=e)}get volume(){var e;return((e=this._mediaPlayerRef.value)==null?void 0:e.volume)??1}set muted(e){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.muted=e)}get muted(){var e;return((e=this._mediaPlayerRef.value)==null?void 0:e.muted)??!1}get mediaState(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.mediaState}get mediaPlayer(){return this._mediaPlayerRef.value}play(){var e;(e=this._mediaPlayerRef.value)==null||e.play()}pause(){var e;(e=this._mediaPlayerRef.value)==null||e.pause()}reset(e=0,t=!1){var i;(i=this._mediaPlayerRef.value)==null||i.reset(e,t)}_renderStyles(){return this.aspectRatio?typeof this.aspectRatio=="number"?Te`
3910
+ `],ct([te({type:Boolean})],nt.prototype,"debug",2),ct([te({type:Object})],nt.prototype,"config",2),ct([te({type:String,attribute:"language"})],nt.prototype,"propLanguage",2),ct([te({type:Number,attribute:"aspectratio"})],nt.prototype,"propAspectRatio",2),ct([te({type:String})],nt.prototype,"preload",2),ct([te({type:Boolean})],nt.prototype,"autoplay",2),ct([te({type:Boolean})],nt.prototype,"loading",2),ct([te({type:Boolean})],nt.prototype,"disabled",2),ct([te({type:Array})],nt.prototype,"controls",2),ct([te({attribute:!1})],nt.prototype,"dataResolver",2),ct([te({attribute:!1})],nt.prototype,"languageResolver",2),ct([ht()],nt.prototype,"_pageHidden",2),ct([ht()],nt.prototype,"_aspectRatio",2),ct([ht()],nt.prototype,"_processing",2),ct([ht()],nt.prototype,"_waiting",2),ct([ht()],nt.prototype,"_errors",2),ct([ht()],nt.prototype,"_seeking",2),ct([ht()],nt.prototype,"_language",2),ct([ht()],nt.prototype,"_languages",2),ct([ht()],nt.prototype,"_captions",2),ct([ht()],nt.prototype,"_fullscreen",2),nt=ct([Mt("vmp-media-player")],nt);var iQ=Object.defineProperty,rQ=Object.getOwnPropertyDescriptor,wt=(r,e,t,i)=>{for(var n=i>1?void 0:i?rQ(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&iQ(e,t,n),n};Pe.PlayerEmbed=class extends Si{constructor(){super(...arguments),this.env="prod",this.apiKey="",this.disableTracking=!1,this.trackingSource="embedded_player",this.preload="auto",this.autoplay=!1,this.aspectRatio=0,this.eventController=new Tp(this,["durationchange","ended","error","loadeddata","pause","stalled","play","playing","ratechange","scenechange","scenesupdate","seeking","seeked","timeupdate","volumechange","processing","waiting","video:loadeddata","video:seeking","video:seeked","video:play","video:playing","video:pause","video:stalled","video:timeupdate","video:ended","video:error"]),this._fetcherController=new qp(this),this._trackingController=new Cy(this),this._mediaPlayerRef=bt()}get fetching(){return this._fetcherController.fetching}get waiting(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.waiting}get initialised(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.initialised}get seeking(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.seeking}get paused(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.paused}get captions(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.captions}get fullscreen(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.fullscreen}get duration(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.duration}set currentTime(e){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.currentTime=e)}get currentTime(){var e;return((e=this._mediaPlayerRef.value)==null?void 0:e.currentTime)??0}set playbackRate(e){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.playbackRate=e)}get playbackRate(){var e;return((e=this._mediaPlayerRef.value)==null?void 0:e.playbackRate)??1}set volume(e){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.volume=e)}get volume(){var e;return((e=this._mediaPlayerRef.value)==null?void 0:e.volume)??1}set muted(e){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.muted=e)}get muted(){var e;return((e=this._mediaPlayerRef.value)==null?void 0:e.muted)??!1}get mediaState(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.mediaState}get mediaPlayer(){return this._mediaPlayerRef.value}play(){var e;(e=this._mediaPlayerRef.value)==null||e.play()}pause(){var e;(e=this._mediaPlayerRef.value)==null||e.pause()}reset(e=0,t=!1){var i;(i=this._mediaPlayerRef.value)==null||i.reset(e,t)}_renderStyles(){return this.aspectRatio?typeof this.aspectRatio=="number"?Te`
3911
3911
  <style>
3912
3912
  :host {
3913
3913
  aspect-ratio: ${this.aspectRatio};
@@ -3936,7 +3936,7 @@ Schedule: ${l.map(d=>rr(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3936
3936
  :host {
3937
3937
  display: flex;
3938
3938
  }
3939
- `],Rt([te({type:Object})],Pe.PlayerEmbed.prototype,"data",2),Rt([te({type:String})],Pe.PlayerEmbed.prototype,"vouchId",2),Rt([te({type:String})],Pe.PlayerEmbed.prototype,"templateId",2),Rt([te({type:Array})],Pe.PlayerEmbed.prototype,"questions",2),Rt([te({type:String})],Pe.PlayerEmbed.prototype,"env",2),Rt([te({type:String})],Pe.PlayerEmbed.prototype,"apiKey",2),Rt([te({type:Boolean})],Pe.PlayerEmbed.prototype,"disableTracking",2),Rt([te({type:String})],Pe.PlayerEmbed.prototype,"trackingSource",2),Rt([te({type:Array})],Pe.PlayerEmbed.prototype,"controls",2),Rt([te({type:String})],Pe.PlayerEmbed.prototype,"preload",2),Rt([te({type:Boolean})],Pe.PlayerEmbed.prototype,"autoplay",2),Rt([te({type:Number})],Pe.PlayerEmbed.prototype,"aspectRatio",2),Rt([te({type:String})],Pe.PlayerEmbed.prototype,"language",2),Rt([ht()],Pe.PlayerEmbed.prototype,"vouch",2),Rt([ht()],Pe.PlayerEmbed.prototype,"template",2),Pe.PlayerEmbed=Rt([Ts("vouch-embed-player")],Pe.PlayerEmbed);function ea(r,e,t,i=20,n=0){let s=[];if(n>=i)return s;const o=l=>{const A=l.assignedNodes().filter(u=>u.nodeType===1);return A.length>0?ea(A[0].parentElement,e,t,i,n+1):[]},a=Array.from(r.children||[]);for(const l of a)e(l)||(t(l)&&s.push(l),l.shadowRoot!=null?s.push(...ea(l.shadowRoot,e,t,i,n+1)):l.tagName==="SLOT"?s.push(...o(l)):s.push(...ea(l,e,t,i,n+1)));return s}function p0(r){return r.hasAttribute("hidden")||r.hasAttribute("aria-hidden")&&r.getAttribute("aria-hidden")!=="false"||r.style.display==="none"||r.style.opacity==="0"||r.style.visibility==="hidden"||r.style.visibility==="collapse"}function nQ(r){return r.hasAttribute("disabled")||r.hasAttribute("aria-disabled")&&r.getAttribute("aria-disabled")!=="false"}function sQ(r){return r.getAttribute("tabindex")==="-1"||p0(r)||nQ(r)?!1:r.hasAttribute("tabindex")||(r instanceof HTMLAnchorElement||r instanceof HTMLAreaElement)&&r.hasAttribute("href")||r instanceof HTMLButtonElement||r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement||r instanceof HTMLIFrameElement}const zA=new Map;function oQ(r,e,t){const i=zA.get(t);i!=null&&window.clearTimeout(i),zA.set(t,window.setTimeout(()=>{r(),zA.delete(t)},e))}const m0=document.createElement("template");m0.innerHTML=`
3939
+ `],wt([te({type:Object})],Pe.PlayerEmbed.prototype,"data",2),wt([te({type:String})],Pe.PlayerEmbed.prototype,"vouchId",2),wt([te({type:String})],Pe.PlayerEmbed.prototype,"templateId",2),wt([te({type:Array})],Pe.PlayerEmbed.prototype,"questions",2),wt([te({type:String})],Pe.PlayerEmbed.prototype,"env",2),wt([te({type:String})],Pe.PlayerEmbed.prototype,"apiKey",2),wt([te({type:Boolean})],Pe.PlayerEmbed.prototype,"disableTracking",2),wt([te({type:String})],Pe.PlayerEmbed.prototype,"trackingSource",2),wt([te({type:Array})],Pe.PlayerEmbed.prototype,"controls",2),wt([te({type:String})],Pe.PlayerEmbed.prototype,"preload",2),wt([te({type:Boolean})],Pe.PlayerEmbed.prototype,"autoplay",2),wt([te({type:Number})],Pe.PlayerEmbed.prototype,"aspectRatio",2),wt([te({type:String})],Pe.PlayerEmbed.prototype,"language",2),wt([te({type:String})],Pe.PlayerEmbed.prototype,"senderId",2),wt([ht()],Pe.PlayerEmbed.prototype,"vouch",2),wt([ht()],Pe.PlayerEmbed.prototype,"template",2),Pe.PlayerEmbed=wt([Ts("vouch-embed-player")],Pe.PlayerEmbed);function ea(r,e,t,i=20,n=0){let s=[];if(n>=i)return s;const o=l=>{const A=l.assignedNodes().filter(u=>u.nodeType===1);return A.length>0?ea(A[0].parentElement,e,t,i,n+1):[]},a=Array.from(r.children||[]);for(const l of a)e(l)||(t(l)&&s.push(l),l.shadowRoot!=null?s.push(...ea(l.shadowRoot,e,t,i,n+1)):l.tagName==="SLOT"?s.push(...o(l)):s.push(...ea(l,e,t,i,n+1)));return s}function p0(r){return r.hasAttribute("hidden")||r.hasAttribute("aria-hidden")&&r.getAttribute("aria-hidden")!=="false"||r.style.display==="none"||r.style.opacity==="0"||r.style.visibility==="hidden"||r.style.visibility==="collapse"}function nQ(r){return r.hasAttribute("disabled")||r.hasAttribute("aria-disabled")&&r.getAttribute("aria-disabled")!=="false"}function sQ(r){return r.getAttribute("tabindex")==="-1"||p0(r)||nQ(r)?!1:r.hasAttribute("tabindex")||(r instanceof HTMLAnchorElement||r instanceof HTMLAreaElement)&&r.hasAttribute("href")||r instanceof HTMLButtonElement||r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement||r instanceof HTMLIFrameElement}const zA=new Map;function oQ(r,e,t){const i=zA.get(t);i!=null&&window.clearTimeout(i),zA.set(t,window.setTimeout(()=>{r(),zA.delete(t)},e))}const m0=document.createElement("template");m0.innerHTML=`
3940
3940
  <div id="start"></div>
3941
3941
  <div id="backup"></div>
3942
3942
  <slot></slot>