@twick/visualizer 0.14.11 → 0.14.13
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.
- package/dist/project.js +32 -32
- package/package.json +8 -8
package/dist/project.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
class
|
|
1
|
+
class oo{constructor(){this.subscribable=new nc(this),this.subscribers=new Set}subscribe(e){return this.subscribers.add(e),()=>this.unsubscribe(e)}unsubscribe(e){this.subscribers.delete(e)}clear(){this.subscribers.clear()}notifySubscribers(e){return[...this.subscribers].map(t=>t(e))}}class nc{constructor(e){this.dispatcher=e}subscribe(e){return this.dispatcher.subscribe(e)}unsubscribe(e){this.dispatcher.unsubscribe(e)}}class Zt extends oo{dispatch(e){this.notifySubscribers(e)}}class Ku extends oo{constructor(){super(...arguments),this.value=!1}raise(){this.value||(this.value=!0,this.notifySubscribers())}reset(){this.value=!1}isRaised(){return this.value}subscribe(e){const t=super.subscribe(e);return this.value&&e(),t}}class wa extends oo{get current(){return this.value}set current(e){this.value=e,this.notifySubscribers(e)}constructor(e){super(),this.value=e,this.subscribable=new Yu(this)}subscribe(e,t=!0){const s=super.subscribe(e);return t&&e(this.value),s}}class Yu extends nc{get current(){return this.dispatcher.current}subscribe(e,t=!0){return this.dispatcher.subscribe(e,t)}}var Tt;(function(r){r.Error="error",r.Warn="warn",r.Info="info",r.Http="http",r.Verbose="verbose",r.Debug="debug",r.Silly="silly"})(Tt||(Tt={}));let Wu=class{constructor(){this.logged=new Zt,this.history=[],this.profilers={}}get onLogged(){return this.logged.subscribable}log(e){this.logged.dispatch(e),this.history.push(e)}error(e){console.error("error from browser process:",typeof e=="string"?e:e.message),this.logLevel(Tt.Error,e),window.browserError&&window.browserError(typeof e=="string"?e:e.message)}warn(e){console.warn("warning from browser process:",typeof e=="string"?e:e.message),this.logLevel(Tt.Warn,e)}info(e){console.info("info from browser process:",typeof e=="string"?e:e.message),this.logLevel(Tt.Info,e)}http(e){console.log("http log from browser process:",typeof e=="string"?e:e.message),this.logLevel(Tt.Http,e)}verbose(e){console.log("verbose log from browser process:",typeof e=="string"?e:e.message),this.logLevel(Tt.Verbose,e)}debug(e){this.logLevel(Tt.Debug,e)}silly(e){console.log("silly log from browser process:",typeof e=="string"?e:e.message),this.logLevel(Tt.Silly,e)}logLevel(e,t){const s=typeof t=="string"?{message:t}:t;s.level=e,this.log(s)}profile(e,t){const s=performance.now();if(this.profilers[e]){const n=this.profilers[e];delete this.profilers[e];const a=t??{message:e};a.level??(a.level=Tt.Debug),a.durationMs=s-n,this.log(a);return}this.profilers[e]=s}};function se(r,e,t){return r+(e-r)*t}function ju(r,e,t,s,n){return t+(n-r)*(s-t)/(e-r)}function me(r,e,t){return t<r?r:t>e?e:t}const lr=[];function zn(){const r=lr.at(-1);if(!r)throw new Error("The scene is not available in the current context.");return r}function qu(r){lr.push(r)}function Xu(r){if(lr.pop()!==r)throw new Error("startScene/endScene were called out of order.")}function Ue(){var r;return((r=lr.at(-1))==null?void 0:r.logger)??console}class lo extends Error{constructor(e,t){typeof e=="string"?(super(e),this.remarks=t):(super(e.message),this.remarks=e.remarks,this.object=e.object,this.durationMs=e.durationMs,this.inspect=e.inspect)}}const ho=[];function Os(){const r=ho.at(-1);if(!r)throw new lo("The thread is not available in the current context.","`useThread()` can only be called from within generator functions.\n It's not available during rendering.");return r}function Qu(r){ho.push(r)}function Zu(r){if(ho.pop()!==r)throw new Error("startThread/endThread was called out of order.")}function Ui(r){return r[0].toUpperCase()+r.slice(1)}function Oe(){let r;return t=>{if(t!==void 0)r=t;else return r}}function rc(r){return{message:r.message,stack:r.stack,remarks:r.remarks}}const Ju=`
|
|
2
2
|
This feature requires enabling the \`experimentalFeatures\` flag in your project
|
|
3
3
|
configuration:
|
|
4
4
|
|
|
@@ -11,11 +11,11 @@ export default makeProject({
|
|
|
11
11
|
|
|
12
12
|
[Learn more](https://motioncanvas.io/docs/experimental) about experimental
|
|
13
13
|
features.
|
|
14
|
-
`;function
|
|
15
|
-
Try using the attached stack trace to locate said loop.`);be.collectionSet.add(this),be.collectionStack.push(this)}finishCollecting(){if(be.collectionSet.delete(this),be.collectionStack.pop()!==this)throw new Error("collectStart/collectEnd was called out of order.")}clearDependencies(){this.dependencies.forEach(e=>e.unsubscribe(this.markDirty)),this.dependencies.clear()}collect(){const e=be.collectionStack.at(-1);e&&(e.dependencies.add(this.event.subscribable),this.event.subscribe(e.markDirty))}dispose(){this.clearDependencies(),this.event.clear(),this.owner=null}async toPromise(){do await be.consumePromises(),this.invokable();while(be.hasPromises());return this.invokable}}be.collectionSet=new Set;be.collectionStack=[];be.promises=[];const ma=Symbol.for("@twick/core/signals/default");function Dt(r){return typeof r=="function"}function qi(r,e){return Dt(r)?()=>e(r()):e(r)}function is(r){return Dt(r)?r():r}class Di extends be{constructor(e,t,s=void 0,n=h=>h,a={}){super(s),this.initial=e,this.interpolation=t,this.parser=n,this.tweening=!1,Object.defineProperty(this.invokable,"reset",{value:this.reset.bind(this)}),Object.defineProperty(this.invokable,"save",{value:this.save.bind(this)}),Object.defineProperty(this.invokable,"isInitial",{value:this.isInitial.bind(this)}),this.initial!==void 0&&(this.current=this.initial,this.markDirty(),Dt(this.initial)||(this.last=this.parse(this.initial))),this.extensions={getter:this.getter.bind(this),setter:this.setter.bind(this),tweener:this.tweener.bind(this),...a}}toSignal(){return this.invokable}parse(e){return this.parser(e)}set(e){return this.extensions.setter(e),this.owner}setter(e){return e===ma&&(e=this.initial),this.current===e?this.owner:(this.current=e,this.markDirty(),this.clearDependencies(),Dt(e)||(this.last=this.parse(e)),this.owner)}get(){return this.extensions.getter()}getter(){var e;if(this.event.isRaised()&&Dt(this.current)){this.clearDependencies(),this.startCollecting();try{this.last=this.parse(this.current())}catch(t){Me().error({...zh(t),inspect:(e=this.owner)==null?void 0:e.key})}this.finishCollecting()}return this.event.reset(),this.collect(),this.last}invoke(e,t,s=Ls,n=this.interpolation){return e===void 0?this.get():t===void 0?this.set(e):this.createQueue(s,n).to(e,t)}createQueue(e,t){const s=this.get(),n=[],a=Vo("animation chain",function*(){for(;n.length>0;)yield*n.shift()});return a.to=(h,l,u=e,d=t)=>(e=u,t=d,n.push(this.tween(h,l,u,d)),a),a.back=(h,l=e,u=t)=>(e=l,t=u,n.push(this.tween(s,h,e,t)),a),a.wait=h=>(n.push(ae(h)),a),a.run=h=>(n.push(h),a),a.do=h=>(n.push(Vo(function*(){h()})),a),a}*tween(e,t,s,n){e===ma&&(e=this.initial),this.tweening=!0,yield*this.extensions.tweener(e,t,s,n),this.set(e),this.tweening=!1}*tweener(e,t,s,n){const a=this.get();yield*_s(t,h=>{this.set(n(a,this.parse(is(e)),s(h)))})}dispose(){super.dispose(),this.initial=void 0,this.current=void 0,this.last=void 0}reset(){return this.initial!==void 0&&this.set(this.initial),this.owner}save(){return this.set(this.get())}isInitial(){return this.collect(),this.current===this.initial}getInitial(){return this.initial}raw(){return this.current}isTweening(){return this.tweening}}class Jn extends Di{constructor(e,t,s,n,a=void 0,h={}){var l;super(void 0,n,a,t,h),this.entries=e,this.signals=[],this.parser=t;for(const u of e){let d,p;Array.isArray(u)?([d,p]=u,(l=p.context).owner??(l.owner=this)):(d=u,p=new Di(qi(s,g=>t(g)[u]),ne,a??this.invokable).toSignal()),this.signals.push([d,p]),Object.defineProperty(this.invokable,d,{value:p})}}toSignal(){return this.invokable}parse(e){return this.parser(e)}getter(){return this.parse(Object.fromEntries(this.signals.map(([e,t])=>[e,t()])))}setter(e){if(Dt(e))for(const[t,s]of this.signals)s(()=>this.parser(e())[t]);else{const t=this.parse(e);for(const[s,n]of this.signals)n(t[s])}return this.owner}reset(){for(const[,e]of this.signals)e.reset();return this.owner}save(){for(const[,e]of this.signals)e.save();return this.owner}isInitial(){for(const[,e]of this.signals)if(!e.isInitial())return!1;return!0}raw(){return Object.fromEntries(this.signals.map(([e,t])=>[e,t.context.raw()]))}}class gf extends be{constructor(e,t){super(t),this.factory=e,this.markDirty()}toSignal(){return this.invokable}dispose(){super.dispose(),this.last=void 0}invoke(...e){var t;if(this.event.isRaised()){this.clearDependencies(),this.startCollecting();try{this.last=this.factory(...e)}catch(s){Me().error({...zh(s),inspect:(t=this.owner)==null?void 0:t.key})}this.finishCollecting()}return this.event.reset(),this.collect(),this.last}}function mf(r,e){return new gf(r,e).toSignal()}function ss(r,e=ts,t){return new Di(r,e,t).toSignal()}class mt{static createSignal(e,t=mt.lerp){return new Jn(["top","right","bottom","left"],s=>new mt(s),e,t).toSignal()}static lerp(e,t,s){return new mt(ne(e.top,t.top,s),ne(e.right,t.right,s),ne(e.bottom,t.bottom,s),ne(e.left,t.left,s))}get x(){return this.left+this.right}get y(){return this.top+this.bottom}constructor(e=0,t,s,n){if(this.top=0,this.right=0,this.bottom=0,this.left=0,e!=null){if(Array.isArray(e)&&(n=e[3],s=e[2],t=e[1],e=e[0]),typeof e=="number"){this.top=e,this.right=t!==void 0?t:e,this.bottom=s!==void 0?s:e,this.left=n!==void 0?n:t!==void 0?t:e;return}this.top=e.top,this.right=e.right,this.bottom=e.bottom,this.left=e.left}}lerp(e,t){return mt.lerp(this,e,t)}scale(e){return new mt(this.top*e,this.right*e,this.bottom*e,this.left*e)}addScalar(e){return new mt(this.top+e,this.right+e,this.bottom+e,this.left+e)}toSymbol(){return mt.symbol}toString(){return`Spacing(${this.top}, ${this.right}, ${this.bottom}, ${this.left})`}toUniform(e,t){e.uniform4f(t,this.top,this.right,this.bottom,this.left)}serialize(){return{top:this.top,right:this.right,bottom:this.bottom,left:this.left}}}mt.symbol=Symbol.for("@twick/core/types/Spacing");const Qh=1e-6;class R{static createSignal(e,t=R.lerp,s){return new Jn(["x","y"],n=>new R(n),e,t,s).toSignal()}static lerp(e,t,s){let n,a;return typeof s=="number"?n=a=s:(n=s.x,a=s.y),new R(ne(e.x,t.x,n),ne(e.y,t.y,a))}static arcLerp(e,t,s,n=!1,a){return a??(a=e.sub(t).ctg),R.lerp(e,t,new R(Kh(s,n,a)))}static createArcLerp(e,t){return(s,n,a)=>R.arcLerp(s,n,a,e,t)}static polarLerp(e,t,s,n=!1,a=R.zero){e=e.sub(a),t=t.sub(a);const h=e.degrees;let l=t.degrees;h>l!==n&&(l=l+(n?-360:360));const d=ne(h,l,s)*li,p=ne(e.magnitude,t.magnitude,s);return new R(p*Math.cos(d)+a.x,p*Math.sin(d)+a.y)}static createPolarLerp(e=!1,t=R.zero){return(s,n,a)=>R.polarLerp(s,n,a,e,new R(t))}static fromOrigin(e){const t=new R;return e===Ze.Middle||(e&At.Left?t.x=-1:e&At.Right&&(t.x=1),e&At.Top?t.y=-1:e&At.Bottom&&(t.y=1)),t}static fromScalar(e){return new R(e,e)}static fromRadians(e){return new R(Math.cos(e),Math.sin(e))}static fromDegrees(e){return R.fromRadians(e*li)}static radians(e,t){return Math.atan2(t,e)}static degrees(e,t){return R.radians(e,t)*Ru}static magnitude(e,t){return Math.sqrt(e*e+t*t)}static squaredMagnitude(e,t){return e*e+t*t}static angleBetween(e,t){return Math.acos(ye(-1,1,e.dot(t)/(e.magnitude*t.magnitude)))*(e.cross(t)>=0?1:-1)}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}get magnitude(){return R.magnitude(this.x,this.y)}get squaredMagnitude(){return R.squaredMagnitude(this.x,this.y)}get normalized(){return this.scale(1/R.magnitude(this.x,this.y))}get safe(){return new R(isNaN(this.x)?0:this.x,isNaN(this.y)?0:this.y)}get flipped(){return new R(-this.x,-this.y)}get floored(){return new R(Math.floor(this.x),Math.floor(this.y))}get perpendicular(){return new R(this.y,-this.x)}get radians(){return R.radians(this.x,this.y)}get degrees(){return R.degrees(this.x,this.y)}get ctg(){return this.x/this.y}constructor(e,t){if(this.x=0,this.y=0,e!=null){if(typeof e!="object"){this.x=e,this.y=t??e;return}if(Array.isArray(e)){this.x=e[0],this.y=e[1];return}if("width"in e){this.x=e.width,this.y=e.height;return}this.x=e.x,this.y=e.y}}lerp(e,t){return R.lerp(this,e,t)}getOriginOffset(e){const t=R.fromOrigin(e);return t.x*=this.x/2,t.y*=this.y/2,t}scale(e){return new R(this.x*e,this.y*e)}mul(e){const t=new R(e);return new R(this.x*t.x,this.y*t.y)}div(e){const t=new R(e);return new R(this.x/t.x,this.y/t.y)}add(e){const t=new R(e);return new R(this.x+t.x,this.y+t.y)}sub(e){const t=new R(e);return new R(this.x-t.x,this.y-t.y)}dot(e){const t=new R(e);return this.x*t.x+this.y*t.y}cross(e){const t=new R(e);return this.x*t.y-this.y*t.x}mod(e){const t=new R(e);return new R(this.x%t.x,this.y%t.y)}addX(e){return new R(this.x+e,this.y)}addY(e){return new R(this.x,this.y+e)}toSymbol(){return R.symbol}toString(){return`Vector2(${this.x}, ${this.y})`}toUniform(e,t){e.uniform2f(t,this.x,this.y)}serialize(){return{x:this.x,y:this.y}}exactlyEquals(e){return this.x===e.x&&this.y===e.y}equals(e,t=Qh){return Math.abs(this.x-e.x)<=t+Number.EPSILON&&Math.abs(this.y-e.y)<=t+Number.EPSILON}}R.symbol=Symbol.for("@twick/core/types/Vector2");R.zero=new R;R.one=new R(1,1);R.right=new R(1,0);R.left=new R(-1,0);R.up=new R(0,1);R.down=new R(0,-1);R.top=new R(0,-1);R.bottom=new R(0,1);R.topLeft=new R(-1,-1);R.topRight=new R(1,-1);R.bottomLeft=new R(-1,1);R.bottomRight=new R(1,1);class we{static fromRotation(e){return we.identity.rotate(e)}static fromTranslation(e){return we.identity.translate(new R(e))}static fromScaling(e){return we.identity.scale(new R(e))}get x(){return new R(this.values[0],this.values[1])}get y(){return new R(this.values[2],this.values[3])}get scaleX(){return this.values[0]}set scaleX(e){this.values[0]=this.x.normalized.scale(e).x}get skewX(){return this.values[1]}set skewX(e){this.values[1]=e}get scaleY(){return this.values[3]}set scaleY(e){this.values[3]=this.y.normalized.scale(e).y}get skewY(){return this.values[2]}set skewY(e){this.values[2]=e}get translateX(){return this.values[4]}set translateX(e){this.values[4]=e}get translateY(){return this.values[5]}set translateY(e){this.values[5]=e}get rotation(){return R.degrees(this.values[0],this.values[1])}set rotation(e){const t=this.rotate(e-this.rotation);this.values[0]=t.values[0],this.values[1]=t.values[1],this.values[2]=t.values[2],this.values[3]=t.values[3]}get translation(){return new R(this.values[4],this.values[5])}set translation(e){const t=new R(e);this.values[4]=t.x,this.values[5]=t.y}get scaling(){return new R(this.values[0],this.values[3])}set scaling(e){const t=new R(e),s=new R(this.values[0],this.values[1]).normalized,n=new R(this.values[2],this.values[3]).normalized;this.values[0]=s.x*t.x,this.values[1]=s.y*t.y,this.values[2]=n.x*t.x,this.values[3]=n.y*t.y}get inverse(){const e=this.values[0],t=this.values[1],s=this.values[2],n=this.values[3],a=this.values[4],h=this.values[5];let l=e*n-t*s;return l?(l=1/l,new we(n*l,-t*l,-s*l,e*l,(s*h-n*a)*l,(t*a-e*h)*l)):null}get determinant(){return this.values[0]*this.values[3]-this.values[1]*this.values[2]}get domMatrix(){return new DOMMatrix([this.values[0],this.values[1],this.values[2],this.values[3],this.values[4],this.values[5]])}constructor(e,t,s,n,a,h){if(this.values=new Float32Array(6),arguments.length===0){this.values=new Float32Array([1,0,0,1,0,0]);return}if(arguments.length===6){this.values[0]=e,this.values[1]=t,this.values[2]=s,this.values[3]=n,this.values[4]=a,this.values[5]=h;return}if(e instanceof DOMMatrix){this.values[0]=e.m11,this.values[1]=e.m12,this.values[2]=e.m21,this.values[3]=e.m22,this.values[4]=e.m41,this.values[5]=e.m42;return}if(e instanceof we){this.values=e.values;return}if(Array.isArray(e)){if(e.length===2){this.values[0]=e[0],this.values[1]=e[1],this.values[2]=t[0],this.values[3]=t[1],this.values[4]=s[0],this.values[5]=s[1];return}if(e.length===3){const p=new R(e[0]),g=new R(e[1]),y=new R(e[2]);this.values[0]=p.x,this.values[1]=p.y,this.values[2]=g.x,this.values[3]=g.y,this.values[4]=y.x,this.values[5]=y.y;return}this.values[0]=e[0],this.values[1]=e[1],this.values[2]=e[2],this.values[3]=e[3],this.values[4]=e[4],this.values[5]=e[5];return}const l=new R(e),u=new R(t),d=new R(s);this.values[0]=l.x,this.values[1]=l.y,this.values[2]=u.x,this.values[3]=u.y,this.values[4]=d.x,this.values[5]=d.y}column(e){return new R(this.values[e*2],this.values[e*2+1])}row(e){return[this.values[e],this.values[e+2],this.values[e+4]]}mul(e){const t=this.values[0],s=this.values[1],n=this.values[2],a=this.values[3],h=this.values[4],l=this.values[5],u=e.values[0],d=e.values[1],p=e.values[2],g=e.values[3],y=e.values[4],v=e.values[5];return new we(t*u+n*d,s*u+a*d,t*p+n*g,s*p+a*g,t*y+n*v+h,s*y+a*v+l)}rotate(e,t=!0){t&&(e*=li);const s=this.values[0],n=this.values[1],a=this.values[2],h=this.values[3],l=this.values[4],u=this.values[5],d=Math.sin(e),p=Math.cos(e);return new we(s*p+a*d,n*p+h*d,s*-d+a*p,n*-d+h*p,l,u)}scale(e){const t=new R(e);return new we(this.values[0]*t.x,this.values[1]*t.x,this.values[2]*t.y,this.values[3]*t.y,this.values[4],this.values[5])}mulScalar(e){return new we(this.values[0]*e,this.values[1]*e,this.values[2]*e,this.values[3]*e,this.values[4]*e,this.values[5]*e)}translate(e){const t=new R(e);return new we(this.values[0],this.values[1],this.values[2],this.values[3],this.values[0]*t.x+this.values[2]*t.y+this.values[4],this.values[1]*t.x+this.values[3]*t.y+this.values[5])}add(e){return new we(this.values[0]+e.values[0],this.values[1]+e.values[1],this.values[2]+e.values[2],this.values[3]+e.values[3],this.values[4]+e.values[4],this.values[5]+e.values[5])}sub(e){return new we(this.values[0]-e.values[0],this.values[1]-e.values[1],this.values[2]-e.values[2],this.values[3]-e.values[3],this.values[4]-e.values[4],this.values[5]-e.values[5])}toSymbol(){return we.symbol}toUniform(e,t){e.uniformMatrix3x2fv(t,!1,this.values)}equals(e,t=Qh){return Math.abs(this.values[0]-e.values[0])<=t+Number.EPSILON&&Math.abs(this.values[1]-e.values[1])<=t+Number.EPSILON&&Math.abs(this.values[2]-e.values[2])<=t+Number.EPSILON&&Math.abs(this.values[3]-e.values[3])<=t+Number.EPSILON&&Math.abs(this.values[4]-e.values[4])<=t+Number.EPSILON&&Math.abs(this.values[5]-e.values[5])<=t+Number.EPSILON}exactlyEquals(e){return this.values[0]===e.values[0]&&this.values[1]===e.values[1]&&this.values[2]===e.values[2]&&this.values[3]===e.values[3]&&this.values[4]===e.values[4]&&this.values[5]===e.values[5]}}we.symbol=Symbol.for("@twick/core/types/Matrix2D");we.identity=new we(1,0,0,1,0,0);we.zero=new we(0,0,0,0,0,0);function Pt(r,e){const t=new we(e);return new R(r.x*t.scaleX+r.y*t.skewY+t.translateX,r.x*t.skewX+r.y*t.scaleY+t.translateY)}function Vt(r,e){const t=new we(e);return new R(r.x*t.scaleX+r.y*t.skewY,r.x*t.skewX+r.y*t.scaleY)}class fe{static createSignal(e,t=fe.lerp){return new Jn(["x","y","width","height"],s=>new fe(s),e,t).toSignal()}static lerp(e,t,s){let n,a,h,l;return typeof s=="number"?n=a=h=l=s:s instanceof R?(n=h=s.x,a=l=s.y):(n=s.x,a=s.y,h=s.width,l=s.height),new fe(ne(e.x,t.x,n),ne(e.y,t.y,a),ne(e.width,t.width,h),ne(e.height,t.height,l))}static arcLerp(e,t,s,n=!1,a){return a??(a=(e.position.sub(t.position).ctg+e.size.sub(t.size).ctg)/2),fe.lerp(e,t,new R(Kh(s,n,a)))}static fromSizeCentered(e){return new fe(-e.width/2,-e.height/2,e.width,e.height)}static fromPoints(...e){let t=1/0,s=1/0,n=-1/0,a=-1/0;for(const h of e)h.x>n&&(n=h.x),h.x<t&&(t=h.x),h.y>a&&(a=h.y),h.y<s&&(s=h.y);return new fe(t,s,n-t,a-s)}static fromBBoxes(...e){let t=1/0,s=1/0,n=-1/0,a=-1/0;for(const h of e){const l=h.x+h.width;l>n&&(n=l),h.x<t&&(t=h.x);const u=h.y+h.height;u>a&&(a=u),h.y<s&&(s=h.y)}return new fe(t,s,n-t,a-s)}lerp(e,t){return fe.lerp(this,e,t)}get position(){return new R(this.x,this.y)}set position(e){this.x=e.x,this.y=e.y}get size(){return new R(this.width,this.height)}get center(){return new R(this.x+this.width/2,this.y+this.height/2)}get left(){return this.x}set left(e){this.width+=this.x-e,this.x=e}get right(){return this.x+this.width}set right(e){this.width=e-this.x}get top(){return this.y}set top(e){this.height+=this.y-e,this.y=e}get bottom(){return this.y+this.height}set bottom(e){this.height=e-this.y}get topLeft(){return this.position}get topRight(){return new R(this.x+this.width,this.y)}get bottomLeft(){return new R(this.x,this.y+this.height)}get bottomRight(){return new R(this.x+this.width,this.y+this.height)}get corners(){return[this.topLeft,this.topRight,this.bottomRight,this.bottomLeft]}get pixelPerfect(){return new fe(Math.floor(this.x),Math.floor(this.y),Math.ceil(this.width+1),Math.ceil(this.height+1))}constructor(e,t=0,s=0,n=0){if(this.x=0,this.y=0,this.width=0,this.height=0,e!=null){if(typeof e=="number"){this.x=e,this.y=t,this.width=s,this.height=n;return}if(e instanceof R){this.x=e.x,this.y=e.y,t instanceof R&&(this.width=t.x,this.height=t.y);return}if(Array.isArray(e)){this.x=e[0],this.y=e[1],this.width=e[2],this.height=e[3];return}this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height}}transform(e){return new fe(Pt(this.position,e),Vt(this.size,e))}transformCorners(e){return this.corners.map(t=>Pt(t,e))}expand(e){const t=new mt(e),s=new fe(this);return s.left-=t.left,s.top-=t.top,s.right+=t.right,s.bottom+=t.bottom,s}addSpacing(e){return this.expand(e)}includes(e){return e.x>=this.x&&e.x<=this.x+this.width&&e.y>=this.y&&e.y<=this.y+this.height}intersects(e){return this.left<e.right&&this.right>e.left&&this.top<e.bottom&&this.bottom>e.top}intersection(e){const t=new fe;return this.intersects(e)&&(t.left=Math.max(this.left,e.left),t.top=Math.max(this.top,e.top),t.right=Math.min(this.right,e.right),t.bottom=Math.min(this.bottom,e.bottom)),t}union(e){const t=new fe;return t.left=Math.min(this.left,e.left),t.top=Math.min(this.top,e.top),t.right=Math.max(this.right,e.right),t.bottom=Math.max(this.bottom,e.bottom),t}toSymbol(){return fe.symbol}toString(){return`BBox(${this.x}, ${this.y}, ${this.width}, ${this.height})`}toUniform(e,t){e.uniform4f(t,this.x,this.y,this.width,this.height)}serialize(){return{x:this.x,y:this.y,width:this.width,height:this.height}}}fe.symbol=Symbol.for("@twick/core/types/Rect");const Zh=(r,e)=>{if(typeof r=="number"){if(e===3)return{mode:"rgb",r:(r>>8&15|r>>4&240)/255,g:(r>>4&15|r&240)/255,b:(r&15|r<<4&240)/255};if(e===4)return{mode:"rgb",r:(r>>12&15|r>>8&240)/255,g:(r>>8&15|r>>4&240)/255,b:(r>>4&15|r&240)/255,alpha:(r&15|r<<4&240)/255};if(e===6)return{mode:"rgb",r:(r>>16&255)/255,g:(r>>8&255)/255,b:(r&255)/255};if(e===8)return{mode:"rgb",r:(r>>24&255)/255,g:(r>>16&255)/255,b:(r>>8&255)/255,alpha:(r&255)/255}}},yf={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},xf=r=>Zh(yf[r.toLowerCase()],6),vf=/^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i,Sf=r=>{let e;return(e=r.match(vf))?Zh(parseInt(e[1],16),e[1].length):void 0},di="([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)",Es=`${di}%`,Ja=`(?:${di}%|${di})`,_f=`(?:${di}(deg|grad|rad|turn)|${di})`,ns="\\s*,\\s*",Ef=new RegExp(`^rgba?\\(\\s*${di}${ns}${di}${ns}${di}\\s*(?:,\\s*${Ja}\\s*)?\\)$`),Tf=new RegExp(`^rgba?\\(\\s*${Es}${ns}${Es}${ns}${Es}\\s*(?:,\\s*${Ja}\\s*)?\\)$`),bf=r=>{let e={mode:"rgb"},t;if(t=r.match(Ef))t[1]!==void 0&&(e.r=t[1]/255),t[2]!==void 0&&(e.g=t[2]/255),t[3]!==void 0&&(e.b=t[3]/255);else if(t=r.match(Tf))t[1]!==void 0&&(e.r=t[1]/100),t[2]!==void 0&&(e.g=t[2]/100),t[3]!==void 0&&(e.b=t[3]/100);else return;return t[4]!==void 0?e.alpha=Math.max(0,Math.min(1,t[4]/100)):t[5]!==void 0&&(e.alpha=Math.max(0,Math.min(1,+t[5]))),e},Af=(r,e)=>r===void 0?void 0:typeof r!="object"?sc(r):r.mode!==void 0?r:e?{...r,mode:e}:void 0,Rs=(r="rgb")=>e=>(e=Af(e,r))!==void 0?e.mode===r?e:bt[e.mode][r]?bt[e.mode][r](e):r==="rgb"?bt[e.mode].rgb(e):bt.rgb[r](bt[e.mode].rgb(e)):void 0,bt={},Jh={},kn=[],ec={},If=r=>r,Se=r=>(bt[r.mode]={...bt[r.mode],...r.toMode},Object.keys(r.fromMode||{}).forEach(e=>{bt[e]||(bt[e]={}),bt[e][r.mode]=r.fromMode[e]}),r.ranges||(r.ranges={}),r.difference||(r.difference={}),r.channels.forEach(e=>{if(r.ranges[e]===void 0&&(r.ranges[e]=[0,1]),!r.interpolate[e])throw new Error(`Missing interpolator for: ${e}`);typeof r.interpolate[e]=="function"&&(r.interpolate[e]={use:r.interpolate[e]}),r.interpolate[e].fixup||(r.interpolate[e].fixup=If)}),Jh[r.mode]=r,(r.parse||[]).forEach(e=>{wf(e,r.mode)}),Rs(r.mode)),tc=r=>Jh[r],wf=(r,e)=>{if(typeof r=="string"){if(!e)throw new Error("'mode' required when 'parser' is a string");ec[r]=e}else typeof r=="function"&&kn.indexOf(r)<0&&kn.push(r)},ya=/[^\x00-\x7F]|[a-zA-Z_]/,Lf=/[^\x00-\x7F]|[-\w]/,B={Function:"function",Ident:"ident",Number:"number",Percentage:"percentage",ParenClose:")",None:"none",Hue:"hue",Alpha:"alpha"};let re=0;function Qs(r){let e=r[re],t=r[re+1];return e==="-"||e==="+"?/\d/.test(t)||t==="."&&/\d/.test(r[re+2]):e==="."?/\d/.test(t):/\d/.test(e)}function xa(r){if(re>=r.length)return!1;let e=r[re];if(ya.test(e))return!0;if(e==="-"){if(r.length-re<2)return!1;let t=r[re+1];return!!(t==="-"||ya.test(t))}return!1}const Rf={deg:1,rad:180/Math.PI,grad:9/10,turn:360};function ms(r){let e="";if((r[re]==="-"||r[re]==="+")&&(e+=r[re++]),e+=Zs(r),r[re]==="."&&/\d/.test(r[re+1])&&(e+=r[re++]+Zs(r)),(r[re]==="e"||r[re]==="E")&&((r[re+1]==="-"||r[re+1]==="+")&&/\d/.test(r[re+2])?e+=r[re++]+r[re++]+Zs(r):/\d/.test(r[re+1])&&(e+=r[re++]+Zs(r))),xa(r)){let t=Mn(r);return t==="deg"||t==="rad"||t==="turn"||t==="grad"?{type:B.Hue,value:e*Rf[t]}:void 0}return r[re]==="%"?(re++,{type:B.Percentage,value:+e}):{type:B.Number,value:+e}}function Zs(r){let e="";for(;/\d/.test(r[re]);)e+=r[re++];return e}function Mn(r){let e="";for(;re<r.length&&Lf.test(r[re]);)e+=r[re++];return e}function Cf(r){let e=Mn(r);return r[re]==="("?(re++,{type:B.Function,value:e}):e==="none"?{type:B.None,value:void 0}:{type:B.Ident,value:e}}function Df(r=""){let e=r.trim(),t=[],s;for(re=0;re<e.length;){if(s=e[re++],s===`
|
|
16
|
-
`||s===" "||s===" "){for(;
|
|
17
|
-
`||e[
|
|
18
|
-
`||e[re]===" "||e[re]===" ");)re++;let n;if(Qs(e)&&(n=ms(e),n.type!==B.Hue)){t.push({type:B.Alpha,value:n});continue}if(xa(e)&&Mn(e)==="none"){t.push({type:B.Alpha,value:{type:B.None,value:void 0}});continue}return}if(/\d/.test(s)){re--,t.push(ms(e));continue}if(ya.test(s)){re--,t.push(Cf(e));continue}return}return t}function Pf(r){r._i=0;let e=r[r._i++];if(!e||e.type!==B.Function||e.value!=="color"||(e=r[r._i++],e.type!==B.Ident))return;const t=ec[e.value];if(!t)return;const s={mode:t},n=ic(r,!1);if(!n)return;const a=tc(t).channels;for(let h=0,l,u;h<a.length;h++)l=n[h],u=a[h],l.type!==B.None&&(s[u]=l.type===B.Number?l.value:l.value/100,u==="alpha"&&(s[u]=Math.max(0,Math.min(1,s[u]))));return s}function ic(r,e){const t=[];let s;for(;r._i<r.length;){if(s=r[r._i++],s.type===B.None||s.type===B.Number||s.type===B.Alpha||s.type===B.Percentage||e&&s.type===B.Hue){t.push(s);continue}if(s.type===B.ParenClose){if(r._i<r.length)return;continue}return}if(!(t.length<3||t.length>4)){if(t.length===4){if(t[3].type!==B.Alpha)return;t[3]=t[3].value}return t.length===3&&t.push({type:B.None,value:void 0}),t.every(n=>n.type!==B.Alpha)?t:void 0}}function kf(r,e){r._i=0;let t=r[r._i++];if(!t||t.type!==B.Function)return;let s=ic(r,e);if(s)return s.unshift(t.value),s}const sc=r=>{if(typeof r!="string")return;const e=Df(r),t=e?kf(e,!0):void 0;let s,n=0,a=kn.length;for(;n<a;)if((s=kn[n++](r,t))!==void 0)return s;return e?Pf(e):void 0};function Mf(r,e){if(!e||e[0]!=="rgb"&&e[0]!=="rgba")return;const t={mode:"rgb"},[,s,n,a,h]=e;if(!(s.type===B.Hue||n.type===B.Hue||a.type===B.Hue))return s.type!==B.None&&(t.r=s.type===B.Number?s.value/255:s.value/100),n.type!==B.None&&(t.g=n.type===B.Number?n.value/255:n.value/100),a.type!==B.None&&(t.b=a.type===B.Number?a.value/255:a.value/100),h.type!==B.None&&(t.alpha=Math.min(1,Math.max(0,h.type===B.Number?h.value:h.value/100))),t}const Ff=r=>r==="transparent"?{mode:"rgb",r:0,g:0,b:0,alpha:0}:void 0,Uf=(r,e,t)=>r+t*(e-r),Of=r=>{let e=[];for(let t=0;t<r.length-1;t++){let s=r[t],n=r[t+1];s===void 0&&n===void 0?e.push(void 0):s!==void 0&&n!==void 0?e.push([s,n]):e.push(s!==void 0?[s,s]:[n,n])}return e},Bf=r=>e=>{let t=Of(e);return s=>{let n=s*t.length,a=s>=1?t.length-1:Math.max(Math.floor(n),0),h=t[a];return h===void 0?void 0:r(h[0],h[1],n-a)}},H=Bf(Uf),Ue=r=>{let e=!1,t=r.map(s=>s!==void 0?(e=!0,s):1);return e?t:r},ls={mode:"rgb",channels:["r","g","b","alpha"],parse:[Mf,Sf,bf,xf,Ff,"srgb"],serialize:"srgb",interpolate:{r:H,g:H,b:H,alpha:{use:H,fixup:Ue}},gamut:!0,white:{r:1,g:1,b:1},black:{r:0,g:0,b:0}},_r=(r=0)=>Math.pow(Math.abs(r),563/256)*Math.sign(r),Ko=r=>{let e=_r(r.r),t=_r(r.g),s=_r(r.b),n={mode:"xyz65",x:.5766690429101305*e+.1855582379065463*t+.1882286462349947*s,y:.297344975250536*e+.6273635662554661*t+.0752914584939979*s,z:.0270313613864123*e+.0706888525358272*t+.9913375368376386*s};return r.alpha!==void 0&&(n.alpha=r.alpha),n},Er=r=>Math.pow(Math.abs(r),256/563)*Math.sign(r),Yo=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n={mode:"a98",r:Er(r*2.0415879038107465-e*.5650069742788597-.3447313507783297*t),g:Er(r*-.9692436362808798+e*1.8759675015077206+.0415550574071756*t),b:Er(r*.0134442806320312-e*.1183623922310184+1.0151749943912058*t)};return s!==void 0&&(n.alpha=s),n},Tr=(r=0)=>{const e=Math.abs(r);return e<=.04045?r/12.92:(Math.sign(r)||1)*Math.pow((e+.055)/1.055,2.4)},hs=({r,g:e,b:t,alpha:s})=>{let n={mode:"lrgb",r:Tr(r),g:Tr(e),b:Tr(t)};return s!==void 0&&(n.alpha=s),n},Mi=r=>{let{r:e,g:t,b:s,alpha:n}=hs(r),a={mode:"xyz65",x:.4123907992659593*e+.357584339383878*t+.1804807884018343*s,y:.2126390058715102*e+.715168678767756*t+.0721923153607337*s,z:.0193308187155918*e+.119194779794626*t+.9505321522496607*s};return n!==void 0&&(a.alpha=n),a},br=(r=0)=>{const e=Math.abs(r);return e>.0031308?(Math.sign(r)||1)*(1.055*Math.pow(e,1/2.4)-.055):r*12.92},cs=({r,g:e,b:t,alpha:s},n="rgb")=>{let a={mode:n,r:br(r),g:br(e),b:br(t)};return s!==void 0&&(a.alpha=s),a},Fi=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=cs({r:r*3.2409699419045226-e*1.537383177570094-.4986107602930034*t,g:r*-.9692436362808796+e*1.8759675015077204+.0415550574071756*t,b:r*.0556300796969936-e*.2039769588889765+1.0569715142428784*t});return s!==void 0&&(n.alpha=s),n},Nf={...ls,mode:"a98",parse:["a98-rgb"],serialize:"a98-rgb",fromMode:{rgb:r=>Yo(Mi(r)),xyz65:Yo},toMode:{rgb:r=>Fi(Ko(r)),xyz65:Ko}},Ge=r=>(r=r%360)<0?r+360:r,$f=(r,e)=>r.map((t,s,n)=>{if(t===void 0)return t;let a=Ge(t);return s===0||r[s-1]===void 0?a:e(a-Ge(n[s-1]))}).reduce((t,s)=>!t.length||s===void 0||t[t.length-1]===void 0?(t.push(s),t):(t.push(s+t[t.length-1]),t),[]),qt=r=>$f(r,e=>Math.abs(e)<=180?e:e-360*Math.sign(e)),Be=[-.14861,1.78277,-.29227,-.90649,1.97294,0],Gf=Math.PI/180,zf=180/Math.PI;let Wo=Be[3]*Be[4],jo=Be[1]*Be[4],qo=Be[1]*Be[2]-Be[0]*Be[3];const Hf=({r,g:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=(qo*t+r*Wo-e*jo)/(qo+Wo-jo),a=t-n,h=(Be[4]*(e-n)-Be[2]*a)/Be[3],l={mode:"cubehelix",l:n,s:n===0||n===1?void 0:Math.sqrt(a*a+h*h)/(Be[4]*n*(1-n))};return l.s&&(l.h=Math.atan2(h,a)*zf-120),s!==void 0&&(l.alpha=s),l},Vf=({h:r,s:e,l:t,alpha:s})=>{let n={mode:"rgb"};r=(r===void 0?0:r+120)*Gf,t===void 0&&(t=0);let a=e===void 0?0:e*t*(1-t),h=Math.cos(r),l=Math.sin(r);return n.r=t+a*(Be[0]*h+Be[1]*l),n.g=t+a*(Be[2]*h+Be[3]*l),n.b=t+a*(Be[4]*h+Be[5]*l),s!==void 0&&(n.alpha=s),n},er=(r,e)=>{if(r.h===void 0||e.h===void 0||!r.s||!e.s)return 0;let t=Ge(r.h),s=Ge(e.h),n=Math.sin((s-t+360)/2*Math.PI/180);return 2*Math.sqrt(r.s*e.s)*n},Kf=(r,e)=>{if(r.h===void 0||e.h===void 0)return 0;let t=Ge(r.h),s=Ge(e.h);return Math.abs(s-t)>180?t-(s-360*Math.sign(s-t)):s-t},tr=(r,e)=>{if(r.h===void 0||e.h===void 0||!r.c||!e.c)return 0;let t=Ge(r.h),s=Ge(e.h),n=Math.sin((s-t+360)/2*Math.PI/180);return 2*Math.sqrt(r.c*e.c)*n},Xt=r=>{let e=r.reduce((s,n)=>{if(n!==void 0){let a=n*Math.PI/180;s.sin+=Math.sin(a),s.cos+=Math.cos(a)}return s},{sin:0,cos:0}),t=Math.atan2(e.sin,e.cos)*180/Math.PI;return t<0?360+t:t},Yf={mode:"cubehelix",channels:["h","s","l","alpha"],parse:["--cubehelix"],serialize:"--cubehelix",ranges:{h:[0,360],s:[0,4.614],l:[0,1]},fromMode:{rgb:Hf},toMode:{rgb:Vf},interpolate:{h:{use:H,fixup:qt},s:H,l:H,alpha:{use:H,fixup:Ue}},difference:{h:er},average:{h:Xt}},ui=({l:r,a:e,b:t,alpha:s},n="lch")=>{e===void 0&&(e=0),t===void 0&&(t=0);let a=Math.sqrt(e*e+t*t),h={mode:n,l:r,c:a};return a&&(h.h=Ge(Math.atan2(t,e)*180/Math.PI)),s!==void 0&&(h.alpha=s),h},fi=({l:r,c:e,h:t,alpha:s},n="lab")=>{t===void 0&&(t=0);let a={mode:n,l:r,a:e?e*Math.cos(t/180*Math.PI):0,b:e?e*Math.sin(t/180*Math.PI):0};return s!==void 0&&(a.alpha=s),a},nc=Math.pow(29,3)/Math.pow(3,3),rc=Math.pow(6,3)/Math.pow(29,3),Re={X:.3457/.3585,Y:1,Z:(1-.3457-.3585)/.3585},Xi={X:.3127/.329,Y:1,Z:(1-.3127-.329)/.329};let Ar=r=>Math.pow(r,3)>rc?Math.pow(r,3):(116*r-16)/nc;const ac=({l:r,a:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=(r+16)/116,a=e/500+n,h=n-t/200,l={mode:"xyz65",x:Ar(a)*Xi.X,y:Ar(n)*Xi.Y,z:Ar(h)*Xi.Z};return s!==void 0&&(l.alpha=s),l},ir=r=>Fi(ac(r)),Ir=r=>r>rc?Math.cbrt(r):(nc*r+16)/116,oc=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Ir(r/Xi.X),a=Ir(e/Xi.Y),h=Ir(t/Xi.Z),l={mode:"lab65",l:116*a-16,a:500*(n-a),b:200*(a-h)};return s!==void 0&&(l.alpha=s),l},sr=r=>{let e=oc(Mi(r));return r.r===r.b&&r.b===r.g&&(e.a=e.b=0),e},Fn=1,lc=1,Cs=26/180*Math.PI,Un=Math.cos(Cs),On=Math.sin(Cs),hc=100/Math.log(139/100),va=({l:r,c:e,h:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n={mode:"lab65",l:(Math.exp(r*Fn/hc)-1)/.0039},a=(Math.exp(.0435*e*lc*Fn)-1)/.075,h=a*Math.cos(t/180*Math.PI-Cs),l=a*Math.sin(t/180*Math.PI-Cs);return n.a=h*Un-l/.83*On,n.b=h*On+l/.83*Un,s!==void 0&&(n.alpha=s),n},Sa=({l:r,a:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=e*Un+t*On,a=.83*(t*Un-e*On),h=Math.sqrt(n*n+a*a),l={mode:"dlch",l:hc/Fn*Math.log(1+.0039*r),c:Math.log(1+.075*h)/(.0435*lc*Fn)};return l.c&&(l.h=Ge((Math.atan2(a,n)+Cs)/Math.PI*180)),s!==void 0&&(l.alpha=s),l},Xo=r=>va(ui(r,"dlch")),Qo=r=>fi(Sa(r),"dlab"),Wf={mode:"dlab",parse:["--din99o-lab"],serialize:"--din99o-lab",toMode:{lab65:Xo,rgb:r=>ir(Xo(r))},fromMode:{lab65:Qo,rgb:r=>Qo(sr(r))},channels:["l","a","b","alpha"],ranges:{l:[0,100],a:[-40.09,45.501],b:[-40.469,44.344]},interpolate:{l:H,a:H,b:H,alpha:{use:H,fixup:Ue}}},jf={mode:"dlch",parse:["--din99o-lch"],serialize:"--din99o-lch",toMode:{lab65:va,dlab:r=>fi(r,"dlab"),rgb:r=>ir(va(r))},fromMode:{lab65:Sa,dlab:r=>ui(r,"dlch"),rgb:r=>Sa(sr(r))},channels:["l","c","h","alpha"],ranges:{l:[0,100],c:[0,51.484],h:[0,360]},interpolate:{l:H,c:H,h:{use:H,fixup:qt},alpha:{use:H,fixup:Ue}},difference:{h:tr},average:{h:Xt}};function qf({h:r,s:e,i:t,alpha:s}){r=Ge(r!==void 0?r:0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.abs(r/60%2-1),a;switch(Math.floor(r/60)){case 0:a={r:t*(1+e*(3/(2-n)-1)),g:t*(1+e*(3*(1-n)/(2-n)-1)),b:t*(1-e)};break;case 1:a={r:t*(1+e*(3*(1-n)/(2-n)-1)),g:t*(1+e*(3/(2-n)-1)),b:t*(1-e)};break;case 2:a={r:t*(1-e),g:t*(1+e*(3/(2-n)-1)),b:t*(1+e*(3*(1-n)/(2-n)-1))};break;case 3:a={r:t*(1-e),g:t*(1+e*(3*(1-n)/(2-n)-1)),b:t*(1+e*(3/(2-n)-1))};break;case 4:a={r:t*(1+e*(3*(1-n)/(2-n)-1)),g:t*(1-e),b:t*(1+e*(3/(2-n)-1))};break;case 5:a={r:t*(1+e*(3/(2-n)-1)),g:t*(1-e),b:t*(1+e*(3*(1-n)/(2-n)-1))};break;default:a={r:t*(1-e),g:t*(1-e),b:t*(1-e)}}return a.mode="rgb",s!==void 0&&(a.alpha=s),a}function Xf({r,g:e,b:t,alpha:s}){r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.max(r,e,t),a=Math.min(r,e,t),h={mode:"hsi",s:r+e+t===0?0:1-3*a/(r+e+t),i:(r+e+t)/3};return n-a!==0&&(h.h=(n===r?(e-t)/(n-a)+(e<t)*6:n===e?(t-r)/(n-a)+2:(r-e)/(n-a)+4)*60),s!==void 0&&(h.alpha=s),h}const Qf={mode:"hsi",toMode:{rgb:qf},parse:["--hsi"],serialize:"--hsi",fromMode:{rgb:Xf},channels:["h","s","i","alpha"],ranges:{h:[0,360]},gamut:"rgb",interpolate:{h:{use:H,fixup:qt},s:H,i:H,alpha:{use:H,fixup:Ue}},difference:{h:er},average:{h:Xt}};function Zf({h:r,s:e,l:t,alpha:s}){r=Ge(r!==void 0?r:0),e===void 0&&(e=0),t===void 0&&(t=0);let n=t+e*(t<.5?t:1-t),a=n-(n-t)*2*Math.abs(r/60%2-1),h;switch(Math.floor(r/60)){case 0:h={r:n,g:a,b:2*t-n};break;case 1:h={r:a,g:n,b:2*t-n};break;case 2:h={r:2*t-n,g:n,b:a};break;case 3:h={r:2*t-n,g:a,b:n};break;case 4:h={r:a,g:2*t-n,b:n};break;case 5:h={r:n,g:2*t-n,b:a};break;default:h={r:2*t-n,g:2*t-n,b:2*t-n}}return h.mode="rgb",s!==void 0&&(h.alpha=s),h}function Jf({r,g:e,b:t,alpha:s}){r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.max(r,e,t),a=Math.min(r,e,t),h={mode:"hsl",s:n===a?0:(n-a)/(1-Math.abs(n+a-1)),l:.5*(n+a)};return n-a!==0&&(h.h=(n===r?(e-t)/(n-a)+(e<t)*6:n===e?(t-r)/(n-a)+2:(r-e)/(n-a)+4)*60),s!==void 0&&(h.alpha=s),h}const ep=(r,e)=>{switch(e){case"deg":return+r;case"rad":return r/Math.PI*180;case"grad":return r/10*9;case"turn":return r*360}},tp=new RegExp(`^hsla?\\(\\s*${_f}${ns}${Es}${ns}${Es}\\s*(?:,\\s*${Ja}\\s*)?\\)$`),ip=r=>{let e=r.match(tp);if(!e)return;let t={mode:"hsl"};return e[3]!==void 0?t.h=+e[3]:e[1]!==void 0&&e[2]!==void 0&&(t.h=ep(e[1],e[2])),e[4]!==void 0&&(t.s=Math.min(Math.max(0,e[4]/100),1)),e[5]!==void 0&&(t.l=Math.min(Math.max(0,e[5]/100),1)),e[6]!==void 0?t.alpha=Math.max(0,Math.min(1,e[6]/100)):e[7]!==void 0&&(t.alpha=Math.max(0,Math.min(1,+e[7]))),t};function sp(r,e){if(!e||e[0]!=="hsl"&&e[0]!=="hsla")return;const t={mode:"hsl"},[,s,n,a,h]=e;if(s.type!==B.None){if(s.type===B.Percentage)return;t.h=s.value}if(n.type!==B.None){if(n.type===B.Hue)return;t.s=n.value/100}if(a.type!==B.None){if(a.type===B.Hue)return;t.l=a.value/100}return h.type!==B.None&&(t.alpha=Math.min(1,Math.max(0,h.type===B.Number?h.value:h.value/100))),t}const cc={mode:"hsl",toMode:{rgb:Zf},fromMode:{rgb:Jf},channels:["h","s","l","alpha"],ranges:{h:[0,360]},gamut:"rgb",parse:[sp,ip],serialize:r=>`hsl(${r.h!==void 0?r.h:"none"} ${r.s!==void 0?r.s*100+"%":"none"} ${r.l!==void 0?r.l*100+"%":"none"}${r.alpha<1?` / ${r.alpha}`:""})`,interpolate:{h:{use:H,fixup:qt},s:H,l:H,alpha:{use:H,fixup:Ue}},difference:{h:er},average:{h:Xt}};function dc({h:r,s:e,v:t,alpha:s}){r=Ge(r!==void 0?r:0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.abs(r/60%2-1),a;switch(Math.floor(r/60)){case 0:a={r:t,g:t*(1-e*n),b:t*(1-e)};break;case 1:a={r:t*(1-e*n),g:t,b:t*(1-e)};break;case 2:a={r:t*(1-e),g:t,b:t*(1-e*n)};break;case 3:a={r:t*(1-e),g:t*(1-e*n),b:t};break;case 4:a={r:t*(1-e*n),g:t*(1-e),b:t};break;case 5:a={r:t,g:t*(1-e),b:t*(1-e*n)};break;default:a={r:t*(1-e),g:t*(1-e),b:t*(1-e)}}return a.mode="rgb",s!==void 0&&(a.alpha=s),a}function uc({r,g:e,b:t,alpha:s}){r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.max(r,e,t),a=Math.min(r,e,t),h={mode:"hsv",s:n===0?0:1-a/n,v:n};return n-a!==0&&(h.h=(n===r?(e-t)/(n-a)+(e<t)*6:n===e?(t-r)/(n-a)+2:(r-e)/(n-a)+4)*60),s!==void 0&&(h.alpha=s),h}const fc={mode:"hsv",toMode:{rgb:dc},parse:["--hsv"],serialize:"--hsv",fromMode:{rgb:uc},channels:["h","s","v","alpha"],ranges:{h:[0,360]},gamut:"rgb",interpolate:{h:{use:H,fixup:qt},s:H,v:H,alpha:{use:H,fixup:Ue}},difference:{h:er},average:{h:Xt}};function np({h:r,w:e,b:t,alpha:s}){if(e===void 0&&(e=0),t===void 0&&(t=0),e+t>1){let n=e+t;e/=n,t/=n}return dc({h:r,s:t===1?1:1-e/(1-t),v:1-t,alpha:s})}function rp(r){let e=uc(r);if(e===void 0)return;let t=e.s!==void 0?e.s:0,s=e.v!==void 0?e.v:0,n={mode:"hwb",w:(1-t)*s,b:1-s};return e.h!==void 0&&(n.h=e.h),e.alpha!==void 0&&(n.alpha=e.alpha),n}function ap(r,e){if(!e||e[0]!=="hwb")return;const t={mode:"hwb"},[,s,n,a,h]=e;if(s.type!==B.None){if(s.type===B.Percentage)return;t.h=s.value}if(n.type!==B.None){if(n.type===B.Hue)return;t.w=n.value/100}if(a.type!==B.None){if(a.type===B.Hue)return;t.b=a.value/100}return h.type!==B.None&&(t.alpha=Math.min(1,Math.max(0,h.type===B.Number?h.value:h.value/100))),t}const op={mode:"hwb",toMode:{rgb:np},fromMode:{rgb:rp},channels:["h","w","b","alpha"],ranges:{h:[0,360]},gamut:"rgb",parse:[ap],serialize:r=>`hwb(${r.h!==void 0?r.h:"none"} ${r.w!==void 0?r.w*100+"%":"none"} ${r.b!==void 0?r.b*100+"%":"none"}${r.alpha<1?` / ${r.alpha}`:""})`,interpolate:{h:{use:H,fixup:qt},w:H,b:H,alpha:{use:H,fixup:Ue}},difference:{h:Kf},average:{h:Xt}},pc=203,nr=.1593017578125,gc=78.84375,rr=.8359375,ar=18.8515625,or=18.6875;function wr(r){if(r<0)return 0;const e=Math.pow(r,1/gc);return 1e4*Math.pow(Math.max(0,e-rr)/(ar-or*e),1/nr)}function Lr(r){if(r<0)return 0;const e=Math.pow(r/1e4,nr);return Math.pow((rr+ar*e)/(1+or*e),gc)}const Rr=r=>Math.max(r/pc,0),Zo=({i:r,t:e,p:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);const n=wr(r+.008609037037932761*e+.11102962500302593*t),a=wr(r-.00860903703793275*e-.11102962500302599*t),h=wr(r+.5600313357106791*e-.32062717498731885*t),l={mode:"xyz65",x:Rr(2.070152218389422*n-1.3263473389671556*a+.2066510476294051*h),y:Rr(.3647385209748074*n+.680566024947227*a-.0453045459220346*h),z:Rr(-.049747207535812*n-.0492609666966138*a+1.1880659249923042*h)};return s!==void 0&&(l.alpha=s),l},Cr=(r=0)=>Math.max(r*pc,0),Jo=({x:r,y:e,z:t,alpha:s})=>{const n=Cr(r),a=Cr(e),h=Cr(t),l=Lr(.3592832590121217*n+.6976051147779502*a-.0358915932320289*h),u=Lr(-.1920808463704995*n+1.1004767970374323*a+.0753748658519118*h),d=Lr(.0070797844607477*n+.0748396662186366*a+.8433265453898765*h),p=.5*l+.5*u,g=1.61376953125*l-3.323486328125*u+1.709716796875*d,y=4.378173828125*l-4.24560546875*u-.132568359375*d,v={mode:"itp",i:p,t:g,p:y};return s!==void 0&&(v.alpha=s),v},lp={mode:"itp",channels:["i","t","p","alpha"],parse:["--ictcp"],serialize:"--ictcp",toMode:{xyz65:Zo,rgb:r=>Fi(Zo(r))},fromMode:{xyz65:Jo,rgb:r=>Jo(Mi(r))},ranges:{i:[0,.581],t:[-.369,.272],p:[-.164,.331]},interpolate:{i:H,t:H,p:H,alpha:{use:H,fixup:Ue}}},hp=134.03437499999998,cp=16295499532821565e-27,Dr=r=>{if(r<0)return 0;let e=Math.pow(r/1e4,nr);return Math.pow((rr+ar*e)/(1+or*e),hp)},Pr=(r=0)=>Math.max(r*203,0),mc=({x:r,y:e,z:t,alpha:s})=>{r=Pr(r),e=Pr(e),t=Pr(t);let n=1.15*r-.15*t,a=.66*e+.34*r,h=Dr(.41478972*n+.579999*a+.014648*t),l=Dr(-.20151*n+1.120649*a+.0531008*t),u=Dr(-.0166008*n+.2648*a+.6684799*t),d=(h+l)/2,p={mode:"jab",j:.44*d/(1-.56*d)-cp,a:3.524*h-4.066708*l+.542708*u,b:.199076*h+1.096799*l-1.295875*u};return s!==void 0&&(p.alpha=s),p},dp=134.03437499999998,el=16295499532821565e-27,kr=r=>{if(r<0)return 0;let e=Math.pow(r,1/dp);return 1e4*Math.pow((rr-e)/(or*e-ar),1/nr)},Mr=r=>r/203,yc=({j:r,a:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=(r+el)/(.44+.56*(r+el)),a=kr(n+.13860504*e+.058047316*t),h=kr(n-.13860504*e-.058047316*t),l=kr(n-.096019242*e-.8118919*t),u={mode:"xyz65",x:Mr(1.661373024652174*a-.914523081304348*h+.23136208173913045*l),y:Mr(-.3250758611844533*a+1.571847026732543*h-.21825383453227928*l),z:Mr(-.090982811*a-.31272829*h+1.5227666*l)};return s!==void 0&&(u.alpha=s),u},xc=r=>{let e=mc(Mi(r));return r.r===r.b&&r.b===r.g&&(e.a=e.b=0),e},vc=r=>Fi(yc(r)),up={mode:"jab",channels:["j","a","b","alpha"],parse:["--jzazbz"],serialize:"--jzazbz",fromMode:{rgb:xc,xyz65:mc},toMode:{rgb:vc,xyz65:yc},ranges:{j:[0,.222],a:[-.109,.129],b:[-.185,.134]},interpolate:{j:H,a:H,b:H,alpha:{use:H,fixup:Ue}}},tl=({j:r,a:e,b:t,alpha:s})=>{e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.sqrt(e*e+t*t),a={mode:"jch",j:r,c:n};return n&&(a.h=Ge(Math.atan2(t,e)*180/Math.PI)),s!==void 0&&(a.alpha=s),a},il=({j:r,c:e,h:t,alpha:s})=>{t===void 0&&(t=0);let n={mode:"jab",j:r,a:e?e*Math.cos(t/180*Math.PI):0,b:e?e*Math.sin(t/180*Math.PI):0};return s!==void 0&&(n.alpha=s),n},fp={mode:"jch",parse:["--jzczhz"],serialize:"--jzczhz",toMode:{jab:il,rgb:r=>vc(il(r))},fromMode:{rgb:r=>tl(xc(r)),jab:tl},channels:["j","c","h","alpha"],ranges:{j:[0,.221],c:[0,.19],h:[0,360]},interpolate:{h:{use:H,fixup:qt},c:H,j:H,alpha:{use:H,fixup:Ue}},difference:{h:tr},average:{h:Xt}},lr=Math.pow(29,3)/Math.pow(3,3),eo=Math.pow(6,3)/Math.pow(29,3);let Fr=r=>Math.pow(r,3)>eo?Math.pow(r,3):(116*r-16)/lr;const to=({l:r,a:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=(r+16)/116,a=e/500+n,h=n-t/200,l={mode:"xyz50",x:Fr(a)*Re.X,y:Fr(n)*Re.Y,z:Fr(h)*Re.Z};return s!==void 0&&(l.alpha=s),l},Ns=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=cs({r:r*3.1341359569958707-e*1.6173863321612538-.4906619460083532*t,g:r*-.978795502912089+e*1.916254567259524+.03344273116131949*t,b:r*.07195537988411677-e*.2289768264158322+1.405386058324125*t});return s!==void 0&&(n.alpha=s),n},Sc=r=>Ns(to(r)),$s=r=>{let{r:e,g:t,b:s,alpha:n}=hs(r),a={mode:"xyz50",x:.436065742824811*e+.3851514688337912*t+.14307845442264197*s,y:.22249319175623702*e+.7168870538238823*t+.06061979053616537*s,z:.013923904500943465*e+.09708128566574634*t+.7140993584005155*s};return n!==void 0&&(a.alpha=n),a},Ur=r=>r>eo?Math.cbrt(r):(lr*r+16)/116,io=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Ur(r/Re.X),a=Ur(e/Re.Y),h=Ur(t/Re.Z),l={mode:"lab",l:116*a-16,a:500*(n-a),b:200*(a-h)};return s!==void 0&&(l.alpha=s),l},_c=r=>{let e=io($s(r));return r.r===r.b&&r.b===r.g&&(e.a=e.b=0),e};function pp(r,e){if(!e||e[0]!=="lab")return;const t={mode:"lab"},[,s,n,a,h]=e;if(!(s.type===B.Hue||n.type===B.Hue||a.type===B.Hue))return s.type!==B.None&&(t.l=Math.min(Math.max(0,s.value),100)),n.type!==B.None&&(t.a=n.type===B.Number?n.value:n.value*125/100),a.type!==B.None&&(t.b=a.type===B.Number?a.value:a.value*125/100),h.type!==B.None&&(t.alpha=Math.min(1,Math.max(0,h.type===B.Number?h.value:h.value/100))),t}const so={mode:"lab",toMode:{xyz50:to,rgb:Sc},fromMode:{xyz50:io,rgb:_c},channels:["l","a","b","alpha"],ranges:{l:[0,100],a:[-125,125],b:[-125,125]},parse:[pp],serialize:r=>`lab(${r.l!==void 0?r.l:"none"} ${r.a!==void 0?r.a:"none"} ${r.b!==void 0?r.b:"none"}${r.alpha<1?` / ${r.alpha}`:""})`,interpolate:{l:H,a:H,b:H,alpha:{use:H,fixup:Ue}}},gp={...so,mode:"lab65",parse:["--lab-d65"],serialize:"--lab-d65",toMode:{xyz65:ac,rgb:ir},fromMode:{xyz65:oc,rgb:sr},ranges:{l:[0,100],a:[-125,125],b:[-125,125]}};function mp(r,e){if(!e||e[0]!=="lch")return;const t={mode:"lch"},[,s,n,a,h]=e;if(s.type!==B.None){if(s.type===B.Hue)return;t.l=Math.min(Math.max(0,s.value),100)}if(n.type!==B.None&&(t.c=Math.max(0,n.type===B.Number?n.value:n.value*150/100)),a.type!==B.None){if(a.type===B.Percentage)return;t.h=a.value}return h.type!==B.None&&(t.alpha=Math.min(1,Math.max(0,h.type===B.Number?h.value:h.value/100))),t}const no={mode:"lch",toMode:{lab:fi,rgb:r=>Sc(fi(r))},fromMode:{rgb:r=>ui(_c(r)),lab:ui},channels:["l","c","h","alpha"],ranges:{l:[0,100],c:[0,150],h:[0,360]},parse:[mp],serialize:r=>`lch(${r.l!==void 0?r.l:"none"} ${r.c!==void 0?r.c:"none"} ${r.h!==void 0?r.h:"none"}${r.alpha<1?` / ${r.alpha}`:""})`,interpolate:{h:{use:H,fixup:qt},c:H,l:H,alpha:{use:H,fixup:Ue}},difference:{h:tr},average:{h:Xt}},yp={...no,mode:"lch65",parse:["--lch-d65"],serialize:"--lch-d65",toMode:{lab65:r=>fi(r,"lab65"),rgb:r=>ir(fi(r,"lab65"))},fromMode:{rgb:r=>ui(sr(r),"lch65"),lab65:r=>ui(r,"lch65")},ranges:{l:[0,100],c:[0,150],h:[0,360]}},Ec=({l:r,u:e,v:t,alpha:s})=>{e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.sqrt(e*e+t*t),a={mode:"lchuv",l:r,c:n};return n&&(a.h=Ge(Math.atan2(t,e)*180/Math.PI)),s!==void 0&&(a.alpha=s),a},Tc=({l:r,c:e,h:t,alpha:s})=>{t===void 0&&(t=0);let n={mode:"luv",l:r,u:e?e*Math.cos(t/180*Math.PI):0,v:e?e*Math.sin(t/180*Math.PI):0};return s!==void 0&&(n.alpha=s),n},bc=(r,e,t)=>4*r/(r+15*e+3*t),Ac=(r,e,t)=>9*e/(r+15*e+3*t),xp=bc(Re.X,Re.Y,Re.Z),vp=Ac(Re.X,Re.Y,Re.Z),Sp=r=>r<=eo?lr*r:116*Math.cbrt(r)-16,_a=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Sp(e/Re.Y),a=bc(r,e,t),h=Ac(r,e,t);!isFinite(a)||!isFinite(h)?n=a=h=0:(a=13*n*(a-xp),h=13*n*(h-vp));let l={mode:"luv",l:n,u:a,v:h};return s!==void 0&&(l.alpha=s),l},_p=(r,e,t)=>4*r/(r+15*e+3*t),Ep=(r,e,t)=>9*e/(r+15*e+3*t),Tp=_p(Re.X,Re.Y,Re.Z),bp=Ep(Re.X,Re.Y,Re.Z),Ea=({l:r,u:e,v:t,alpha:s})=>{if(r===void 0&&(r=0),r===0)return{mode:"xyz50",x:0,y:0,z:0};e===void 0&&(e=0),t===void 0&&(t=0);let n=e/(13*r)+Tp,a=t/(13*r)+bp,h=Re.Y*(r<=8?r/lr:Math.pow((r+16)/116,3)),l=h*(9*n)/(4*a),u=h*(12-3*n-20*a)/(4*a),d={mode:"xyz50",x:l,y:h,z:u};return s!==void 0&&(d.alpha=s),d},Ap=r=>Ec(_a($s(r))),Ip=r=>Ns(Ea(Tc(r))),wp={mode:"lchuv",toMode:{luv:Tc,rgb:Ip},fromMode:{rgb:Ap,luv:Ec},channels:["l","c","h","alpha"],parse:["--lchuv"],serialize:"--lchuv",ranges:{l:[0,100],c:[0,176.956],h:[0,360]},interpolate:{h:{use:H,fixup:qt},c:H,l:H,alpha:{use:H,fixup:Ue}},difference:{h:tr},average:{h:Xt}},Lp={...ls,mode:"lrgb",toMode:{rgb:cs},fromMode:{rgb:hs},parse:["srgb-linear"],serialize:"srgb-linear"},Rp={mode:"luv",toMode:{xyz50:Ea,rgb:r=>Ns(Ea(r))},fromMode:{xyz50:_a,rgb:r=>_a($s(r))},channels:["l","u","v","alpha"],parse:["--luv"],serialize:"--luv",ranges:{l:[0,100],u:[-84.936,175.042],v:[-125.882,87.243]},interpolate:{l:H,u:H,v:H,alpha:{use:H,fixup:Ue}}},Ic=({r,g:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.cbrt(.412221469470763*r+.5363325372617348*e+.0514459932675022*t),a=Math.cbrt(.2119034958178252*r+.6806995506452344*e+.1073969535369406*t),h=Math.cbrt(.0883024591900564*r+.2817188391361215*e+.6299787016738222*t),l={mode:"oklab",l:.210454268309314*n+.7936177747023054*a-.0040720430116193*h,a:1.9779985324311684*n-2.42859224204858*a+.450593709617411*h,b:.0259040424655478*n+.7827717124575296*a-.8086757549230774*h};return s!==void 0&&(l.alpha=s),l},hr=r=>{let e=Ic(hs(r));return r.r===r.b&&r.b===r.g&&(e.a=e.b=0),e},Gs=({l:r,a:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.pow(r+.3963377773761749*e+.2158037573099136*t,3),a=Math.pow(r-.1055613458156586*e-.0638541728258133*t,3),h=Math.pow(r-.0894841775298119*e-1.2914855480194092*t,3),l={mode:"lrgb",r:4.076741636075957*n-3.3077115392580616*a+.2309699031821044*h,g:-1.2684379732850317*n+2.6097573492876887*a-.3413193760026573*h,b:-.0041960761386756*n-.7034186179359362*a+1.7076146940746117*h};return s!==void 0&&(l.alpha=s),l},cr=r=>cs(Gs(r));function Ta(r){const s=1.170873786407767;return .5*(s*r-.206+Math.sqrt((s*r-.206)*(s*r-.206)+4*.03*s*r))}function Bn(r){return(r*r+.206*r)/(1.170873786407767*(r+.03))}function Cp(r,e){let t,s,n,a,h,l,u,d;-1.88170328*r-.80936493*e>1?(t=1.19086277,s=1.76576728,n=.59662641,a=.75515197,h=.56771245,l=4.0767416621,u=-3.3077115913,d=.2309699292):1.81444104*r-1.19445276*e>1?(t=.73956515,s=-.45954404,n=.08285427,a=.1254107,h=.14503204,l=-1.2684380046,u=2.6097574011,d=-.3413193965):(t=1.35733652,s=-.00915799,n=-1.1513021,a=-.50559606,h=.00692167,l=-.0041960863,u=-.7034186147,d=1.707614701);let p=t+s*r+n*e+a*r*r+h*r*e,g=.3963377774*r+.2158037573*e,y=-.1055613458*r-.0638541728*e,v=-.0894841775*r-1.291485548*e;{let x=1+p*g,E=1+p*y,o=1+p*v,c=x*x*x,f=E*E*E,m=o*o*o,S=3*g*x*x,T=3*y*E*E,b=3*v*o*o,A=6*g*g*x,I=6*y*y*E,L=6*v*v*o,w=l*c+u*f+d*m,C=l*S+u*T+d*b,k=l*A+u*I+d*L;p=p-w*C/(C*C-.5*w*k)}return p}function ro(r,e){let t=Cp(r,e),s=Gs({l:1,a:t*r,b:t*e}),n=Math.cbrt(1/Math.max(s.r,s.g,s.b)),a=n*t;return[n,a]}function Dp(r,e,t,s,n,a=null){a||(a=ro(r,e));let h;if((t-n)*a[1]-(a[0]-n)*s<=0)h=a[1]*n/(s*a[0]+a[1]*(n-t));else{h=a[1]*(n-1)/(s*(a[0]-1)+a[1]*(n-t));{let l=t-n,u=s,d=.3963377774*r+.2158037573*e,p=-.1055613458*r-.0638541728*e,g=-.0894841775*r-1.291485548*e,y=l+u*d,v=l+u*p,x=l+u*g;{let E=n*(1-h)+h*t,o=h*s,c=E+o*d,f=E+o*p,m=E+o*g,S=c*c*c,T=f*f*f,b=m*m*m,A=3*y*c*c,I=3*v*f*f,L=3*x*m*m,w=6*y*y*c,C=6*v*v*f,k=6*x*x*m,U=4.0767416621*S-3.3077115913*T+.2309699292*b-1,G=4.0767416621*A-3.3077115913*I+.2309699292*L,$=4.0767416621*w-3.3077115913*C+.2309699292*k,z=G/(G*G-.5*U*$),j=-U*z,Y=-1.2684380046*S+2.6097574011*T-.3413193965*b-1,F=-1.2684380046*A+2.6097574011*I-.3413193965*L,O=-1.2684380046*w+2.6097574011*C-.3413193965*k,te=F/(F*F-.5*Y*O),ee=-Y*te,se=-.0041960863*S-.7034186147*T+1.707614701*b-1,he=-.0041960863*A-.7034186147*I+1.707614701*L,W=-.0041960863*w-.7034186147*C+1.707614701*k,me=he/(he*he-.5*se*W),De=-se*me;j=z>=0?j:1e6,ee=te>=0?ee:1e6,De=me>=0?De:1e6,h+=Math.min(j,Math.min(ee,De))}}}return h}function ao(r,e,t=null){t||(t=ro(r,e));let s=t[0],n=t[1];return[n/s,n/(1-s)]}function wc(r,e,t){let s=ro(e,t),n=Dp(e,t,r,1,r,s),a=ao(e,t,s),h=.11516993+1/(7.4477897+4.1590124*t+e*(-2.19557347+1.75198401*t+e*(-2.13704948-10.02301043*t+e*(-4.24894561+5.38770819*t+4.69891013*e)))),l=.11239642+1/(1.6132032-.68124379*t+e*(.40370612+.90148123*t+e*(-.27087943+.6122399*t+e*(.00299215-.45399568*t-.14661872*e)))),u=n/Math.min(r*a[0],(1-r)*a[1]),d=r*h,p=(1-r)*l,g=.9*u*Math.sqrt(Math.sqrt(1/(1/(d*d*d*d)+1/(p*p*p*p))));return d=r*.4,p=(1-r)*.8,[Math.sqrt(1/(1/(d*d)+1/(p*p))),g,n]}function sl(r){const e=r.l!==void 0?r.l:0,t=r.a!==void 0?r.a:0,s=r.b!==void 0?r.b:0,n={mode:"okhsl",l:Ta(e)};r.alpha!==void 0&&(n.alpha=r.alpha);let a=Math.sqrt(t*t+s*s);if(!a)return n.s=0,n;let[h,l,u]=wc(e,t/a,s/a),d;if(a<l){let p=0,g=.8*h,y=1-g/l;d=(a-p)/(g+y*(a-p))*.8}else{let p=l,g=.2*l*l*1.25*1.25/h,y=1-g/(u-l);d=.8+.2*((a-p)/(g+y*(a-p)))}return d&&(n.s=d,n.h=Ge(Math.atan2(s,t)*180/Math.PI)),n}function nl(r){let e=r.h!==void 0?r.h:0,t=r.s!==void 0?r.s:0,s=r.l!==void 0?r.l:0;const n={mode:"oklab",l:Bn(s)};if(r.alpha!==void 0&&(n.alpha=r.alpha),!t||s===1)return n.a=n.b=0,n;let a=Math.cos(e/180*Math.PI),h=Math.sin(e/180*Math.PI),[l,u,d]=wc(n.l,a,h),p,g,y,v;t<.8?(p=1.25*t,g=0,y=.8*l,v=1-y/u):(p=5*(t-.8),g=u,y=.2*u*u*1.25*1.25/l,v=1-y/(d-u));let x=g+p*y/(1-v*p);return n.a=x*a,n.b=x*h,n}const Pp={...cc,mode:"okhsl",channels:["h","s","l","alpha"],parse:["--okhsl"],serialize:"--okhsl",fromMode:{oklab:sl,rgb:r=>sl(hr(r))},toMode:{oklab:nl,rgb:r=>cr(nl(r))}};function rl(r){let e=r.l!==void 0?r.l:0,t=r.a!==void 0?r.a:0,s=r.b!==void 0?r.b:0,n=Math.sqrt(t*t+s*s),a=n?t/n:1,h=n?s/n:1,[l,u]=ao(a,h),d=.5,p=1-d/l,g=u/(n+e*u),y=g*e,v=g*n,x=Bn(y),E=v*x/y,o=Gs({l:x,a:a*E,b:h*E}),c=Math.cbrt(1/Math.max(o.r,o.g,o.b,0));e=e/c,n=n/c*Ta(e)/e,e=Ta(e);const f={mode:"okhsv",s:n?(d+u)*v/(u*d+u*p*v):0,v:e?e/y:0};return f.s&&(f.h=Ge(Math.atan2(s,t)*180/Math.PI)),r.alpha!==void 0&&(f.alpha=r.alpha),f}function al(r){const e={mode:"oklab"};r.alpha!==void 0&&(e.alpha=r.alpha);const t=r.h!==void 0?r.h:0,s=r.s!==void 0?r.s:0,n=r.v!==void 0?r.v:0,a=Math.cos(t/180*Math.PI),h=Math.sin(t/180*Math.PI),[l,u]=ao(a,h),d=.5,p=1-d/l,g=1-s*d/(d+u-u*p*s),y=s*u*d/(d+u-u*p*s),v=Bn(g),x=y*v/g,E=Gs({l:v,a:a*x,b:h*x}),o=Math.cbrt(1/Math.max(E.r,E.g,E.b,0)),c=Bn(n*g),f=y*c/g;return e.l=c*o,e.a=f*a*o,e.b=f*h*o,e}const kp={...fc,mode:"okhsv",channels:["h","s","v","alpha"],parse:["--okhsv"],serialize:"--okhsv",fromMode:{oklab:rl,rgb:r=>rl(hr(r))},toMode:{oklab:al,rgb:r=>cr(al(r))}};function Mp(r,e){if(!e||e[0]!=="oklab")return;const t={mode:"oklab"},[,s,n,a,h]=e;if(!(s.type===B.Hue||n.type===B.Hue||a.type===B.Hue))return s.type!==B.None&&(t.l=Math.min(Math.max(0,s.type===B.Number?s.value:s.value/100),1)),n.type!==B.None&&(t.a=n.type===B.Number?n.value:n.value*.4/100),a.type!==B.None&&(t.b=a.type===B.Number?a.value:a.value*.4/100),h.type!==B.None&&(t.alpha=Math.min(1,Math.max(0,h.type===B.Number?h.value:h.value/100))),t}const Fp={...so,mode:"oklab",toMode:{lrgb:Gs,rgb:cr},fromMode:{lrgb:Ic,rgb:hr},ranges:{l:[0,1],a:[-.4,.4],b:[-.4,.4]},parse:[Mp],serialize:r=>`oklab(${r.l!==void 0?r.l:"none"} ${r.a!==void 0?r.a:"none"} ${r.b!==void 0?r.b:"none"}${r.alpha<1?` / ${r.alpha}`:""})`};function Up(r,e){if(!e||e[0]!=="oklch")return;const t={mode:"oklch"},[,s,n,a,h]=e;if(s.type!==B.None){if(s.type===B.Hue)return;t.l=Math.min(Math.max(0,s.type===B.Number?s.value:s.value/100),1)}if(n.type!==B.None&&(t.c=Math.max(0,n.type===B.Number?n.value:n.value*.4/100)),a.type!==B.None){if(a.type===B.Percentage)return;t.h=a.value}return h.type!==B.None&&(t.alpha=Math.min(1,Math.max(0,h.type===B.Number?h.value:h.value/100))),t}const Op={...no,mode:"oklch",toMode:{oklab:r=>fi(r,"oklab"),rgb:r=>cr(fi(r,"oklab"))},fromMode:{rgb:r=>ui(hr(r),"oklch"),oklab:r=>ui(r,"oklch")},parse:[Up],serialize:r=>`oklch(${r.l!==void 0?r.l:"none"} ${r.c!==void 0?r.c:"none"} ${r.h!==void 0?r.h:"none"}${r.alpha<1?` / ${r.alpha}`:""})`,ranges:{l:[0,1],c:[0,.4],h:[0,360]}},ol=r=>{let{r:e,g:t,b:s,alpha:n}=hs(r),a={mode:"xyz65",x:.486570948648216*e+.265667693169093*t+.1982172852343625*s,y:.2289745640697487*e+.6917385218365062*t+.079286914093745*s,z:0*e+.0451133818589026*t+1.043944368900976*s};return n!==void 0&&(a.alpha=n),a},ll=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=cs({r:r*2.4934969119414263-e*.9313836179191242-.402710784450717*t,g:r*-.8294889695615749+e*1.7626640603183465+.0236246858419436*t,b:r*.0358458302437845-e*.0761723892680418+.9568845240076871*t},"p3");return s!==void 0&&(n.alpha=s),n},Bp={...ls,mode:"p3",parse:["display-p3"],serialize:"display-p3",fromMode:{rgb:r=>ll(Mi(r)),xyz65:ll},toMode:{rgb:r=>Fi(ol(r)),xyz65:ol}},Or=r=>{let e=Math.abs(r);return e>=1/512?Math.sign(r)*Math.pow(e,1/1.8):16*r},hl=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n={mode:"prophoto",r:Or(r*1.3457868816471585-e*.2555720873797946-.0511018649755453*t),g:Or(r*-.5446307051249019+e*1.5082477428451466+.0205274474364214*t),b:Or(r*0+e*0+1.2119675456389452*t)};return s!==void 0&&(n.alpha=s),n},Br=(r=0)=>{let e=Math.abs(r);return e>=16/512?Math.sign(r)*Math.pow(e,1.8):r/16},cl=r=>{let e=Br(r.r),t=Br(r.g),s=Br(r.b),n={mode:"xyz50",x:.7977666449006423*e+.1351812974005331*t+.0313477341283922*s,y:.2880748288194013*e+.7118352342418731*t+899369387256e-16*s,z:0*e+0*t+.8251046025104602*s};return r.alpha!==void 0&&(n.alpha=r.alpha),n},Np={...ls,mode:"prophoto",parse:["prophoto-rgb"],serialize:"prophoto-rgb",fromMode:{xyz50:hl,rgb:r=>hl($s(r))},toMode:{xyz50:cl,rgb:r=>Ns(cl(r))}},dl=1.09929682680944,$p=.018053968510807,Nr=r=>{const e=Math.abs(r);return e>$p?(Math.sign(r)||1)*(dl*Math.pow(e,.45)-(dl-1)):4.5*r},ul=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n={mode:"rec2020",r:Nr(r*1.7166511879712683-e*.3556707837763925-.2533662813736599*t),g:Nr(r*-.6666843518324893+e*1.6164812366349395+.0157685458139111*t),b:Nr(r*.0176398574453108-e*.0427706132578085+.9421031212354739*t)};return s!==void 0&&(n.alpha=s),n},fl=1.09929682680944,Gp=.018053968510807,$r=(r=0)=>{let e=Math.abs(r);return e<Gp*4.5?r/4.5:(Math.sign(r)||1)*Math.pow((e+fl-1)/fl,1/.45)},pl=r=>{let e=$r(r.r),t=$r(r.g),s=$r(r.b),n={mode:"xyz65",x:.6369580483012911*e+.1446169035862083*t+.1688809751641721*s,y:.262700212011267*e+.6779980715188708*t+.059301716469862*s,z:0*e+.0280726930490874*t+1.0609850577107909*s};return r.alpha!==void 0&&(n.alpha=r.alpha),n},zp={...ls,mode:"rec2020",fromMode:{xyz65:ul,rgb:r=>ul(Mi(r))},toMode:{xyz65:pl,rgb:r=>Fi(pl(r))},parse:["rec2020"],serialize:"rec2020"},Ri=.0037930732552754493,Lc=Math.cbrt(Ri),Gr=r=>Math.cbrt(r)-Lc,Hp=r=>{const{r:e,g:t,b:s,alpha:n}=hs(r),a=Gr(.3*e+.622*t+.078*s+Ri),h=Gr(.23*e+.692*t+.078*s+Ri),l=Gr(.2434226892454782*e+.2047674442449682*t+.5518098665095535*s+Ri),u={mode:"xyb",x:(a-h)/2,y:(a+h)/2,b:l-(a+h)/2};return n!==void 0&&(u.alpha=n),u},zr=r=>Math.pow(r+Lc,3),Vp=({x:r,y:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);const n=zr(r+e)-Ri,a=zr(e-r)-Ri,h=zr(t+e)-Ri,l=cs({r:11.031566904639861*n-9.866943908131562*a-.16462299650829934*h,g:-3.2541473810744237*n+4.418770377582723*a-.16462299650829934*h,b:-3.6588512867136815*n+2.7129230459360922*a+1.9459282407775895*h});return s!==void 0&&(l.alpha=s),l},Kp={mode:"xyb",channels:["x","y","b","alpha"],parse:["--xyb"],serialize:"--xyb",toMode:{rgb:Vp},fromMode:{rgb:Hp},ranges:{x:[-.0154,.0281],y:[0,.8453],b:[-.2778,.388]},interpolate:{x:H,y:H,b:H,alpha:{use:H,fixup:Ue}}},Yp={mode:"xyz50",parse:["xyz-d50"],serialize:"xyz-d50",toMode:{rgb:Ns,lab:io},fromMode:{rgb:$s,lab:to},channels:["x","y","z","alpha"],ranges:{x:[0,.964],y:[0,.999],z:[0,.825]},interpolate:{x:H,y:H,z:H,alpha:{use:H,fixup:Ue}}},Wp=r=>{let{x:e,y:t,z:s,alpha:n}=r;e===void 0&&(e=0),t===void 0&&(t=0),s===void 0&&(s=0);let a={mode:"xyz50",x:1.0479298208405488*e+.0229467933410191*t-.0501922295431356*s,y:.0296278156881593*e+.990434484573249*t-.0170738250293851*s,z:-.0092430581525912*e+.0150551448965779*t+.7518742899580008*s};return n!==void 0&&(a.alpha=n),a},jp=r=>{let{x:e,y:t,z:s,alpha:n}=r;e===void 0&&(e=0),t===void 0&&(t=0),s===void 0&&(s=0);let a={mode:"xyz65",x:.9554734527042182*e-.0230985368742614*t+.0632593086610217*s,y:-.0283697069632081*e+1.0099954580058226*t+.021041398966943*s,z:.0123140016883199*e-.0205076964334779*t+1.3303659366080753*s};return n!==void 0&&(a.alpha=n),a},qp={mode:"xyz65",toMode:{rgb:Fi,xyz50:Wp},fromMode:{rgb:Mi,xyz50:jp},ranges:{x:[0,.95],y:[0,1],z:[0,1.088]},channels:["x","y","z","alpha"],parse:["xyz","xyz-d65"],serialize:"xyz-d65",interpolate:{x:H,y:H,z:H,alpha:{use:H,fixup:Ue}}},Xp=({r,g:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);const n={mode:"yiq",y:.29889531*r+.58662247*e+.11448223*t,i:.59597799*r-.2741761*e-.32180189*t,q:.21147017*r-.52261711*e+.31114694*t};return s!==void 0&&(n.alpha=s),n},Qp=({y:r,i:e,q:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);const n={mode:"rgb",r:r+.95608445*e+.6208885*t,g:r-.27137664*e-.6486059*t,b:r-1.10561724*e+1.70250126*t};return s!==void 0&&(n.alpha=s),n},Zp={mode:"yiq",toMode:{rgb:Qp},fromMode:{rgb:Xp},channels:["y","i","q","alpha"],parse:["--yiq"],serialize:"--yiq",ranges:{i:[-.595,.595],q:[-.522,.522]},interpolate:{y:H,i:H,q:H,alpha:{use:H,fixup:Ue}}},Jp=r=>Math.max(0,Math.min(1,r||0)),yn=r=>Math.round(Jp(r)*255),eg=Rs("rgb"),tg=r=>{if(r===void 0)return;let e=yn(r.r),t=yn(r.g),s=yn(r.b);return"#"+(1<<24|e<<16|t<<8|s).toString(16).slice(1)},ig=r=>{if(r===void 0)return;let e=yn(r.alpha!==void 0?r.alpha:1);return tg(r)+(256|e).toString(16).slice(1)},sg=r=>ig(eg(r)),ng=r=>{r[0]===void 0&&(r[0]=0),r[r.length-1]===void 0&&(r[r.length-1]=1);let e=1,t,s,n,a;for(;e<r.length;){if(r[e]===void 0){for(s=e,n=r[e-1],t=e;r[t]===void 0;)t++;for(a=(r[t]-n)/(t-e+1);e<t;)r[e]=n+(e+1-s)*a,e++}else r[e]<r[e-1]&&(r[e]=r[e-1]);e++}return r},rg=(r=.5)=>e=>r<=0?1:r>=1?0:Math.pow(e,Math.log(.5)/Math.log(r)),Js=r=>typeof r=="function",Ei=r=>r&&typeof r=="object",gl=r=>typeof r=="number",ag=(r,e="rgb",t,s)=>{let n=tc(e),a=Rs(e),h=[],l=[],u={};r.forEach(y=>{Array.isArray(y)?(h.push(a(y[0])),l.push(y[1])):gl(y)||Js(y)?u[l.length]=y:(h.push(a(y)),l.push(void 0))}),ng(l);let d=n.channels.reduce((y,v)=>{let x;return Ei(t)&&Ei(t[v])&&t[v].fixup?x=t[v].fixup:Ei(n.interpolate[v])&&n.interpolate[v].fixup?x=n.interpolate[v].fixup:x=E=>E,y[v]=x(h.map(E=>E[v])),y},{}),p=n.channels.reduce((y,v)=>{let x;return Js(t)?x=t:Ei(t)&&Js(t[v])?x=t[v]:Ei(t)&&Ei(t[v])&&t[v].use?x=t[v].use:Js(n.interpolate[v])?x=n.interpolate[v]:Ei(n.interpolate[v])&&(x=n.interpolate[v].use),y[v]=x(d[v]),y},{}),g=h.length-1;return y=>{if(y=Math.min(Math.max(0,y),1),y<=l[0])return h[0];if(y>l[g])return h[g];let v=0;for(;l[v]<y;)v++;let x=l[v-1],E=l[v]-x,o=(y-x)/E,c=u[v]||u[0];c!==void 0&&(gl(c)&&(c=rg((c-x)/E)),o=c(o));let f=(v-1+o)/g;return n.channels.reduce((m,S)=>{let T=p[S](f);return T!==void 0&&(m[S]=T),m},{mode:e})}},og=(r,e="rgb",t)=>ag(r,e,t);Se(Nf);Se(Yf);Se(Wf);Se(jf);Se(Qf);Se(cc);Se(fc);Se(op);Se(lp);Se(up);Se(fp);Se(so);Se(gp);Se(no);Se(yp);Se(wp);Se(Lp);Se(Rp);Se(Pp);Se(kp);Se(Fp);Se(Op);Se(Bp);Se(Np);Se(zp);Se(ls);Se(Kp);Se(Yp);Se(qp);Se(Zp);function lg(r){const e=r>>16&255,t=r>>8&255,s=r&255;return[e/255,t/255,s/255,1]}class Le{constructor(e){if(this.symbol=Le.symbol,e==null){this.r=0,this.g=0,this.b=0,this.a=1;return}if(e instanceof Le){this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a;return}if(typeof e=="string"){const t=sc(e);if(!t)throw new Error(`Invalid color string value provided: ${e}`);const s=t.mode==="rgb"?t:Rs("rgb")(t);if(s){this.r=ye(0,1,s.r),this.g=ye(0,1,s.g),this.b=ye(0,1,s.b),this.a=ye(0,1,s.alpha??1);return}}if(typeof e=="number"){const[t,s,n,a]=lg(e);this.r=ye(0,1,t),this.g=ye(0,1,s),this.b=ye(0,1,n),this.a=ye(0,1,a);return}if(typeof e=="object"&&"r"in e&&"g"in e&&"b"in e){const t=e;this.r=ye(0,1,t.r/255),this.g=ye(0,1,t.g/255),this.b=ye(0,1,t.b/255),this.a=ye(0,1,t.a??1);return}throw new Error(`Invalid color value provided: ${e}`)}static lerp(e,t,s,n="lch"){const a=e instanceof Le?e:new Le(e??void 0),h=t instanceof Le?t:new Le(t??void 0),l={mode:"rgb",r:a.r,g:a.g,b:a.b},u={mode:"rgb",r:h.r,g:h.g,b:h.b},g=og([l,u],n??"lch")(s),v=Rs("rgb")(g),x=a.a+(h.a-a.a)*s,E=v?ye(0,1,v.r):0,o=v?ye(0,1,v.g):0,c=v?ye(0,1,v.b):0;return new Le({r:E*255,g:o*255,b:c*255,a:ye(0,1,x)})}static createLerp(e="lch"){return(t,s,n)=>Le.lerp(t,s,n,e)}static createSignal(e,t=Le.lerp){return new Di(e,t,void 0,s=>s instanceof Le?s:new Le(s)).toSignal()}toSymbol(){return this.symbol}gl(){return[this.r,this.g,this.b,this.a]}toUniform(e,t){e.uniform4fv(t,this.gl())}serialize(){const e=Math.round(this.r*255),t=Math.round(this.g*255),s=Math.round(this.b*255),n=ye(0,1,this.a).toFixed(3);return`rgba(${e}, ${t}, ${s}, ${n})`}css(){const e=Math.round(this.r*255),t=Math.round(this.g*255),s=Math.round(this.b*255);return`rgb(${e},${t},${s})`}alpha(){return this.a}hex(){return sg({mode:"rgb",r:this.r,g:this.g,b:this.b,alpha:this.a})}lerp(e,t,s="lch"){return Le.lerp(this,e,t,s)}}Le.symbol=Symbol.for("@twick/core/types/Color");function hg(r,e){const t=R.fromDegrees(r);return Vt(t,e).degrees}function ba(r,e){return R.magnitude(e.m11,e.m12)*r}function cg(r){if(r===Ze.Middle)return R.zero;let e=0;r&At.Left?e=-1:r&At.Right&&(e=1);let t=0;return r&At.Top?t=-1:r&At.Bottom&&(t=1),new R(e,t)}function dg(r){return{core:r,two:r,ui:r,vitePlugin:r}}const en={shared:{background:"FFFFFF00",range:[0,1/0],size:{x:1920,y:1080}},rendering:{exporter:{name:"@twick/core/wasm"},fps:30,resolutionScale:1,colorSpace:"srgb"},preview:{fps:30,resolutionScale:1}};function ug(r){var s,n,a;const e={...en,...r.settings,shared:{...en.shared,...(s=r.settings)==null?void 0:s.shared},rendering:{...en.rendering,...(n=r.settings)==null?void 0:n.rendering},preview:{...en.preview,...(a=r.settings)==null?void 0:a.preview}},t={...e,shared:{...e.shared,background:new Le(e.shared.background),size:new R(e.shared.size)}};return{...r,name:r.name??"project",settings:t,plugins:[],logger:new _u,versions:dg("0.10.4")}}var xt;(function(r){r[r.Playing=0]="Playing",r[r.Rendering=1]="Rendering",r[r.Paused=2]="Paused",r[r.Presenting=3]="Presenting"})(xt||(xt={}));function fg(r){return r&&(typeof r=="object"||typeof r=="function")&&"toPromise"in r}function Rc(r){return r!==null&&typeof r=="object"&&Symbol.iterator in r&&"next"in r}const pg=`
|
|
14
|
+
`;function ef(r,e){return{level:Tt.Error,message:r,remarks:""+Ju}}const tf=180/Math.PI,pi=Math.PI/180,co=[];function ac(){const r=co.at(-1);if(!r)throw new Error("The playback is not available in the current context.");return r}function sf(r){co.push(r)}function nf(r){if(co.pop()!==r)throw new Error("startPlayback/endPlayback were called out of order.")}function oc(r,e,t){if(e.length>=r.length){const s=Math.floor(e.length*t),n=Math.floor(se(r.length-1,e.length,t));let a="";for(let h=0;h<e.length;h++)h<s?a+=e[h]:(r[h]||h<=n)&&(a+=r[h]??e[h]);return a}else{const s=Math.round(r.length*(1-t)),n=Math.floor(se(r.length+1,e.length,t)),a=[];for(let h=r.length-1;h>=0;h--)h<s?a.unshift(r[h]):(e[h]||h<n)&&a.unshift(e[h]??r[h]);return a.join("")}}function us(r,e,t,s=!1){if(t===0)return r;if(t===1)return e;if(r==null||e==null){s||Ue().warn(`Attempting to lerp ${r} -> ${e} may result in unexpected behavior.`);return}if(typeof r=="number"&&typeof e=="number")return se(r,e,t);if(typeof r=="string"&&typeof e=="string")return oc(r,e,t);if(typeof r=="boolean"&&typeof e=="boolean")return t<.5?r:e;if("lerp"in r)return r.lerp(e,t);if(r&&e&&typeof r=="object"&&typeof e=="object")if(Array.isArray(r)&&Array.isArray(e)){if(r.length===e.length)return r.map((n,a)=>us(n,e[a],t))}else{let n=!1;if(!(r instanceof Map)&&!(e instanceof Map)&&(n=!0,r=new Map(Object.entries(r)),e=new Map(Object.entries(e))),r instanceof Map&&e instanceof Map){const a=new Map;for(const h of new Set([...r.keys(),...e.keys()])){const l=us(r.get(h),e.get(h),t,!0);l!==void 0&&a.set(h,l)}return n?Object.fromEntries(a):a}}return e}function rf(r,e,t){return t<.5?r:e}function lc(r,e,t){let s=e;t>1?t=1/t:s=!s;const n=s?Math.acos(me(-1,1,1-r)):Math.asin(r),a=se(n,se(0,Math.PI/2,r),t);let h=Math.sin(a),l=1-Math.cos(a);return e&&([h,l]=[l,h]),{x:h,y:l}}function Ei(r,...e){const t={[r.name]:r},s=Object.getOwnPropertyDescriptor(t,r.name);if(s)for(let n=e.length-1;n>=0;n--)e[n](t,r.name,s)}const il=Symbol.for("@twick/core/decorators/UNINITIALIZED");function hr(r){return(e,t)=>{let s=il;Object.defineProperty(e,t,{get(){return s===il&&(s=r.call(this)),s}})}}function rt(r){return function(e,t,s){s.value.prototype.name=r??t,s.value.prototype.threadable=!0}}function af(r,e=0,t=1){return r=1-Math.cos(r*Math.PI/2),se(e,t,r)}function of(r,e=0,t=1){return r=Math.sin(r*Math.PI/2),se(e,t,r)}function lf(r,e=0,t=1){return r=-(Math.cos(Math.PI*r)-1)/2,se(e,t,r)}function hf(r,e=0,t=1){return r=r*r,se(e,t,r)}function cf(r,e=0,t=1){return r=1-Math.pow(1-r,2),se(e,t,r)}function df(r,e=0,t=1){return r=r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2,se(e,t,r)}function uf(r,e=0,t=1){return r=r*r*r,se(e,t,r)}function ff(r,e=0,t=1){return r=1-Math.pow(1-r,3),se(e,t,r)}function Bs(r,e=0,t=1){return r=r<.5?4*r*r*r:1-Math.pow(-2*r+2,3)/2,se(e,t,r)}function pf(r,e=0,t=1){return r=r*r*r*r,se(e,t,r)}function gf(r,e=0,t=1){return r=1-Math.pow(1-r,4),se(e,t,r)}function mf(r,e=0,t=1){return r=r<.5?8*r*r*r*r:1-Math.pow(-2*r+2,4)/2,se(e,t,r)}function yf(r,e=0,t=1){return r=r*r*r*r*r,se(e,t,r)}function vf(r,e=0,t=1){return r=1-Math.pow(1-r,5),se(e,t,r)}function xf(r,e=0,t=1){return r=r<.5?16*r*r*r*r*r:1-Math.pow(-2*r+2,5)/2,se(e,t,r)}function Sf(r,e=0,t=1){return r=r===0?0:Math.pow(2,10*r-10),se(e,t,r)}function hc(r,e=0,t=1){return r=r===1?1:1-Math.pow(2,-10*r),se(e,t,r)}function _f(r,e=0,t=1){return r=r===0?0:r===1?1:r<.5?Math.pow(2,20*r-10)/2:(2-Math.pow(2,-20*r+10))/2,se(e,t,r)}function Ef(r,e=0,t=1){return r=1-Math.sqrt(1-Math.pow(r,2)),se(e,t,r)}function Tf(r,e=0,t=1){return r=Math.sqrt(1-Math.pow(r-1,2)),se(e,t,r)}function bf(r,e=0,t=1){return r=r<.5?(1-Math.sqrt(1-Math.pow(2*r,2)))/2:(Math.sqrt(1-Math.pow(-2*r+2,2))+1)/2,se(e,t,r)}function Af(r=1.70158){return(e,t=0,s=1)=>(e=(r+1)*e*e*e-r*e*e,se(t,s,e))}function If(r=1.70158){return(e,t=0,s=1)=>(e=1+(r+1)*Math.pow(e-1,3)+r*Math.pow(e-1,2),se(t,s,e))}function wf(r=1.70158,e=1.525){return(t,s=0,n=1)=>(t=t<.5?Math.pow(2*t,2)*((r*e+1)*2*t-r*e)/2:(Math.pow(2*t-2,2)*((r*e+1)*(t*2-2)+r*e)+2)/2,se(s,n,t))}function Lf(r=2.094395){return(e,t=0,s=1)=>(e=e===0?0:e===1?1:-Math.pow(2,10*e-10)*Math.sin((e*10-10.75)*r),se(t,s,e))}function Rf(r=2.094395){return(e,t=0,s=1)=>(e=e===0?0:e===1?1:Math.pow(2,-10*e)*Math.sin((e*10-.75)*r)+1,se(t,s,e))}function Cf(r=1.39626){return(e,t=0,s=1)=>(e=e===0?0:e===1?1:e<.5?-(Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*r))/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*r)/2+1,se(t,s,e))}function Pf(r=7.5625,e=2.75){const t=uo(r,e);return(s,n=0,a=1)=>1-t(1-s,n,a)}function uo(r=7.5625,e=2.75){return(t,s=0,n=1)=>(t<1/e?t=r*t*t:t<2/e?t=r*(t-=1.505/e)*t+.75:t<2.5/e?t=r*(t-=2.25/e)*t+.9375:t=r*(t-=2.625/e)*t+.984375,se(s,n,t))}function Df(r=7.5625,e=2.75){const t=uo(r,e);return(s,n=0,a=1)=>s<.5?(1-t(1-2*s,n,a))/2:(1+t(2*s-1,n,a))/2}function cc(r,e=0,t=1){return se(e,t,r)}const kf=Af(),Mf=If(),Ff=wf(),Uf=Pf(),Of=uo(),Bf=Df(),Nf=Lf(),dc=Rf(),$f=Cf();Ei(Ps,rt());function*Ps(r,e,t){const s=Os(),n=s.time(),a=s.time()+r;for(e(0,0);a>s.fixed;){const h=s.fixed-n,l=h/r;h>0&&e(l,h),yield}s.time(a),e(1,r),t==null||t(1,r)}var kt;(function(r){r[r.Top=4]="Top",r[r.Bottom=8]="Bottom",r[r.Left=16]="Left",r[r.Right=32]="Right"})(kt||(kt={}));var sl;(function(r){r[r.Vertical=1]="Vertical",r[r.Horizontal=2]="Horizontal"})(sl||(sl={}));var st;(function(r){r[r.Middle=3]="Middle",r[r.Top=5]="Top",r[r.Bottom=9]="Bottom",r[r.Left=18]="Left",r[r.Right=34]="Right",r[r.TopLeft=20]="TopLeft",r[r.TopRight=36]="TopRight",r[r.BottomLeft=24]="BottomLeft",r[r.BottomRight=40]="BottomRight"})(st||(st={}));Ei(uc,rt());function*uc(r,...e){let t=!0;typeof r=="boolean"?t=r:e.push(r);const s=Os(),n=e.map(l=>s.children.find(u=>u.runner===l)).filter(l=>l),a=s.time();let h;if(t){for(;n.find(l=>!l.canceled);)yield;h=Math.max(...n.map(l=>l.time()))}else{for(;!n.find(u=>u.canceled);)yield;const l=n.filter(u=>u.canceled);h=Math.min(...l.map(u=>u.time()))}s.time(Math.max(a,h))}Ei(Se,rt());function*Se(...r){for(const e of r)yield e;yield*uc(...r)}Ei(oe,rt());function*oe(r=0,e){const t=Os(),s=ac().framesToSeconds(1),n=t.time()+r;for(;n-s>t.fixed;)yield;t.time(n),e&&(yield*e)}Ei(Fi,rt());function*Fi(r,e){yield*oe(r),"next"in e?yield*e:e()}function Hn(r,e){const t=Object.getPrototypeOf(r);t.threadable||(t.threadable=!0,t.name=typeof e=="string"?e:fc(e))}function fc(r){return Object.getPrototypeOf(r).name??null}function nl(r,e){let t;return typeof r=="string"?(t=e(),Hn(t,r)):(t=r(),Hn(t,t)),t}class ye{static collectPromise(e,t=null){const s={promise:e,value:t,stack:new Error().stack},n=this.collectionStack.at(-1);return n&&(s.owner=n.owner),e.then(a=>{s.value=a,n==null||n.markDirty()}),this.promises.push(s),s}static hasPromises(){return this.promises.length>0}static async consumePromises(){const e=[...this.promises];return await Promise.all(e.map(t=>t.promise)),this.promises=this.promises.filter(t=>!e.includes(t)),e}constructor(e){this.owner=e,this.dependencies=new Set,this.event=new Ku,this.markDirty=()=>this.event.raise(),this.invokable=this.invoke.bind(this),Object.defineProperty(this.invokable,"context",{value:this}),Object.defineProperty(this.invokable,"toPromise",{value:this.toPromise.bind(this)})}invoke(){}startCollecting(){if(ye.collectionSet.has(this))throw new lo("A circular dependency occurred between signals.",`This can happen when signals reference each other in a loop.
|
|
15
|
+
Try using the attached stack trace to locate said loop.`);ye.collectionSet.add(this),ye.collectionStack.push(this)}finishCollecting(){if(ye.collectionSet.delete(this),ye.collectionStack.pop()!==this)throw new Error("collectStart/collectEnd was called out of order.")}clearDependencies(){this.dependencies.forEach(e=>e.unsubscribe(this.markDirty)),this.dependencies.clear()}collect(){const e=ye.collectionStack.at(-1);e&&(e.dependencies.add(this.event.subscribable),this.event.subscribe(e.markDirty))}dispose(){this.clearDependencies(),this.event.clear(),this.owner=null}async toPromise(){do await ye.consumePromises(),this.invokable();while(ye.hasPromises());return this.invokable}}ye.collectionSet=new Set;ye.collectionStack=[];ye.promises=[];const La=Symbol.for("@twick/core/signals/default");function Bt(r){return typeof r=="function"}function rs(r,e){return Bt(r)?()=>e(r()):e(r)}function fs(r){return Bt(r)?r():r}class $i extends ye{constructor(e,t,s=void 0,n=h=>h,a={}){super(s),this.initial=e,this.interpolation=t,this.parser=n,this.tweening=!1,Object.defineProperty(this.invokable,"reset",{value:this.reset.bind(this)}),Object.defineProperty(this.invokable,"save",{value:this.save.bind(this)}),Object.defineProperty(this.invokable,"isInitial",{value:this.isInitial.bind(this)}),this.initial!==void 0&&(this.current=this.initial,this.markDirty(),Bt(this.initial)||(this.last=this.parse(this.initial))),this.extensions={getter:this.getter.bind(this),setter:this.setter.bind(this),tweener:this.tweener.bind(this),...a}}toSignal(){return this.invokable}parse(e){return this.parser(e)}set(e){return this.extensions.setter(e),this.owner}setter(e){return e===La&&(e=this.initial),this.current===e?this.owner:(this.current=e,this.markDirty(),this.clearDependencies(),Bt(e)||(this.last=this.parse(e)),this.owner)}get(){return this.extensions.getter()}getter(){var e;if(this.event.isRaised()&&Bt(this.current)){this.clearDependencies(),this.startCollecting();try{this.last=this.parse(this.current())}catch(t){Ue().error({...rc(t),inspect:(e=this.owner)==null?void 0:e.key})}this.finishCollecting()}return this.event.reset(),this.collect(),this.last}invoke(e,t,s=Bs,n=this.interpolation){return e===void 0?this.get():t===void 0?this.set(e):this.createQueue(s,n).to(e,t)}createQueue(e,t){const s=this.get(),n=[],a=nl("animation chain",function*(){for(;n.length>0;)yield*n.shift()});return a.to=(h,l,u=e,d=t)=>(e=u,t=d,n.push(this.tween(h,l,u,d)),a),a.back=(h,l=e,u=t)=>(e=l,t=u,n.push(this.tween(s,h,e,t)),a),a.wait=h=>(n.push(oe(h)),a),a.run=h=>(n.push(h),a),a.do=h=>(n.push(nl(function*(){h()})),a),a}*tween(e,t,s,n){e===La&&(e=this.initial),this.tweening=!0,yield*this.extensions.tweener(e,t,s,n),this.set(e),this.tweening=!1}*tweener(e,t,s,n){const a=this.get();yield*Ps(t,h=>{this.set(n(a,this.parse(fs(e)),s(h)))})}dispose(){super.dispose(),this.initial=void 0,this.current=void 0,this.last=void 0}reset(){return this.initial!==void 0&&this.set(this.initial),this.owner}save(){return this.set(this.get())}isInitial(){return this.collect(),this.current===this.initial}getInitial(){return this.initial}raw(){return this.current}isTweening(){return this.tweening}}class cr extends $i{constructor(e,t,s,n,a=void 0,h={}){var l;super(void 0,n,a,t,h),this.entries=e,this.signals=[],this.parser=t;for(const u of e){let d,p;Array.isArray(u)?([d,p]=u,(l=p.context).owner??(l.owner=this)):(d=u,p=new $i(rs(s,g=>t(g)[u]),se,a??this.invokable).toSignal()),this.signals.push([d,p]),Object.defineProperty(this.invokable,d,{value:p})}}toSignal(){return this.invokable}parse(e){return this.parser(e)}getter(){return this.parse(Object.fromEntries(this.signals.map(([e,t])=>[e,t()])))}setter(e){if(Bt(e))for(const[t,s]of this.signals)s(()=>this.parser(e())[t]);else{const t=this.parse(e);for(const[s,n]of this.signals)n(t[s])}return this.owner}reset(){for(const[,e]of this.signals)e.reset();return this.owner}save(){for(const[,e]of this.signals)e.save();return this.owner}isInitial(){for(const[,e]of this.signals)if(!e.isInitial())return!1;return!0}raw(){return Object.fromEntries(this.signals.map(([e,t])=>[e,t.context.raw()]))}}class Gf extends ye{constructor(e,t){super(t),this.factory=e,this.markDirty()}toSignal(){return this.invokable}dispose(){super.dispose(),this.last=void 0}invoke(...e){var t;if(this.event.isRaised()){this.clearDependencies(),this.startCollecting();try{this.last=this.factory(...e)}catch(s){Ue().error({...rc(s),inspect:(t=this.owner)==null?void 0:t.key})}this.finishCollecting()}return this.event.reset(),this.collect(),this.last}}function zf(r,e){return new Gf(r,e).toSignal()}function ps(r,e=us,t){return new $i(r,e,t).toSignal()}class bt{static createSignal(e,t=bt.lerp){return new cr(["top","right","bottom","left"],s=>new bt(s),e,t).toSignal()}static lerp(e,t,s){return new bt(se(e.top,t.top,s),se(e.right,t.right,s),se(e.bottom,t.bottom,s),se(e.left,t.left,s))}get x(){return this.left+this.right}get y(){return this.top+this.bottom}constructor(e=0,t,s,n){if(this.top=0,this.right=0,this.bottom=0,this.left=0,e!=null){if(Array.isArray(e)&&(n=e[3],s=e[2],t=e[1],e=e[0]),typeof e=="number"){this.top=e,this.right=t!==void 0?t:e,this.bottom=s!==void 0?s:e,this.left=n!==void 0?n:t!==void 0?t:e;return}this.top=e.top,this.right=e.right,this.bottom=e.bottom,this.left=e.left}}lerp(e,t){return bt.lerp(this,e,t)}scale(e){return new bt(this.top*e,this.right*e,this.bottom*e,this.left*e)}addScalar(e){return new bt(this.top+e,this.right+e,this.bottom+e,this.left+e)}toSymbol(){return bt.symbol}toString(){return`Spacing(${this.top}, ${this.right}, ${this.bottom}, ${this.left})`}toUniform(e,t){e.uniform4f(t,this.top,this.right,this.bottom,this.left)}serialize(){return{top:this.top,right:this.right,bottom:this.bottom,left:this.left}}}bt.symbol=Symbol.for("@twick/core/types/Spacing");const pc=1e-6;class C{static createSignal(e,t=C.lerp,s){return new cr(["x","y"],n=>new C(n),e,t,s).toSignal()}static lerp(e,t,s){let n,a;return typeof s=="number"?n=a=s:(n=s.x,a=s.y),new C(se(e.x,t.x,n),se(e.y,t.y,a))}static arcLerp(e,t,s,n=!1,a){return a??(a=e.sub(t).ctg),C.lerp(e,t,new C(lc(s,n,a)))}static createArcLerp(e,t){return(s,n,a)=>C.arcLerp(s,n,a,e,t)}static polarLerp(e,t,s,n=!1,a=C.zero){e=e.sub(a),t=t.sub(a);const h=e.degrees;let l=t.degrees;h>l!==n&&(l=l+(n?-360:360));const d=se(h,l,s)*pi,p=se(e.magnitude,t.magnitude,s);return new C(p*Math.cos(d)+a.x,p*Math.sin(d)+a.y)}static createPolarLerp(e=!1,t=C.zero){return(s,n,a)=>C.polarLerp(s,n,a,e,new C(t))}static fromOrigin(e){const t=new C;return e===st.Middle||(e&kt.Left?t.x=-1:e&kt.Right&&(t.x=1),e&kt.Top?t.y=-1:e&kt.Bottom&&(t.y=1)),t}static fromScalar(e){return new C(e,e)}static fromRadians(e){return new C(Math.cos(e),Math.sin(e))}static fromDegrees(e){return C.fromRadians(e*pi)}static radians(e,t){return Math.atan2(t,e)}static degrees(e,t){return C.radians(e,t)*tf}static magnitude(e,t){return Math.sqrt(e*e+t*t)}static squaredMagnitude(e,t){return e*e+t*t}static angleBetween(e,t){return Math.acos(me(-1,1,e.dot(t)/(e.magnitude*t.magnitude)))*(e.cross(t)>=0?1:-1)}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}get magnitude(){return C.magnitude(this.x,this.y)}get squaredMagnitude(){return C.squaredMagnitude(this.x,this.y)}get normalized(){return this.scale(1/C.magnitude(this.x,this.y))}get safe(){return new C(isNaN(this.x)?0:this.x,isNaN(this.y)?0:this.y)}get flipped(){return new C(-this.x,-this.y)}get floored(){return new C(Math.floor(this.x),Math.floor(this.y))}get perpendicular(){return new C(this.y,-this.x)}get radians(){return C.radians(this.x,this.y)}get degrees(){return C.degrees(this.x,this.y)}get ctg(){return this.x/this.y}constructor(e,t){if(this.x=0,this.y=0,e!=null){if(typeof e!="object"){this.x=e,this.y=t??e;return}if(Array.isArray(e)){this.x=e[0],this.y=e[1];return}if("width"in e){this.x=e.width,this.y=e.height;return}this.x=e.x,this.y=e.y}}lerp(e,t){return C.lerp(this,e,t)}getOriginOffset(e){const t=C.fromOrigin(e);return t.x*=this.x/2,t.y*=this.y/2,t}scale(e){return new C(this.x*e,this.y*e)}mul(e){const t=new C(e);return new C(this.x*t.x,this.y*t.y)}div(e){const t=new C(e);return new C(this.x/t.x,this.y/t.y)}add(e){const t=new C(e);return new C(this.x+t.x,this.y+t.y)}sub(e){const t=new C(e);return new C(this.x-t.x,this.y-t.y)}dot(e){const t=new C(e);return this.x*t.x+this.y*t.y}cross(e){const t=new C(e);return this.x*t.y-this.y*t.x}mod(e){const t=new C(e);return new C(this.x%t.x,this.y%t.y)}addX(e){return new C(this.x+e,this.y)}addY(e){return new C(this.x,this.y+e)}toSymbol(){return C.symbol}toString(){return`Vector2(${this.x}, ${this.y})`}toUniform(e,t){e.uniform2f(t,this.x,this.y)}serialize(){return{x:this.x,y:this.y}}exactlyEquals(e){return this.x===e.x&&this.y===e.y}equals(e,t=pc){return Math.abs(this.x-e.x)<=t+Number.EPSILON&&Math.abs(this.y-e.y)<=t+Number.EPSILON}}C.symbol=Symbol.for("@twick/core/types/Vector2");C.zero=new C;C.one=new C(1,1);C.right=new C(1,0);C.left=new C(-1,0);C.up=new C(0,1);C.down=new C(0,-1);C.top=new C(0,-1);C.bottom=new C(0,1);C.topLeft=new C(-1,-1);C.topRight=new C(1,-1);C.bottomLeft=new C(-1,1);C.bottomRight=new C(1,1);class Ie{static fromRotation(e){return Ie.identity.rotate(e)}static fromTranslation(e){return Ie.identity.translate(new C(e))}static fromScaling(e){return Ie.identity.scale(new C(e))}get x(){return new C(this.values[0],this.values[1])}get y(){return new C(this.values[2],this.values[3])}get scaleX(){return this.values[0]}set scaleX(e){this.values[0]=this.x.normalized.scale(e).x}get skewX(){return this.values[1]}set skewX(e){this.values[1]=e}get scaleY(){return this.values[3]}set scaleY(e){this.values[3]=this.y.normalized.scale(e).y}get skewY(){return this.values[2]}set skewY(e){this.values[2]=e}get translateX(){return this.values[4]}set translateX(e){this.values[4]=e}get translateY(){return this.values[5]}set translateY(e){this.values[5]=e}get rotation(){return C.degrees(this.values[0],this.values[1])}set rotation(e){const t=this.rotate(e-this.rotation);this.values[0]=t.values[0],this.values[1]=t.values[1],this.values[2]=t.values[2],this.values[3]=t.values[3]}get translation(){return new C(this.values[4],this.values[5])}set translation(e){const t=new C(e);this.values[4]=t.x,this.values[5]=t.y}get scaling(){return new C(this.values[0],this.values[3])}set scaling(e){const t=new C(e),s=new C(this.values[0],this.values[1]).normalized,n=new C(this.values[2],this.values[3]).normalized;this.values[0]=s.x*t.x,this.values[1]=s.y*t.y,this.values[2]=n.x*t.x,this.values[3]=n.y*t.y}get inverse(){const e=this.values[0],t=this.values[1],s=this.values[2],n=this.values[3],a=this.values[4],h=this.values[5];let l=e*n-t*s;return l?(l=1/l,new Ie(n*l,-t*l,-s*l,e*l,(s*h-n*a)*l,(t*a-e*h)*l)):null}get determinant(){return this.values[0]*this.values[3]-this.values[1]*this.values[2]}get domMatrix(){return new DOMMatrix([this.values[0],this.values[1],this.values[2],this.values[3],this.values[4],this.values[5]])}constructor(e,t,s,n,a,h){if(this.values=new Float32Array(6),arguments.length===0){this.values=new Float32Array([1,0,0,1,0,0]);return}if(arguments.length===6){this.values[0]=e,this.values[1]=t,this.values[2]=s,this.values[3]=n,this.values[4]=a,this.values[5]=h;return}if(e instanceof DOMMatrix){this.values[0]=e.m11,this.values[1]=e.m12,this.values[2]=e.m21,this.values[3]=e.m22,this.values[4]=e.m41,this.values[5]=e.m42;return}if(e instanceof Ie){this.values=e.values;return}if(Array.isArray(e)){if(e.length===2){this.values[0]=e[0],this.values[1]=e[1],this.values[2]=t[0],this.values[3]=t[1],this.values[4]=s[0],this.values[5]=s[1];return}if(e.length===3){const p=new C(e[0]),g=new C(e[1]),y=new C(e[2]);this.values[0]=p.x,this.values[1]=p.y,this.values[2]=g.x,this.values[3]=g.y,this.values[4]=y.x,this.values[5]=y.y;return}this.values[0]=e[0],this.values[1]=e[1],this.values[2]=e[2],this.values[3]=e[3],this.values[4]=e[4],this.values[5]=e[5];return}const l=new C(e),u=new C(t),d=new C(s);this.values[0]=l.x,this.values[1]=l.y,this.values[2]=u.x,this.values[3]=u.y,this.values[4]=d.x,this.values[5]=d.y}column(e){return new C(this.values[e*2],this.values[e*2+1])}row(e){return[this.values[e],this.values[e+2],this.values[e+4]]}mul(e){const t=this.values[0],s=this.values[1],n=this.values[2],a=this.values[3],h=this.values[4],l=this.values[5],u=e.values[0],d=e.values[1],p=e.values[2],g=e.values[3],y=e.values[4],x=e.values[5];return new Ie(t*u+n*d,s*u+a*d,t*p+n*g,s*p+a*g,t*y+n*x+h,s*y+a*x+l)}rotate(e,t=!0){t&&(e*=pi);const s=this.values[0],n=this.values[1],a=this.values[2],h=this.values[3],l=this.values[4],u=this.values[5],d=Math.sin(e),p=Math.cos(e);return new Ie(s*p+a*d,n*p+h*d,s*-d+a*p,n*-d+h*p,l,u)}scale(e){const t=new C(e);return new Ie(this.values[0]*t.x,this.values[1]*t.x,this.values[2]*t.y,this.values[3]*t.y,this.values[4],this.values[5])}mulScalar(e){return new Ie(this.values[0]*e,this.values[1]*e,this.values[2]*e,this.values[3]*e,this.values[4]*e,this.values[5]*e)}translate(e){const t=new C(e);return new Ie(this.values[0],this.values[1],this.values[2],this.values[3],this.values[0]*t.x+this.values[2]*t.y+this.values[4],this.values[1]*t.x+this.values[3]*t.y+this.values[5])}add(e){return new Ie(this.values[0]+e.values[0],this.values[1]+e.values[1],this.values[2]+e.values[2],this.values[3]+e.values[3],this.values[4]+e.values[4],this.values[5]+e.values[5])}sub(e){return new Ie(this.values[0]-e.values[0],this.values[1]-e.values[1],this.values[2]-e.values[2],this.values[3]-e.values[3],this.values[4]-e.values[4],this.values[5]-e.values[5])}toSymbol(){return Ie.symbol}toUniform(e,t){e.uniformMatrix3x2fv(t,!1,this.values)}equals(e,t=pc){return Math.abs(this.values[0]-e.values[0])<=t+Number.EPSILON&&Math.abs(this.values[1]-e.values[1])<=t+Number.EPSILON&&Math.abs(this.values[2]-e.values[2])<=t+Number.EPSILON&&Math.abs(this.values[3]-e.values[3])<=t+Number.EPSILON&&Math.abs(this.values[4]-e.values[4])<=t+Number.EPSILON&&Math.abs(this.values[5]-e.values[5])<=t+Number.EPSILON}exactlyEquals(e){return this.values[0]===e.values[0]&&this.values[1]===e.values[1]&&this.values[2]===e.values[2]&&this.values[3]===e.values[3]&&this.values[4]===e.values[4]&&this.values[5]===e.values[5]}}Ie.symbol=Symbol.for("@twick/core/types/Matrix2D");Ie.identity=new Ie(1,0,0,1,0,0);Ie.zero=new Ie(0,0,0,0,0,0);function Nt(r,e){const t=new Ie(e);return new C(r.x*t.scaleX+r.y*t.skewY+t.translateX,r.x*t.skewX+r.y*t.scaleY+t.translateY)}function Jt(r,e){const t=new Ie(e);return new C(r.x*t.scaleX+r.y*t.skewY,r.x*t.skewX+r.y*t.scaleY)}class pe{static createSignal(e,t=pe.lerp){return new cr(["x","y","width","height"],s=>new pe(s),e,t).toSignal()}static lerp(e,t,s){let n,a,h,l;return typeof s=="number"?n=a=h=l=s:s instanceof C?(n=h=s.x,a=l=s.y):(n=s.x,a=s.y,h=s.width,l=s.height),new pe(se(e.x,t.x,n),se(e.y,t.y,a),se(e.width,t.width,h),se(e.height,t.height,l))}static arcLerp(e,t,s,n=!1,a){return a??(a=(e.position.sub(t.position).ctg+e.size.sub(t.size).ctg)/2),pe.lerp(e,t,new C(lc(s,n,a)))}static fromSizeCentered(e){return new pe(-e.width/2,-e.height/2,e.width,e.height)}static fromPoints(...e){let t=1/0,s=1/0,n=-1/0,a=-1/0;for(const h of e)h.x>n&&(n=h.x),h.x<t&&(t=h.x),h.y>a&&(a=h.y),h.y<s&&(s=h.y);return new pe(t,s,n-t,a-s)}static fromBBoxes(...e){let t=1/0,s=1/0,n=-1/0,a=-1/0;for(const h of e){const l=h.x+h.width;l>n&&(n=l),h.x<t&&(t=h.x);const u=h.y+h.height;u>a&&(a=u),h.y<s&&(s=h.y)}return new pe(t,s,n-t,a-s)}lerp(e,t){return pe.lerp(this,e,t)}get position(){return new C(this.x,this.y)}set position(e){this.x=e.x,this.y=e.y}get size(){return new C(this.width,this.height)}get center(){return new C(this.x+this.width/2,this.y+this.height/2)}get left(){return this.x}set left(e){this.width+=this.x-e,this.x=e}get right(){return this.x+this.width}set right(e){this.width=e-this.x}get top(){return this.y}set top(e){this.height+=this.y-e,this.y=e}get bottom(){return this.y+this.height}set bottom(e){this.height=e-this.y}get topLeft(){return this.position}get topRight(){return new C(this.x+this.width,this.y)}get bottomLeft(){return new C(this.x,this.y+this.height)}get bottomRight(){return new C(this.x+this.width,this.y+this.height)}get corners(){return[this.topLeft,this.topRight,this.bottomRight,this.bottomLeft]}get pixelPerfect(){return new pe(Math.floor(this.x),Math.floor(this.y),Math.ceil(this.width+1),Math.ceil(this.height+1))}constructor(e,t=0,s=0,n=0){if(this.x=0,this.y=0,this.width=0,this.height=0,e!=null){if(typeof e=="number"){this.x=e,this.y=t,this.width=s,this.height=n;return}if(e instanceof C){this.x=e.x,this.y=e.y,t instanceof C&&(this.width=t.x,this.height=t.y);return}if(Array.isArray(e)){this.x=e[0],this.y=e[1],this.width=e[2],this.height=e[3];return}this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height}}transform(e){return new pe(Nt(this.position,e),Jt(this.size,e))}transformCorners(e){return this.corners.map(t=>Nt(t,e))}expand(e){const t=new bt(e),s=new pe(this);return s.left-=t.left,s.top-=t.top,s.right+=t.right,s.bottom+=t.bottom,s}addSpacing(e){return this.expand(e)}includes(e){return e.x>=this.x&&e.x<=this.x+this.width&&e.y>=this.y&&e.y<=this.y+this.height}intersects(e){return this.left<e.right&&this.right>e.left&&this.top<e.bottom&&this.bottom>e.top}intersection(e){const t=new pe;return this.intersects(e)&&(t.left=Math.max(this.left,e.left),t.top=Math.max(this.top,e.top),t.right=Math.min(this.right,e.right),t.bottom=Math.min(this.bottom,e.bottom)),t}union(e){const t=new pe;return t.left=Math.min(this.left,e.left),t.top=Math.min(this.top,e.top),t.right=Math.max(this.right,e.right),t.bottom=Math.max(this.bottom,e.bottom),t}toSymbol(){return pe.symbol}toString(){return`BBox(${this.x}, ${this.y}, ${this.width}, ${this.height})`}toUniform(e,t){e.uniform4f(t,this.x,this.y,this.width,this.height)}serialize(){return{x:this.x,y:this.y,width:this.width,height:this.height}}}pe.symbol=Symbol.for("@twick/core/types/Rect");const gc=(r,e)=>{if(typeof r=="number"){if(e===3)return{mode:"rgb",r:(r>>8&15|r>>4&240)/255,g:(r>>4&15|r&240)/255,b:(r&15|r<<4&240)/255};if(e===4)return{mode:"rgb",r:(r>>12&15|r>>8&240)/255,g:(r>>8&15|r>>4&240)/255,b:(r>>4&15|r&240)/255,alpha:(r&15|r<<4&240)/255};if(e===6)return{mode:"rgb",r:(r>>16&255)/255,g:(r>>8&255)/255,b:(r&255)/255};if(e===8)return{mode:"rgb",r:(r>>24&255)/255,g:(r>>16&255)/255,b:(r>>8&255)/255,alpha:(r&255)/255}}},Hf={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Vf=r=>gc(Hf[r.toLowerCase()],6),Kf=/^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i,Yf=r=>{let e;return(e=r.match(Kf))?gc(parseInt(e[1],16),e[1].length):void 0},yi="([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)",Ds=`${yi}%`,fo=`(?:${yi}%|${yi})`,Wf=`(?:${yi}(deg|grad|rad|turn)|${yi})`,gs="\\s*,\\s*",jf=new RegExp(`^rgba?\\(\\s*${yi}${gs}${yi}${gs}${yi}\\s*(?:,\\s*${fo}\\s*)?\\)$`),qf=new RegExp(`^rgba?\\(\\s*${Ds}${gs}${Ds}${gs}${Ds}\\s*(?:,\\s*${fo}\\s*)?\\)$`),Xf=r=>{let e={mode:"rgb"},t;if(t=r.match(jf))t[1]!==void 0&&(e.r=t[1]/255),t[2]!==void 0&&(e.g=t[2]/255),t[3]!==void 0&&(e.b=t[3]/255);else if(t=r.match(qf))t[1]!==void 0&&(e.r=t[1]/100),t[2]!==void 0&&(e.g=t[2]/100),t[3]!==void 0&&(e.b=t[3]/100);else return;return t[4]!==void 0?e.alpha=Math.max(0,Math.min(1,t[4]/100)):t[5]!==void 0&&(e.alpha=Math.max(0,Math.min(1,+t[5]))),e},Qf=(r,e)=>r===void 0?void 0:typeof r!="object"?Sc(r):r.mode!==void 0?r:e?{...r,mode:e}:void 0,Ns=(r="rgb")=>e=>(e=Qf(e,r))!==void 0?e.mode===r?e:Dt[e.mode][r]?Dt[e.mode][r](e):r==="rgb"?Dt[e.mode].rgb(e):Dt.rgb[r](Dt[e.mode].rgb(e)):void 0,Dt={},mc={},Vn=[],yc={},Zf=r=>r,ve=r=>(Dt[r.mode]={...Dt[r.mode],...r.toMode},Object.keys(r.fromMode||{}).forEach(e=>{Dt[e]||(Dt[e]={}),Dt[e][r.mode]=r.fromMode[e]}),r.ranges||(r.ranges={}),r.difference||(r.difference={}),r.channels.forEach(e=>{if(r.ranges[e]===void 0&&(r.ranges[e]=[0,1]),!r.interpolate[e])throw new Error(`Missing interpolator for: ${e}`);typeof r.interpolate[e]=="function"&&(r.interpolate[e]={use:r.interpolate[e]}),r.interpolate[e].fixup||(r.interpolate[e].fixup=Zf)}),mc[r.mode]=r,(r.parse||[]).forEach(e=>{Jf(e,r.mode)}),Ns(r.mode)),vc=r=>mc[r],Jf=(r,e)=>{if(typeof r=="string"){if(!e)throw new Error("'mode' required when 'parser' is a string");yc[r]=e}else typeof r=="function"&&Vn.indexOf(r)<0&&Vn.push(r)},Ra=/[^\x00-\x7F]|[a-zA-Z_]/,ep=/[^\x00-\x7F]|[-\w]/,B={Function:"function",Ident:"ident",Number:"number",Percentage:"percentage",ParenClose:")",None:"none",Hue:"hue",Alpha:"alpha"};let ne=0;function on(r){let e=r[ne],t=r[ne+1];return e==="-"||e==="+"?/\d/.test(t)||t==="."&&/\d/.test(r[ne+2]):e==="."?/\d/.test(t):/\d/.test(e)}function Ca(r){if(ne>=r.length)return!1;let e=r[ne];if(Ra.test(e))return!0;if(e==="-"){if(r.length-ne<2)return!1;let t=r[ne+1];return!!(t==="-"||Ra.test(t))}return!1}const tp={deg:1,rad:180/Math.PI,grad:9/10,turn:360};function Is(r){let e="";if((r[ne]==="-"||r[ne]==="+")&&(e+=r[ne++]),e+=ln(r),r[ne]==="."&&/\d/.test(r[ne+1])&&(e+=r[ne++]+ln(r)),(r[ne]==="e"||r[ne]==="E")&&((r[ne+1]==="-"||r[ne+1]==="+")&&/\d/.test(r[ne+2])?e+=r[ne++]+r[ne++]+ln(r):/\d/.test(r[ne+1])&&(e+=r[ne++]+ln(r))),Ca(r)){let t=Kn(r);return t==="deg"||t==="rad"||t==="turn"||t==="grad"?{type:B.Hue,value:e*tp[t]}:void 0}return r[ne]==="%"?(ne++,{type:B.Percentage,value:+e}):{type:B.Number,value:+e}}function ln(r){let e="";for(;/\d/.test(r[ne]);)e+=r[ne++];return e}function Kn(r){let e="";for(;ne<r.length&&ep.test(r[ne]);)e+=r[ne++];return e}function ip(r){let e=Kn(r);return r[ne]==="("?(ne++,{type:B.Function,value:e}):e==="none"?{type:B.None,value:void 0}:{type:B.Ident,value:e}}function sp(r=""){let e=r.trim(),t=[],s;for(ne=0;ne<e.length;){if(s=e[ne++],s===`
|
|
16
|
+
`||s===" "||s===" "){for(;ne<e.length&&(e[ne]===`
|
|
17
|
+
`||e[ne]===" "||e[ne]===" ");)ne++;continue}if(s===",")return;if(s===")"){t.push({type:B.ParenClose});continue}if(s==="+"){if(ne--,on(e)){t.push(Is(e));continue}return}if(s==="-"){if(ne--,on(e)){t.push(Is(e));continue}if(Ca(e)){t.push({type:B.Ident,value:Kn(e)});continue}return}if(s==="."){if(ne--,on(e)){t.push(Is(e));continue}return}if(s==="/"){for(;ne<e.length&&(e[ne]===`
|
|
18
|
+
`||e[ne]===" "||e[ne]===" ");)ne++;let n;if(on(e)&&(n=Is(e),n.type!==B.Hue)){t.push({type:B.Alpha,value:n});continue}if(Ca(e)&&Kn(e)==="none"){t.push({type:B.Alpha,value:{type:B.None,value:void 0}});continue}return}if(/\d/.test(s)){ne--,t.push(Is(e));continue}if(Ra.test(s)){ne--,t.push(ip(e));continue}return}return t}function np(r){r._i=0;let e=r[r._i++];if(!e||e.type!==B.Function||e.value!=="color"||(e=r[r._i++],e.type!==B.Ident))return;const t=yc[e.value];if(!t)return;const s={mode:t},n=xc(r,!1);if(!n)return;const a=vc(t).channels;for(let h=0,l,u;h<a.length;h++)l=n[h],u=a[h],l.type!==B.None&&(s[u]=l.type===B.Number?l.value:l.value/100,u==="alpha"&&(s[u]=Math.max(0,Math.min(1,s[u]))));return s}function xc(r,e){const t=[];let s;for(;r._i<r.length;){if(s=r[r._i++],s.type===B.None||s.type===B.Number||s.type===B.Alpha||s.type===B.Percentage||e&&s.type===B.Hue){t.push(s);continue}if(s.type===B.ParenClose){if(r._i<r.length)return;continue}return}if(!(t.length<3||t.length>4)){if(t.length===4){if(t[3].type!==B.Alpha)return;t[3]=t[3].value}return t.length===3&&t.push({type:B.None,value:void 0}),t.every(n=>n.type!==B.Alpha)?t:void 0}}function rp(r,e){r._i=0;let t=r[r._i++];if(!t||t.type!==B.Function)return;let s=xc(r,e);if(s)return s.unshift(t.value),s}const Sc=r=>{if(typeof r!="string")return;const e=sp(r),t=e?rp(e,!0):void 0;let s,n=0,a=Vn.length;for(;n<a;)if((s=Vn[n++](r,t))!==void 0)return s;return e?np(e):void 0};function ap(r,e){if(!e||e[0]!=="rgb"&&e[0]!=="rgba")return;const t={mode:"rgb"},[,s,n,a,h]=e;if(!(s.type===B.Hue||n.type===B.Hue||a.type===B.Hue))return s.type!==B.None&&(t.r=s.type===B.Number?s.value/255:s.value/100),n.type!==B.None&&(t.g=n.type===B.Number?n.value/255:n.value/100),a.type!==B.None&&(t.b=a.type===B.Number?a.value/255:a.value/100),h.type!==B.None&&(t.alpha=Math.min(1,Math.max(0,h.type===B.Number?h.value:h.value/100))),t}const op=r=>r==="transparent"?{mode:"rgb",r:0,g:0,b:0,alpha:0}:void 0,lp=(r,e,t)=>r+t*(e-r),hp=r=>{let e=[];for(let t=0;t<r.length-1;t++){let s=r[t],n=r[t+1];s===void 0&&n===void 0?e.push(void 0):s!==void 0&&n!==void 0?e.push([s,n]):e.push(s!==void 0?[s,s]:[n,n])}return e},cp=r=>e=>{let t=hp(e);return s=>{let n=s*t.length,a=s>=1?t.length-1:Math.max(Math.floor(n),0),h=t[a];return h===void 0?void 0:r(h[0],h[1],n-a)}},Y=cp(lp),Be=r=>{let e=!1,t=r.map(s=>s!==void 0?(e=!0,s):1);return e?t:r},vs={mode:"rgb",channels:["r","g","b","alpha"],parse:[ap,Yf,Xf,Vf,op,"srgb"],serialize:"srgb",interpolate:{r:Y,g:Y,b:Y,alpha:{use:Y,fixup:Be}},gamut:!0,white:{r:1,g:1,b:1},black:{r:0,g:0,b:0}},kr=(r=0)=>Math.pow(Math.abs(r),563/256)*Math.sign(r),rl=r=>{let e=kr(r.r),t=kr(r.g),s=kr(r.b),n={mode:"xyz65",x:.5766690429101305*e+.1855582379065463*t+.1882286462349947*s,y:.297344975250536*e+.6273635662554661*t+.0752914584939979*s,z:.0270313613864123*e+.0706888525358272*t+.9913375368376386*s};return r.alpha!==void 0&&(n.alpha=r.alpha),n},Mr=r=>Math.pow(Math.abs(r),256/563)*Math.sign(r),al=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n={mode:"a98",r:Mr(r*2.0415879038107465-e*.5650069742788597-.3447313507783297*t),g:Mr(r*-.9692436362808798+e*1.8759675015077206+.0415550574071756*t),b:Mr(r*.0134442806320312-e*.1183623922310184+1.0151749943912058*t)};return s!==void 0&&(n.alpha=s),n},Fr=(r=0)=>{const e=Math.abs(r);return e<=.04045?r/12.92:(Math.sign(r)||1)*Math.pow((e+.055)/1.055,2.4)},xs=({r,g:e,b:t,alpha:s})=>{let n={mode:"lrgb",r:Fr(r),g:Fr(e),b:Fr(t)};return s!==void 0&&(n.alpha=s),n},Hi=r=>{let{r:e,g:t,b:s,alpha:n}=xs(r),a={mode:"xyz65",x:.4123907992659593*e+.357584339383878*t+.1804807884018343*s,y:.2126390058715102*e+.715168678767756*t+.0721923153607337*s,z:.0193308187155918*e+.119194779794626*t+.9505321522496607*s};return n!==void 0&&(a.alpha=n),a},Ur=(r=0)=>{const e=Math.abs(r);return e>.0031308?(Math.sign(r)||1)*(1.055*Math.pow(e,1/2.4)-.055):r*12.92},Ss=({r,g:e,b:t,alpha:s},n="rgb")=>{let a={mode:n,r:Ur(r),g:Ur(e),b:Ur(t)};return s!==void 0&&(a.alpha=s),a},Vi=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Ss({r:r*3.2409699419045226-e*1.537383177570094-.4986107602930034*t,g:r*-.9692436362808796+e*1.8759675015077204+.0415550574071756*t,b:r*.0556300796969936-e*.2039769588889765+1.0569715142428784*t});return s!==void 0&&(n.alpha=s),n},dp={...vs,mode:"a98",parse:["a98-rgb"],serialize:"a98-rgb",fromMode:{rgb:r=>al(Hi(r)),xyz65:al},toMode:{rgb:r=>Vi(rl(r)),xyz65:rl}},Ke=r=>(r=r%360)<0?r+360:r,up=(r,e)=>r.map((t,s,n)=>{if(t===void 0)return t;let a=Ke(t);return s===0||r[s-1]===void 0?a:e(a-Ke(n[s-1]))}).reduce((t,s)=>!t.length||s===void 0||t[t.length-1]===void 0?(t.push(s),t):(t.push(s+t[t.length-1]),t),[]),si=r=>up(r,e=>Math.abs(e)<=180?e:e-360*Math.sign(e)),$e=[-.14861,1.78277,-.29227,-.90649,1.97294,0],fp=Math.PI/180,pp=180/Math.PI;let ol=$e[3]*$e[4],ll=$e[1]*$e[4],hl=$e[1]*$e[2]-$e[0]*$e[3];const gp=({r,g:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=(hl*t+r*ol-e*ll)/(hl+ol-ll),a=t-n,h=($e[4]*(e-n)-$e[2]*a)/$e[3],l={mode:"cubehelix",l:n,s:n===0||n===1?void 0:Math.sqrt(a*a+h*h)/($e[4]*n*(1-n))};return l.s&&(l.h=Math.atan2(h,a)*pp-120),s!==void 0&&(l.alpha=s),l},mp=({h:r,s:e,l:t,alpha:s})=>{let n={mode:"rgb"};r=(r===void 0?0:r+120)*fp,t===void 0&&(t=0);let a=e===void 0?0:e*t*(1-t),h=Math.cos(r),l=Math.sin(r);return n.r=t+a*($e[0]*h+$e[1]*l),n.g=t+a*($e[2]*h+$e[3]*l),n.b=t+a*($e[4]*h+$e[5]*l),s!==void 0&&(n.alpha=s),n},dr=(r,e)=>{if(r.h===void 0||e.h===void 0||!r.s||!e.s)return 0;let t=Ke(r.h),s=Ke(e.h),n=Math.sin((s-t+360)/2*Math.PI/180);return 2*Math.sqrt(r.s*e.s)*n},yp=(r,e)=>{if(r.h===void 0||e.h===void 0)return 0;let t=Ke(r.h),s=Ke(e.h);return Math.abs(s-t)>180?t-(s-360*Math.sign(s-t)):s-t},ur=(r,e)=>{if(r.h===void 0||e.h===void 0||!r.c||!e.c)return 0;let t=Ke(r.h),s=Ke(e.h),n=Math.sin((s-t+360)/2*Math.PI/180);return 2*Math.sqrt(r.c*e.c)*n},ni=r=>{let e=r.reduce((s,n)=>{if(n!==void 0){let a=n*Math.PI/180;s.sin+=Math.sin(a),s.cos+=Math.cos(a)}return s},{sin:0,cos:0}),t=Math.atan2(e.sin,e.cos)*180/Math.PI;return t<0?360+t:t},vp={mode:"cubehelix",channels:["h","s","l","alpha"],parse:["--cubehelix"],serialize:"--cubehelix",ranges:{h:[0,360],s:[0,4.614],l:[0,1]},fromMode:{rgb:gp},toMode:{rgb:mp},interpolate:{h:{use:Y,fixup:si},s:Y,l:Y,alpha:{use:Y,fixup:Be}},difference:{h:dr},average:{h:ni}},vi=({l:r,a:e,b:t,alpha:s},n="lch")=>{e===void 0&&(e=0),t===void 0&&(t=0);let a=Math.sqrt(e*e+t*t),h={mode:n,l:r,c:a};return a&&(h.h=Ke(Math.atan2(t,e)*180/Math.PI)),s!==void 0&&(h.alpha=s),h},xi=({l:r,c:e,h:t,alpha:s},n="lab")=>{t===void 0&&(t=0);let a={mode:n,l:r,a:e?e*Math.cos(t/180*Math.PI):0,b:e?e*Math.sin(t/180*Math.PI):0};return s!==void 0&&(a.alpha=s),a},_c=Math.pow(29,3)/Math.pow(3,3),Ec=Math.pow(6,3)/Math.pow(29,3),De={X:.3457/.3585,Y:1,Z:(1-.3457-.3585)/.3585},as={X:.3127/.329,Y:1,Z:(1-.3127-.329)/.329};let Or=r=>Math.pow(r,3)>Ec?Math.pow(r,3):(116*r-16)/_c;const Tc=({l:r,a:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=(r+16)/116,a=e/500+n,h=n-t/200,l={mode:"xyz65",x:Or(a)*as.X,y:Or(n)*as.Y,z:Or(h)*as.Z};return s!==void 0&&(l.alpha=s),l},fr=r=>Vi(Tc(r)),Br=r=>r>Ec?Math.cbrt(r):(_c*r+16)/116,bc=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Br(r/as.X),a=Br(e/as.Y),h=Br(t/as.Z),l={mode:"lab65",l:116*a-16,a:500*(n-a),b:200*(a-h)};return s!==void 0&&(l.alpha=s),l},pr=r=>{let e=bc(Hi(r));return r.r===r.b&&r.b===r.g&&(e.a=e.b=0),e},Yn=1,Ac=1,$s=26/180*Math.PI,Wn=Math.cos($s),jn=Math.sin($s),Ic=100/Math.log(139/100),Pa=({l:r,c:e,h:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n={mode:"lab65",l:(Math.exp(r*Yn/Ic)-1)/.0039},a=(Math.exp(.0435*e*Ac*Yn)-1)/.075,h=a*Math.cos(t/180*Math.PI-$s),l=a*Math.sin(t/180*Math.PI-$s);return n.a=h*Wn-l/.83*jn,n.b=h*jn+l/.83*Wn,s!==void 0&&(n.alpha=s),n},Da=({l:r,a:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=e*Wn+t*jn,a=.83*(t*Wn-e*jn),h=Math.sqrt(n*n+a*a),l={mode:"dlch",l:Ic/Yn*Math.log(1+.0039*r),c:Math.log(1+.075*h)/(.0435*Ac*Yn)};return l.c&&(l.h=Ke((Math.atan2(a,n)+$s)/Math.PI*180)),s!==void 0&&(l.alpha=s),l},cl=r=>Pa(vi(r,"dlch")),dl=r=>xi(Da(r),"dlab"),xp={mode:"dlab",parse:["--din99o-lab"],serialize:"--din99o-lab",toMode:{lab65:cl,rgb:r=>fr(cl(r))},fromMode:{lab65:dl,rgb:r=>dl(pr(r))},channels:["l","a","b","alpha"],ranges:{l:[0,100],a:[-40.09,45.501],b:[-40.469,44.344]},interpolate:{l:Y,a:Y,b:Y,alpha:{use:Y,fixup:Be}}},Sp={mode:"dlch",parse:["--din99o-lch"],serialize:"--din99o-lch",toMode:{lab65:Pa,dlab:r=>xi(r,"dlab"),rgb:r=>fr(Pa(r))},fromMode:{lab65:Da,dlab:r=>vi(r,"dlch"),rgb:r=>Da(pr(r))},channels:["l","c","h","alpha"],ranges:{l:[0,100],c:[0,51.484],h:[0,360]},interpolate:{l:Y,c:Y,h:{use:Y,fixup:si},alpha:{use:Y,fixup:Be}},difference:{h:ur},average:{h:ni}};function _p({h:r,s:e,i:t,alpha:s}){r=Ke(r!==void 0?r:0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.abs(r/60%2-1),a;switch(Math.floor(r/60)){case 0:a={r:t*(1+e*(3/(2-n)-1)),g:t*(1+e*(3*(1-n)/(2-n)-1)),b:t*(1-e)};break;case 1:a={r:t*(1+e*(3*(1-n)/(2-n)-1)),g:t*(1+e*(3/(2-n)-1)),b:t*(1-e)};break;case 2:a={r:t*(1-e),g:t*(1+e*(3/(2-n)-1)),b:t*(1+e*(3*(1-n)/(2-n)-1))};break;case 3:a={r:t*(1-e),g:t*(1+e*(3*(1-n)/(2-n)-1)),b:t*(1+e*(3/(2-n)-1))};break;case 4:a={r:t*(1+e*(3*(1-n)/(2-n)-1)),g:t*(1-e),b:t*(1+e*(3/(2-n)-1))};break;case 5:a={r:t*(1+e*(3/(2-n)-1)),g:t*(1-e),b:t*(1+e*(3*(1-n)/(2-n)-1))};break;default:a={r:t*(1-e),g:t*(1-e),b:t*(1-e)}}return a.mode="rgb",s!==void 0&&(a.alpha=s),a}function Ep({r,g:e,b:t,alpha:s}){r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.max(r,e,t),a=Math.min(r,e,t),h={mode:"hsi",s:r+e+t===0?0:1-3*a/(r+e+t),i:(r+e+t)/3};return n-a!==0&&(h.h=(n===r?(e-t)/(n-a)+(e<t)*6:n===e?(t-r)/(n-a)+2:(r-e)/(n-a)+4)*60),s!==void 0&&(h.alpha=s),h}const Tp={mode:"hsi",toMode:{rgb:_p},parse:["--hsi"],serialize:"--hsi",fromMode:{rgb:Ep},channels:["h","s","i","alpha"],ranges:{h:[0,360]},gamut:"rgb",interpolate:{h:{use:Y,fixup:si},s:Y,i:Y,alpha:{use:Y,fixup:Be}},difference:{h:dr},average:{h:ni}};function bp({h:r,s:e,l:t,alpha:s}){r=Ke(r!==void 0?r:0),e===void 0&&(e=0),t===void 0&&(t=0);let n=t+e*(t<.5?t:1-t),a=n-(n-t)*2*Math.abs(r/60%2-1),h;switch(Math.floor(r/60)){case 0:h={r:n,g:a,b:2*t-n};break;case 1:h={r:a,g:n,b:2*t-n};break;case 2:h={r:2*t-n,g:n,b:a};break;case 3:h={r:2*t-n,g:a,b:n};break;case 4:h={r:a,g:2*t-n,b:n};break;case 5:h={r:n,g:2*t-n,b:a};break;default:h={r:2*t-n,g:2*t-n,b:2*t-n}}return h.mode="rgb",s!==void 0&&(h.alpha=s),h}function Ap({r,g:e,b:t,alpha:s}){r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.max(r,e,t),a=Math.min(r,e,t),h={mode:"hsl",s:n===a?0:(n-a)/(1-Math.abs(n+a-1)),l:.5*(n+a)};return n-a!==0&&(h.h=(n===r?(e-t)/(n-a)+(e<t)*6:n===e?(t-r)/(n-a)+2:(r-e)/(n-a)+4)*60),s!==void 0&&(h.alpha=s),h}const Ip=(r,e)=>{switch(e){case"deg":return+r;case"rad":return r/Math.PI*180;case"grad":return r/10*9;case"turn":return r*360}},wp=new RegExp(`^hsla?\\(\\s*${Wf}${gs}${Ds}${gs}${Ds}\\s*(?:,\\s*${fo}\\s*)?\\)$`),Lp=r=>{let e=r.match(wp);if(!e)return;let t={mode:"hsl"};return e[3]!==void 0?t.h=+e[3]:e[1]!==void 0&&e[2]!==void 0&&(t.h=Ip(e[1],e[2])),e[4]!==void 0&&(t.s=Math.min(Math.max(0,e[4]/100),1)),e[5]!==void 0&&(t.l=Math.min(Math.max(0,e[5]/100),1)),e[6]!==void 0?t.alpha=Math.max(0,Math.min(1,e[6]/100)):e[7]!==void 0&&(t.alpha=Math.max(0,Math.min(1,+e[7]))),t};function Rp(r,e){if(!e||e[0]!=="hsl"&&e[0]!=="hsla")return;const t={mode:"hsl"},[,s,n,a,h]=e;if(s.type!==B.None){if(s.type===B.Percentage)return;t.h=s.value}if(n.type!==B.None){if(n.type===B.Hue)return;t.s=n.value/100}if(a.type!==B.None){if(a.type===B.Hue)return;t.l=a.value/100}return h.type!==B.None&&(t.alpha=Math.min(1,Math.max(0,h.type===B.Number?h.value:h.value/100))),t}const wc={mode:"hsl",toMode:{rgb:bp},fromMode:{rgb:Ap},channels:["h","s","l","alpha"],ranges:{h:[0,360]},gamut:"rgb",parse:[Rp,Lp],serialize:r=>`hsl(${r.h!==void 0?r.h:"none"} ${r.s!==void 0?r.s*100+"%":"none"} ${r.l!==void 0?r.l*100+"%":"none"}${r.alpha<1?` / ${r.alpha}`:""})`,interpolate:{h:{use:Y,fixup:si},s:Y,l:Y,alpha:{use:Y,fixup:Be}},difference:{h:dr},average:{h:ni}};function Lc({h:r,s:e,v:t,alpha:s}){r=Ke(r!==void 0?r:0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.abs(r/60%2-1),a;switch(Math.floor(r/60)){case 0:a={r:t,g:t*(1-e*n),b:t*(1-e)};break;case 1:a={r:t*(1-e*n),g:t,b:t*(1-e)};break;case 2:a={r:t*(1-e),g:t,b:t*(1-e*n)};break;case 3:a={r:t*(1-e),g:t*(1-e*n),b:t};break;case 4:a={r:t*(1-e*n),g:t*(1-e),b:t};break;case 5:a={r:t,g:t*(1-e),b:t*(1-e*n)};break;default:a={r:t*(1-e),g:t*(1-e),b:t*(1-e)}}return a.mode="rgb",s!==void 0&&(a.alpha=s),a}function Rc({r,g:e,b:t,alpha:s}){r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.max(r,e,t),a=Math.min(r,e,t),h={mode:"hsv",s:n===0?0:1-a/n,v:n};return n-a!==0&&(h.h=(n===r?(e-t)/(n-a)+(e<t)*6:n===e?(t-r)/(n-a)+2:(r-e)/(n-a)+4)*60),s!==void 0&&(h.alpha=s),h}const Cc={mode:"hsv",toMode:{rgb:Lc},parse:["--hsv"],serialize:"--hsv",fromMode:{rgb:Rc},channels:["h","s","v","alpha"],ranges:{h:[0,360]},gamut:"rgb",interpolate:{h:{use:Y,fixup:si},s:Y,v:Y,alpha:{use:Y,fixup:Be}},difference:{h:dr},average:{h:ni}};function Cp({h:r,w:e,b:t,alpha:s}){if(e===void 0&&(e=0),t===void 0&&(t=0),e+t>1){let n=e+t;e/=n,t/=n}return Lc({h:r,s:t===1?1:1-e/(1-t),v:1-t,alpha:s})}function Pp(r){let e=Rc(r);if(e===void 0)return;let t=e.s!==void 0?e.s:0,s=e.v!==void 0?e.v:0,n={mode:"hwb",w:(1-t)*s,b:1-s};return e.h!==void 0&&(n.h=e.h),e.alpha!==void 0&&(n.alpha=e.alpha),n}function Dp(r,e){if(!e||e[0]!=="hwb")return;const t={mode:"hwb"},[,s,n,a,h]=e;if(s.type!==B.None){if(s.type===B.Percentage)return;t.h=s.value}if(n.type!==B.None){if(n.type===B.Hue)return;t.w=n.value/100}if(a.type!==B.None){if(a.type===B.Hue)return;t.b=a.value/100}return h.type!==B.None&&(t.alpha=Math.min(1,Math.max(0,h.type===B.Number?h.value:h.value/100))),t}const kp={mode:"hwb",toMode:{rgb:Cp},fromMode:{rgb:Pp},channels:["h","w","b","alpha"],ranges:{h:[0,360]},gamut:"rgb",parse:[Dp],serialize:r=>`hwb(${r.h!==void 0?r.h:"none"} ${r.w!==void 0?r.w*100+"%":"none"} ${r.b!==void 0?r.b*100+"%":"none"}${r.alpha<1?` / ${r.alpha}`:""})`,interpolate:{h:{use:Y,fixup:si},w:Y,b:Y,alpha:{use:Y,fixup:Be}},difference:{h:yp},average:{h:ni}},Pc=203,gr=.1593017578125,Dc=78.84375,mr=.8359375,yr=18.8515625,vr=18.6875;function Nr(r){if(r<0)return 0;const e=Math.pow(r,1/Dc);return 1e4*Math.pow(Math.max(0,e-mr)/(yr-vr*e),1/gr)}function $r(r){if(r<0)return 0;const e=Math.pow(r/1e4,gr);return Math.pow((mr+yr*e)/(1+vr*e),Dc)}const Gr=r=>Math.max(r/Pc,0),ul=({i:r,t:e,p:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);const n=Nr(r+.008609037037932761*e+.11102962500302593*t),a=Nr(r-.00860903703793275*e-.11102962500302599*t),h=Nr(r+.5600313357106791*e-.32062717498731885*t),l={mode:"xyz65",x:Gr(2.070152218389422*n-1.3263473389671556*a+.2066510476294051*h),y:Gr(.3647385209748074*n+.680566024947227*a-.0453045459220346*h),z:Gr(-.049747207535812*n-.0492609666966138*a+1.1880659249923042*h)};return s!==void 0&&(l.alpha=s),l},zr=(r=0)=>Math.max(r*Pc,0),fl=({x:r,y:e,z:t,alpha:s})=>{const n=zr(r),a=zr(e),h=zr(t),l=$r(.3592832590121217*n+.6976051147779502*a-.0358915932320289*h),u=$r(-.1920808463704995*n+1.1004767970374323*a+.0753748658519118*h),d=$r(.0070797844607477*n+.0748396662186366*a+.8433265453898765*h),p=.5*l+.5*u,g=1.61376953125*l-3.323486328125*u+1.709716796875*d,y=4.378173828125*l-4.24560546875*u-.132568359375*d,x={mode:"itp",i:p,t:g,p:y};return s!==void 0&&(x.alpha=s),x},Mp={mode:"itp",channels:["i","t","p","alpha"],parse:["--ictcp"],serialize:"--ictcp",toMode:{xyz65:ul,rgb:r=>Vi(ul(r))},fromMode:{xyz65:fl,rgb:r=>fl(Hi(r))},ranges:{i:[0,.581],t:[-.369,.272],p:[-.164,.331]},interpolate:{i:Y,t:Y,p:Y,alpha:{use:Y,fixup:Be}}},Fp=134.03437499999998,Up=16295499532821565e-27,Hr=r=>{if(r<0)return 0;let e=Math.pow(r/1e4,gr);return Math.pow((mr+yr*e)/(1+vr*e),Fp)},Vr=(r=0)=>Math.max(r*203,0),kc=({x:r,y:e,z:t,alpha:s})=>{r=Vr(r),e=Vr(e),t=Vr(t);let n=1.15*r-.15*t,a=.66*e+.34*r,h=Hr(.41478972*n+.579999*a+.014648*t),l=Hr(-.20151*n+1.120649*a+.0531008*t),u=Hr(-.0166008*n+.2648*a+.6684799*t),d=(h+l)/2,p={mode:"jab",j:.44*d/(1-.56*d)-Up,a:3.524*h-4.066708*l+.542708*u,b:.199076*h+1.096799*l-1.295875*u};return s!==void 0&&(p.alpha=s),p},Op=134.03437499999998,pl=16295499532821565e-27,Kr=r=>{if(r<0)return 0;let e=Math.pow(r,1/Op);return 1e4*Math.pow((mr-e)/(vr*e-yr),1/gr)},Yr=r=>r/203,Mc=({j:r,a:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=(r+pl)/(.44+.56*(r+pl)),a=Kr(n+.13860504*e+.058047316*t),h=Kr(n-.13860504*e-.058047316*t),l=Kr(n-.096019242*e-.8118919*t),u={mode:"xyz65",x:Yr(1.661373024652174*a-.914523081304348*h+.23136208173913045*l),y:Yr(-.3250758611844533*a+1.571847026732543*h-.21825383453227928*l),z:Yr(-.090982811*a-.31272829*h+1.5227666*l)};return s!==void 0&&(u.alpha=s),u},Fc=r=>{let e=kc(Hi(r));return r.r===r.b&&r.b===r.g&&(e.a=e.b=0),e},Uc=r=>Vi(Mc(r)),Bp={mode:"jab",channels:["j","a","b","alpha"],parse:["--jzazbz"],serialize:"--jzazbz",fromMode:{rgb:Fc,xyz65:kc},toMode:{rgb:Uc,xyz65:Mc},ranges:{j:[0,.222],a:[-.109,.129],b:[-.185,.134]},interpolate:{j:Y,a:Y,b:Y,alpha:{use:Y,fixup:Be}}},gl=({j:r,a:e,b:t,alpha:s})=>{e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.sqrt(e*e+t*t),a={mode:"jch",j:r,c:n};return n&&(a.h=Ke(Math.atan2(t,e)*180/Math.PI)),s!==void 0&&(a.alpha=s),a},ml=({j:r,c:e,h:t,alpha:s})=>{t===void 0&&(t=0);let n={mode:"jab",j:r,a:e?e*Math.cos(t/180*Math.PI):0,b:e?e*Math.sin(t/180*Math.PI):0};return s!==void 0&&(n.alpha=s),n},Np={mode:"jch",parse:["--jzczhz"],serialize:"--jzczhz",toMode:{jab:ml,rgb:r=>Uc(ml(r))},fromMode:{rgb:r=>gl(Fc(r)),jab:gl},channels:["j","c","h","alpha"],ranges:{j:[0,.221],c:[0,.19],h:[0,360]},interpolate:{h:{use:Y,fixup:si},c:Y,j:Y,alpha:{use:Y,fixup:Be}},difference:{h:ur},average:{h:ni}},xr=Math.pow(29,3)/Math.pow(3,3),po=Math.pow(6,3)/Math.pow(29,3);let Wr=r=>Math.pow(r,3)>po?Math.pow(r,3):(116*r-16)/xr;const go=({l:r,a:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=(r+16)/116,a=e/500+n,h=n-t/200,l={mode:"xyz50",x:Wr(a)*De.X,y:Wr(n)*De.Y,z:Wr(h)*De.Z};return s!==void 0&&(l.alpha=s),l},js=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Ss({r:r*3.1341359569958707-e*1.6173863321612538-.4906619460083532*t,g:r*-.978795502912089+e*1.916254567259524+.03344273116131949*t,b:r*.07195537988411677-e*.2289768264158322+1.405386058324125*t});return s!==void 0&&(n.alpha=s),n},Oc=r=>js(go(r)),qs=r=>{let{r:e,g:t,b:s,alpha:n}=xs(r),a={mode:"xyz50",x:.436065742824811*e+.3851514688337912*t+.14307845442264197*s,y:.22249319175623702*e+.7168870538238823*t+.06061979053616537*s,z:.013923904500943465*e+.09708128566574634*t+.7140993584005155*s};return n!==void 0&&(a.alpha=n),a},jr=r=>r>po?Math.cbrt(r):(xr*r+16)/116,mo=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=jr(r/De.X),a=jr(e/De.Y),h=jr(t/De.Z),l={mode:"lab",l:116*a-16,a:500*(n-a),b:200*(a-h)};return s!==void 0&&(l.alpha=s),l},Bc=r=>{let e=mo(qs(r));return r.r===r.b&&r.b===r.g&&(e.a=e.b=0),e};function $p(r,e){if(!e||e[0]!=="lab")return;const t={mode:"lab"},[,s,n,a,h]=e;if(!(s.type===B.Hue||n.type===B.Hue||a.type===B.Hue))return s.type!==B.None&&(t.l=Math.min(Math.max(0,s.value),100)),n.type!==B.None&&(t.a=n.type===B.Number?n.value:n.value*125/100),a.type!==B.None&&(t.b=a.type===B.Number?a.value:a.value*125/100),h.type!==B.None&&(t.alpha=Math.min(1,Math.max(0,h.type===B.Number?h.value:h.value/100))),t}const yo={mode:"lab",toMode:{xyz50:go,rgb:Oc},fromMode:{xyz50:mo,rgb:Bc},channels:["l","a","b","alpha"],ranges:{l:[0,100],a:[-125,125],b:[-125,125]},parse:[$p],serialize:r=>`lab(${r.l!==void 0?r.l:"none"} ${r.a!==void 0?r.a:"none"} ${r.b!==void 0?r.b:"none"}${r.alpha<1?` / ${r.alpha}`:""})`,interpolate:{l:Y,a:Y,b:Y,alpha:{use:Y,fixup:Be}}},Gp={...yo,mode:"lab65",parse:["--lab-d65"],serialize:"--lab-d65",toMode:{xyz65:Tc,rgb:fr},fromMode:{xyz65:bc,rgb:pr},ranges:{l:[0,100],a:[-125,125],b:[-125,125]}};function zp(r,e){if(!e||e[0]!=="lch")return;const t={mode:"lch"},[,s,n,a,h]=e;if(s.type!==B.None){if(s.type===B.Hue)return;t.l=Math.min(Math.max(0,s.value),100)}if(n.type!==B.None&&(t.c=Math.max(0,n.type===B.Number?n.value:n.value*150/100)),a.type!==B.None){if(a.type===B.Percentage)return;t.h=a.value}return h.type!==B.None&&(t.alpha=Math.min(1,Math.max(0,h.type===B.Number?h.value:h.value/100))),t}const vo={mode:"lch",toMode:{lab:xi,rgb:r=>Oc(xi(r))},fromMode:{rgb:r=>vi(Bc(r)),lab:vi},channels:["l","c","h","alpha"],ranges:{l:[0,100],c:[0,150],h:[0,360]},parse:[zp],serialize:r=>`lch(${r.l!==void 0?r.l:"none"} ${r.c!==void 0?r.c:"none"} ${r.h!==void 0?r.h:"none"}${r.alpha<1?` / ${r.alpha}`:""})`,interpolate:{h:{use:Y,fixup:si},c:Y,l:Y,alpha:{use:Y,fixup:Be}},difference:{h:ur},average:{h:ni}},Hp={...vo,mode:"lch65",parse:["--lch-d65"],serialize:"--lch-d65",toMode:{lab65:r=>xi(r,"lab65"),rgb:r=>fr(xi(r,"lab65"))},fromMode:{rgb:r=>vi(pr(r),"lch65"),lab65:r=>vi(r,"lch65")},ranges:{l:[0,100],c:[0,150],h:[0,360]}},Nc=({l:r,u:e,v:t,alpha:s})=>{e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.sqrt(e*e+t*t),a={mode:"lchuv",l:r,c:n};return n&&(a.h=Ke(Math.atan2(t,e)*180/Math.PI)),s!==void 0&&(a.alpha=s),a},$c=({l:r,c:e,h:t,alpha:s})=>{t===void 0&&(t=0);let n={mode:"luv",l:r,u:e?e*Math.cos(t/180*Math.PI):0,v:e?e*Math.sin(t/180*Math.PI):0};return s!==void 0&&(n.alpha=s),n},Gc=(r,e,t)=>4*r/(r+15*e+3*t),zc=(r,e,t)=>9*e/(r+15*e+3*t),Vp=Gc(De.X,De.Y,De.Z),Kp=zc(De.X,De.Y,De.Z),Yp=r=>r<=po?xr*r:116*Math.cbrt(r)-16,ka=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Yp(e/De.Y),a=Gc(r,e,t),h=zc(r,e,t);!isFinite(a)||!isFinite(h)?n=a=h=0:(a=13*n*(a-Vp),h=13*n*(h-Kp));let l={mode:"luv",l:n,u:a,v:h};return s!==void 0&&(l.alpha=s),l},Wp=(r,e,t)=>4*r/(r+15*e+3*t),jp=(r,e,t)=>9*e/(r+15*e+3*t),qp=Wp(De.X,De.Y,De.Z),Xp=jp(De.X,De.Y,De.Z),Ma=({l:r,u:e,v:t,alpha:s})=>{if(r===void 0&&(r=0),r===0)return{mode:"xyz50",x:0,y:0,z:0};e===void 0&&(e=0),t===void 0&&(t=0);let n=e/(13*r)+qp,a=t/(13*r)+Xp,h=De.Y*(r<=8?r/xr:Math.pow((r+16)/116,3)),l=h*(9*n)/(4*a),u=h*(12-3*n-20*a)/(4*a),d={mode:"xyz50",x:l,y:h,z:u};return s!==void 0&&(d.alpha=s),d},Qp=r=>Nc(ka(qs(r))),Zp=r=>js(Ma($c(r))),Jp={mode:"lchuv",toMode:{luv:$c,rgb:Zp},fromMode:{rgb:Qp,luv:Nc},channels:["l","c","h","alpha"],parse:["--lchuv"],serialize:"--lchuv",ranges:{l:[0,100],c:[0,176.956],h:[0,360]},interpolate:{h:{use:Y,fixup:si},c:Y,l:Y,alpha:{use:Y,fixup:Be}},difference:{h:ur},average:{h:ni}},eg={...vs,mode:"lrgb",toMode:{rgb:Ss},fromMode:{rgb:xs},parse:["srgb-linear"],serialize:"srgb-linear"},tg={mode:"luv",toMode:{xyz50:Ma,rgb:r=>js(Ma(r))},fromMode:{xyz50:ka,rgb:r=>ka(qs(r))},channels:["l","u","v","alpha"],parse:["--luv"],serialize:"--luv",ranges:{l:[0,100],u:[-84.936,175.042],v:[-125.882,87.243]},interpolate:{l:Y,u:Y,v:Y,alpha:{use:Y,fixup:Be}}},Hc=({r,g:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.cbrt(.412221469470763*r+.5363325372617348*e+.0514459932675022*t),a=Math.cbrt(.2119034958178252*r+.6806995506452344*e+.1073969535369406*t),h=Math.cbrt(.0883024591900564*r+.2817188391361215*e+.6299787016738222*t),l={mode:"oklab",l:.210454268309314*n+.7936177747023054*a-.0040720430116193*h,a:1.9779985324311684*n-2.42859224204858*a+.450593709617411*h,b:.0259040424655478*n+.7827717124575296*a-.8086757549230774*h};return s!==void 0&&(l.alpha=s),l},Sr=r=>{let e=Hc(xs(r));return r.r===r.b&&r.b===r.g&&(e.a=e.b=0),e},Xs=({l:r,a:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Math.pow(r+.3963377773761749*e+.2158037573099136*t,3),a=Math.pow(r-.1055613458156586*e-.0638541728258133*t,3),h=Math.pow(r-.0894841775298119*e-1.2914855480194092*t,3),l={mode:"lrgb",r:4.076741636075957*n-3.3077115392580616*a+.2309699031821044*h,g:-1.2684379732850317*n+2.6097573492876887*a-.3413193760026573*h,b:-.0041960761386756*n-.7034186179359362*a+1.7076146940746117*h};return s!==void 0&&(l.alpha=s),l},_r=r=>Ss(Xs(r));function Fa(r){const s=1.170873786407767;return .5*(s*r-.206+Math.sqrt((s*r-.206)*(s*r-.206)+4*.03*s*r))}function qn(r){return(r*r+.206*r)/(1.170873786407767*(r+.03))}function ig(r,e){let t,s,n,a,h,l,u,d;-1.88170328*r-.80936493*e>1?(t=1.19086277,s=1.76576728,n=.59662641,a=.75515197,h=.56771245,l=4.0767416621,u=-3.3077115913,d=.2309699292):1.81444104*r-1.19445276*e>1?(t=.73956515,s=-.45954404,n=.08285427,a=.1254107,h=.14503204,l=-1.2684380046,u=2.6097574011,d=-.3413193965):(t=1.35733652,s=-.00915799,n=-1.1513021,a=-.50559606,h=.00692167,l=-.0041960863,u=-.7034186147,d=1.707614701);let p=t+s*r+n*e+a*r*r+h*r*e,g=.3963377774*r+.2158037573*e,y=-.1055613458*r-.0638541728*e,x=-.0894841775*r-1.291485548*e;{let v=1+p*g,_=1+p*y,o=1+p*x,c=v*v*v,f=_*_*_,m=o*o*o,S=3*g*v*v,T=3*y*_*_,b=3*x*o*o,A=6*g*g*v,I=6*y*y*_,L=6*x*x*o,w=l*c+u*f+d*m,R=l*S+u*T+d*b,M=l*A+u*I+d*L;p=p-w*R/(R*R-.5*w*M)}return p}function xo(r,e){let t=ig(r,e),s=Xs({l:1,a:t*r,b:t*e}),n=Math.cbrt(1/Math.max(s.r,s.g,s.b)),a=n*t;return[n,a]}function sg(r,e,t,s,n,a=null){a||(a=xo(r,e));let h;if((t-n)*a[1]-(a[0]-n)*s<=0)h=a[1]*n/(s*a[0]+a[1]*(n-t));else{h=a[1]*(n-1)/(s*(a[0]-1)+a[1]*(n-t));{let l=t-n,u=s,d=.3963377774*r+.2158037573*e,p=-.1055613458*r-.0638541728*e,g=-.0894841775*r-1.291485548*e,y=l+u*d,x=l+u*p,v=l+u*g;{let _=n*(1-h)+h*t,o=h*s,c=_+o*d,f=_+o*p,m=_+o*g,S=c*c*c,T=f*f*f,b=m*m*m,A=3*y*c*c,I=3*x*f*f,L=3*v*m*m,w=6*y*y*c,R=6*x*x*f,M=6*v*v*m,k=4.0767416621*S-3.3077115913*T+.2309699292*b-1,z=4.0767416621*A-3.3077115913*I+.2309699292*L,O=4.0767416621*w-3.3077115913*R+.2309699292*M,U=z/(z*z-.5*k*O),j=-k*U,H=-1.2684380046*S+2.6097574011*T-.3413193965*b-1,V=-1.2684380046*A+2.6097574011*I-.3413193965*L,J=-1.2684380046*w+2.6097574011*R-.3413193965*M,$=V/(V*V-.5*H*J),G=-H*$,ie=-.0041960863*S-.7034186147*T+1.707614701*b-1,ce=-.0041960863*A-.7034186147*I+1.707614701*L,K=-.0041960863*w-.7034186147*R+1.707614701*M,ue=ce/(ce*ce-.5*ie*K),Ce=-ie*ue;j=U>=0?j:1e6,G=$>=0?G:1e6,Ce=ue>=0?Ce:1e6,h+=Math.min(j,Math.min(G,Ce))}}}return h}function So(r,e,t=null){t||(t=xo(r,e));let s=t[0],n=t[1];return[n/s,n/(1-s)]}function Vc(r,e,t){let s=xo(e,t),n=sg(e,t,r,1,r,s),a=So(e,t,s),h=.11516993+1/(7.4477897+4.1590124*t+e*(-2.19557347+1.75198401*t+e*(-2.13704948-10.02301043*t+e*(-4.24894561+5.38770819*t+4.69891013*e)))),l=.11239642+1/(1.6132032-.68124379*t+e*(.40370612+.90148123*t+e*(-.27087943+.6122399*t+e*(.00299215-.45399568*t-.14661872*e)))),u=n/Math.min(r*a[0],(1-r)*a[1]),d=r*h,p=(1-r)*l,g=.9*u*Math.sqrt(Math.sqrt(1/(1/(d*d*d*d)+1/(p*p*p*p))));return d=r*.4,p=(1-r)*.8,[Math.sqrt(1/(1/(d*d)+1/(p*p))),g,n]}function yl(r){const e=r.l!==void 0?r.l:0,t=r.a!==void 0?r.a:0,s=r.b!==void 0?r.b:0,n={mode:"okhsl",l:Fa(e)};r.alpha!==void 0&&(n.alpha=r.alpha);let a=Math.sqrt(t*t+s*s);if(!a)return n.s=0,n;let[h,l,u]=Vc(e,t/a,s/a),d;if(a<l){let p=0,g=.8*h,y=1-g/l;d=(a-p)/(g+y*(a-p))*.8}else{let p=l,g=.2*l*l*1.25*1.25/h,y=1-g/(u-l);d=.8+.2*((a-p)/(g+y*(a-p)))}return d&&(n.s=d,n.h=Ke(Math.atan2(s,t)*180/Math.PI)),n}function vl(r){let e=r.h!==void 0?r.h:0,t=r.s!==void 0?r.s:0,s=r.l!==void 0?r.l:0;const n={mode:"oklab",l:qn(s)};if(r.alpha!==void 0&&(n.alpha=r.alpha),!t||s===1)return n.a=n.b=0,n;let a=Math.cos(e/180*Math.PI),h=Math.sin(e/180*Math.PI),[l,u,d]=Vc(n.l,a,h),p,g,y,x;t<.8?(p=1.25*t,g=0,y=.8*l,x=1-y/u):(p=5*(t-.8),g=u,y=.2*u*u*1.25*1.25/l,x=1-y/(d-u));let v=g+p*y/(1-x*p);return n.a=v*a,n.b=v*h,n}const ng={...wc,mode:"okhsl",channels:["h","s","l","alpha"],parse:["--okhsl"],serialize:"--okhsl",fromMode:{oklab:yl,rgb:r=>yl(Sr(r))},toMode:{oklab:vl,rgb:r=>_r(vl(r))}};function xl(r){let e=r.l!==void 0?r.l:0,t=r.a!==void 0?r.a:0,s=r.b!==void 0?r.b:0,n=Math.sqrt(t*t+s*s),a=n?t/n:1,h=n?s/n:1,[l,u]=So(a,h),d=.5,p=1-d/l,g=u/(n+e*u),y=g*e,x=g*n,v=qn(y),_=x*v/y,o=Xs({l:v,a:a*_,b:h*_}),c=Math.cbrt(1/Math.max(o.r,o.g,o.b,0));e=e/c,n=n/c*Fa(e)/e,e=Fa(e);const f={mode:"okhsv",s:n?(d+u)*x/(u*d+u*p*x):0,v:e?e/y:0};return f.s&&(f.h=Ke(Math.atan2(s,t)*180/Math.PI)),r.alpha!==void 0&&(f.alpha=r.alpha),f}function Sl(r){const e={mode:"oklab"};r.alpha!==void 0&&(e.alpha=r.alpha);const t=r.h!==void 0?r.h:0,s=r.s!==void 0?r.s:0,n=r.v!==void 0?r.v:0,a=Math.cos(t/180*Math.PI),h=Math.sin(t/180*Math.PI),[l,u]=So(a,h),d=.5,p=1-d/l,g=1-s*d/(d+u-u*p*s),y=s*u*d/(d+u-u*p*s),x=qn(g),v=y*x/g,_=Xs({l:x,a:a*v,b:h*v}),o=Math.cbrt(1/Math.max(_.r,_.g,_.b,0)),c=qn(n*g),f=y*c/g;return e.l=c*o,e.a=f*a*o,e.b=f*h*o,e}const rg={...Cc,mode:"okhsv",channels:["h","s","v","alpha"],parse:["--okhsv"],serialize:"--okhsv",fromMode:{oklab:xl,rgb:r=>xl(Sr(r))},toMode:{oklab:Sl,rgb:r=>_r(Sl(r))}};function ag(r,e){if(!e||e[0]!=="oklab")return;const t={mode:"oklab"},[,s,n,a,h]=e;if(!(s.type===B.Hue||n.type===B.Hue||a.type===B.Hue))return s.type!==B.None&&(t.l=Math.min(Math.max(0,s.type===B.Number?s.value:s.value/100),1)),n.type!==B.None&&(t.a=n.type===B.Number?n.value:n.value*.4/100),a.type!==B.None&&(t.b=a.type===B.Number?a.value:a.value*.4/100),h.type!==B.None&&(t.alpha=Math.min(1,Math.max(0,h.type===B.Number?h.value:h.value/100))),t}const og={...yo,mode:"oklab",toMode:{lrgb:Xs,rgb:_r},fromMode:{lrgb:Hc,rgb:Sr},ranges:{l:[0,1],a:[-.4,.4],b:[-.4,.4]},parse:[ag],serialize:r=>`oklab(${r.l!==void 0?r.l:"none"} ${r.a!==void 0?r.a:"none"} ${r.b!==void 0?r.b:"none"}${r.alpha<1?` / ${r.alpha}`:""})`};function lg(r,e){if(!e||e[0]!=="oklch")return;const t={mode:"oklch"},[,s,n,a,h]=e;if(s.type!==B.None){if(s.type===B.Hue)return;t.l=Math.min(Math.max(0,s.type===B.Number?s.value:s.value/100),1)}if(n.type!==B.None&&(t.c=Math.max(0,n.type===B.Number?n.value:n.value*.4/100)),a.type!==B.None){if(a.type===B.Percentage)return;t.h=a.value}return h.type!==B.None&&(t.alpha=Math.min(1,Math.max(0,h.type===B.Number?h.value:h.value/100))),t}const hg={...vo,mode:"oklch",toMode:{oklab:r=>xi(r,"oklab"),rgb:r=>_r(xi(r,"oklab"))},fromMode:{rgb:r=>vi(Sr(r),"oklch"),oklab:r=>vi(r,"oklch")},parse:[lg],serialize:r=>`oklch(${r.l!==void 0?r.l:"none"} ${r.c!==void 0?r.c:"none"} ${r.h!==void 0?r.h:"none"}${r.alpha<1?` / ${r.alpha}`:""})`,ranges:{l:[0,1],c:[0,.4],h:[0,360]}},_l=r=>{let{r:e,g:t,b:s,alpha:n}=xs(r),a={mode:"xyz65",x:.486570948648216*e+.265667693169093*t+.1982172852343625*s,y:.2289745640697487*e+.6917385218365062*t+.079286914093745*s,z:0*e+.0451133818589026*t+1.043944368900976*s};return n!==void 0&&(a.alpha=n),a},El=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n=Ss({r:r*2.4934969119414263-e*.9313836179191242-.402710784450717*t,g:r*-.8294889695615749+e*1.7626640603183465+.0236246858419436*t,b:r*.0358458302437845-e*.0761723892680418+.9568845240076871*t},"p3");return s!==void 0&&(n.alpha=s),n},cg={...vs,mode:"p3",parse:["display-p3"],serialize:"display-p3",fromMode:{rgb:r=>El(Hi(r)),xyz65:El},toMode:{rgb:r=>Vi(_l(r)),xyz65:_l}},qr=r=>{let e=Math.abs(r);return e>=1/512?Math.sign(r)*Math.pow(e,1/1.8):16*r},Tl=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n={mode:"prophoto",r:qr(r*1.3457868816471585-e*.2555720873797946-.0511018649755453*t),g:qr(r*-.5446307051249019+e*1.5082477428451466+.0205274474364214*t),b:qr(r*0+e*0+1.2119675456389452*t)};return s!==void 0&&(n.alpha=s),n},Xr=(r=0)=>{let e=Math.abs(r);return e>=16/512?Math.sign(r)*Math.pow(e,1.8):r/16},bl=r=>{let e=Xr(r.r),t=Xr(r.g),s=Xr(r.b),n={mode:"xyz50",x:.7977666449006423*e+.1351812974005331*t+.0313477341283922*s,y:.2880748288194013*e+.7118352342418731*t+899369387256e-16*s,z:0*e+0*t+.8251046025104602*s};return r.alpha!==void 0&&(n.alpha=r.alpha),n},dg={...vs,mode:"prophoto",parse:["prophoto-rgb"],serialize:"prophoto-rgb",fromMode:{xyz50:Tl,rgb:r=>Tl(qs(r))},toMode:{xyz50:bl,rgb:r=>js(bl(r))}},Al=1.09929682680944,ug=.018053968510807,Qr=r=>{const e=Math.abs(r);return e>ug?(Math.sign(r)||1)*(Al*Math.pow(e,.45)-(Al-1)):4.5*r},Il=({x:r,y:e,z:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);let n={mode:"rec2020",r:Qr(r*1.7166511879712683-e*.3556707837763925-.2533662813736599*t),g:Qr(r*-.6666843518324893+e*1.6164812366349395+.0157685458139111*t),b:Qr(r*.0176398574453108-e*.0427706132578085+.9421031212354739*t)};return s!==void 0&&(n.alpha=s),n},wl=1.09929682680944,fg=.018053968510807,Zr=(r=0)=>{let e=Math.abs(r);return e<fg*4.5?r/4.5:(Math.sign(r)||1)*Math.pow((e+wl-1)/wl,1/.45)},Ll=r=>{let e=Zr(r.r),t=Zr(r.g),s=Zr(r.b),n={mode:"xyz65",x:.6369580483012911*e+.1446169035862083*t+.1688809751641721*s,y:.262700212011267*e+.6779980715188708*t+.059301716469862*s,z:0*e+.0280726930490874*t+1.0609850577107909*s};return r.alpha!==void 0&&(n.alpha=r.alpha),n},pg={...vs,mode:"rec2020",fromMode:{xyz65:Il,rgb:r=>Il(Hi(r))},toMode:{xyz65:Ll,rgb:r=>Vi(Ll(r))},parse:["rec2020"],serialize:"rec2020"},Oi=.0037930732552754493,Kc=Math.cbrt(Oi),Jr=r=>Math.cbrt(r)-Kc,gg=r=>{const{r:e,g:t,b:s,alpha:n}=xs(r),a=Jr(.3*e+.622*t+.078*s+Oi),h=Jr(.23*e+.692*t+.078*s+Oi),l=Jr(.2434226892454782*e+.2047674442449682*t+.5518098665095535*s+Oi),u={mode:"xyb",x:(a-h)/2,y:(a+h)/2,b:l-(a+h)/2};return n!==void 0&&(u.alpha=n),u},ea=r=>Math.pow(r+Kc,3),mg=({x:r,y:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);const n=ea(r+e)-Oi,a=ea(e-r)-Oi,h=ea(t+e)-Oi,l=Ss({r:11.031566904639861*n-9.866943908131562*a-.16462299650829934*h,g:-3.2541473810744237*n+4.418770377582723*a-.16462299650829934*h,b:-3.6588512867136815*n+2.7129230459360922*a+1.9459282407775895*h});return s!==void 0&&(l.alpha=s),l},yg={mode:"xyb",channels:["x","y","b","alpha"],parse:["--xyb"],serialize:"--xyb",toMode:{rgb:mg},fromMode:{rgb:gg},ranges:{x:[-.0154,.0281],y:[0,.8453],b:[-.2778,.388]},interpolate:{x:Y,y:Y,b:Y,alpha:{use:Y,fixup:Be}}},vg={mode:"xyz50",parse:["xyz-d50"],serialize:"xyz-d50",toMode:{rgb:js,lab:mo},fromMode:{rgb:qs,lab:go},channels:["x","y","z","alpha"],ranges:{x:[0,.964],y:[0,.999],z:[0,.825]},interpolate:{x:Y,y:Y,z:Y,alpha:{use:Y,fixup:Be}}},xg=r=>{let{x:e,y:t,z:s,alpha:n}=r;e===void 0&&(e=0),t===void 0&&(t=0),s===void 0&&(s=0);let a={mode:"xyz50",x:1.0479298208405488*e+.0229467933410191*t-.0501922295431356*s,y:.0296278156881593*e+.990434484573249*t-.0170738250293851*s,z:-.0092430581525912*e+.0150551448965779*t+.7518742899580008*s};return n!==void 0&&(a.alpha=n),a},Sg=r=>{let{x:e,y:t,z:s,alpha:n}=r;e===void 0&&(e=0),t===void 0&&(t=0),s===void 0&&(s=0);let a={mode:"xyz65",x:.9554734527042182*e-.0230985368742614*t+.0632593086610217*s,y:-.0283697069632081*e+1.0099954580058226*t+.021041398966943*s,z:.0123140016883199*e-.0205076964334779*t+1.3303659366080753*s};return n!==void 0&&(a.alpha=n),a},_g={mode:"xyz65",toMode:{rgb:Vi,xyz50:xg},fromMode:{rgb:Hi,xyz50:Sg},ranges:{x:[0,.95],y:[0,1],z:[0,1.088]},channels:["x","y","z","alpha"],parse:["xyz","xyz-d65"],serialize:"xyz-d65",interpolate:{x:Y,y:Y,z:Y,alpha:{use:Y,fixup:Be}}},Eg=({r,g:e,b:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);const n={mode:"yiq",y:.29889531*r+.58662247*e+.11448223*t,i:.59597799*r-.2741761*e-.32180189*t,q:.21147017*r-.52261711*e+.31114694*t};return s!==void 0&&(n.alpha=s),n},Tg=({y:r,i:e,q:t,alpha:s})=>{r===void 0&&(r=0),e===void 0&&(e=0),t===void 0&&(t=0);const n={mode:"rgb",r:r+.95608445*e+.6208885*t,g:r-.27137664*e-.6486059*t,b:r-1.10561724*e+1.70250126*t};return s!==void 0&&(n.alpha=s),n},bg={mode:"yiq",toMode:{rgb:Tg},fromMode:{rgb:Eg},channels:["y","i","q","alpha"],parse:["--yiq"],serialize:"--yiq",ranges:{i:[-.595,.595],q:[-.522,.522]},interpolate:{y:Y,i:Y,q:Y,alpha:{use:Y,fixup:Be}}},Ag=r=>Math.max(0,Math.min(1,r||0)),Ln=r=>Math.round(Ag(r)*255),Ig=Ns("rgb"),wg=r=>{if(r===void 0)return;let e=Ln(r.r),t=Ln(r.g),s=Ln(r.b);return"#"+(1<<24|e<<16|t<<8|s).toString(16).slice(1)},Lg=r=>{if(r===void 0)return;let e=Ln(r.alpha!==void 0?r.alpha:1);return wg(r)+(256|e).toString(16).slice(1)},Rg=r=>Lg(Ig(r)),Cg=r=>{r[0]===void 0&&(r[0]=0),r[r.length-1]===void 0&&(r[r.length-1]=1);let e=1,t,s,n,a;for(;e<r.length;){if(r[e]===void 0){for(s=e,n=r[e-1],t=e;r[t]===void 0;)t++;for(a=(r[t]-n)/(t-e+1);e<t;)r[e]=n+(e+1-s)*a,e++}else r[e]<r[e-1]&&(r[e]=r[e-1]);e++}return r},Pg=(r=.5)=>e=>r<=0?1:r>=1?0:Math.pow(e,Math.log(.5)/Math.log(r)),hn=r=>typeof r=="function",Ri=r=>r&&typeof r=="object",Rl=r=>typeof r=="number",Dg=(r,e="rgb",t,s)=>{let n=vc(e),a=Ns(e),h=[],l=[],u={};r.forEach(y=>{Array.isArray(y)?(h.push(a(y[0])),l.push(y[1])):Rl(y)||hn(y)?u[l.length]=y:(h.push(a(y)),l.push(void 0))}),Cg(l);let d=n.channels.reduce((y,x)=>{let v;return Ri(t)&&Ri(t[x])&&t[x].fixup?v=t[x].fixup:Ri(n.interpolate[x])&&n.interpolate[x].fixup?v=n.interpolate[x].fixup:v=_=>_,y[x]=v(h.map(_=>_[x])),y},{}),p=n.channels.reduce((y,x)=>{let v;return hn(t)?v=t:Ri(t)&&hn(t[x])?v=t[x]:Ri(t)&&Ri(t[x])&&t[x].use?v=t[x].use:hn(n.interpolate[x])?v=n.interpolate[x]:Ri(n.interpolate[x])&&(v=n.interpolate[x].use),y[x]=v(d[x]),y},{}),g=h.length-1;return y=>{if(y=Math.min(Math.max(0,y),1),y<=l[0])return h[0];if(y>l[g])return h[g];let x=0;for(;l[x]<y;)x++;let v=l[x-1],_=l[x]-v,o=(y-v)/_,c=u[x]||u[0];c!==void 0&&(Rl(c)&&(c=Pg((c-v)/_)),o=c(o));let f=(x-1+o)/g;return n.channels.reduce((m,S)=>{let T=p[S](f);return T!==void 0&&(m[S]=T),m},{mode:e})}},kg=(r,e="rgb",t)=>Dg(r,e,t);ve(dp);ve(vp);ve(xp);ve(Sp);ve(Tp);ve(wc);ve(Cc);ve(kp);ve(Mp);ve(Bp);ve(Np);ve(yo);ve(Gp);ve(vo);ve(Hp);ve(Jp);ve(eg);ve(tg);ve(ng);ve(rg);ve(og);ve(hg);ve(cg);ve(dg);ve(pg);ve(vs);ve(yg);ve(vg);ve(_g);ve(bg);function Mg(r){const e=r>>16&255,t=r>>8&255,s=r&255;return[e/255,t/255,s/255,1]}class we{constructor(e){if(this.symbol=we.symbol,e==null){this.r=0,this.g=0,this.b=0,this.a=1;return}if(e instanceof we){this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a;return}if(typeof e=="string"){const t=Sc(e);if(!t)throw new Error(`Invalid color string value provided: ${e}`);const s=t.mode==="rgb"?t:Ns("rgb")(t);if(s){this.r=me(0,1,s.r),this.g=me(0,1,s.g),this.b=me(0,1,s.b),this.a=me(0,1,s.alpha??1);return}}if(typeof e=="number"){const[t,s,n,a]=Mg(e);this.r=me(0,1,t),this.g=me(0,1,s),this.b=me(0,1,n),this.a=me(0,1,a);return}if(typeof e=="object"&&"r"in e&&"g"in e&&"b"in e){const t=e;this.r=me(0,1,t.r/255),this.g=me(0,1,t.g/255),this.b=me(0,1,t.b/255),this.a=me(0,1,t.a??1);return}throw new Error(`Invalid color value provided: ${e}`)}static lerp(e,t,s,n="lch"){const a=e instanceof we?e:new we(e??void 0),h=t instanceof we?t:new we(t??void 0),l={mode:"rgb",r:a.r,g:a.g,b:a.b},u={mode:"rgb",r:h.r,g:h.g,b:h.b},g=kg([l,u],n??"lch")(s),x=Ns("rgb")(g),v=a.a+(h.a-a.a)*s,_=x?me(0,1,x.r):0,o=x?me(0,1,x.g):0,c=x?me(0,1,x.b):0;return new we({r:_*255,g:o*255,b:c*255,a:me(0,1,v)})}static createLerp(e="lch"){return(t,s,n)=>we.lerp(t,s,n,e)}static createSignal(e,t=we.lerp){return new $i(e,t,void 0,s=>s instanceof we?s:new we(s)).toSignal()}toSymbol(){return this.symbol}gl(){return[this.r,this.g,this.b,this.a]}toUniform(e,t){e.uniform4fv(t,this.gl())}serialize(){const e=Math.round(this.r*255),t=Math.round(this.g*255),s=Math.round(this.b*255),n=me(0,1,this.a).toFixed(3);return`rgba(${e}, ${t}, ${s}, ${n})`}css(){const e=Math.round(this.r*255),t=Math.round(this.g*255),s=Math.round(this.b*255);return`rgb(${e},${t},${s})`}alpha(){return this.a}hex(){return Rg({mode:"rgb",r:this.r,g:this.g,b:this.b,alpha:this.a})}lerp(e,t,s="lch"){return we.lerp(this,e,t,s)}}we.symbol=Symbol.for("@twick/core/types/Color");function Fg(r,e){const t=C.fromDegrees(r);return Jt(t,e).degrees}function Ua(r,e){return C.magnitude(e.m11,e.m12)*r}function Ug(r){if(r===st.Middle)return C.zero;let e=0;r&kt.Left?e=-1:r&kt.Right&&(e=1);let t=0;return r&kt.Top?t=-1:r&kt.Bottom&&(t=1),new C(e,t)}function Og(r){return{core:r,two:r,ui:r,vitePlugin:r}}const cn={shared:{background:"FFFFFF00",range:[0,1/0],size:{x:1920,y:1080}},rendering:{exporter:{name:"@twick/core/wasm"},fps:30,resolutionScale:1,colorSpace:"srgb"},preview:{fps:30,resolutionScale:1}};function Bg(r){var s,n,a;const e={...cn,...r.settings,shared:{...cn.shared,...(s=r.settings)==null?void 0:s.shared},rendering:{...cn.rendering,...(n=r.settings)==null?void 0:n.rendering},preview:{...cn.preview,...(a=r.settings)==null?void 0:a.preview}},t={...e,shared:{...e.shared,background:new we(e.shared.background),size:new C(e.shared.size)}};return{...r,name:r.name??"project",settings:t,plugins:[],logger:new Wu,versions:Og("0.10.4")}}var tt;(function(r){r[r.Playing=0]="Playing",r[r.Rendering=1]="Rendering",r[r.Paused=2]="Paused",r[r.Presenting=3]="Presenting"})(tt||(tt={}));function Ng(r){return r&&(typeof r=="object"||typeof r=="function")&&"toPromise"in r}function Yc(r){return r!==null&&typeof r=="object"&&Symbol.iterator in r&&"next"in r}const $g=`
|
|
19
19
|
This usually happens when you mistakenly reuse a generator that is already
|
|
20
20
|
running.
|
|
21
21
|
|
|
@@ -57,7 +57,7 @@ yield* all(
|
|
|
57
57
|
rect().x(200, 1),
|
|
58
58
|
);
|
|
59
59
|
\`\`\`
|
|
60
|
-
`;
|
|
60
|
+
`;Ei(Wc,rt());function*Wc(){}class ta{get fixed(){return this.fixedTime}get canceled(){var e;return this.isCanceled||(((e=this.parent)==null?void 0:e.canceled)??!1)}get paused(){var e;return this.isPaused||(((e=this.parent)==null?void 0:e.paused)??!1)}constructor(e){this.runner=e,this.children=[],this.time=ps(0),this.parent=null,this.isCanceled=!1,this.isPaused=!1,this.fixedTime=0,this.queue=[],this.runner.task&&(Ue().error({message:`The generator "${fc(this.runner)}" is already being executed by another thread.`,remarks:$g}),this.runner=Wc()),this.runner.task=this}next(){if(this.paused)return{value:null,done:!1};Qu(this);const e=this.runner.next(this.value);return Zu(this),this.value=null,e}update(e){this.paused||(this.time(this.time()+e),this.fixedTime+=e),this.children=this.children.filter(t=>!t.canceled)}spawn(e){return Yc(e)||(e=e()),this.queue.push(e),e}add(e){e.parent=this,e.isCanceled=!1,e.time(this.time()),e.fixedTime=this.fixedTime,this.children.push(e),Hn(e.runner,`unknown ${this.children.length}`)}drain(e){this.queue.forEach(e),this.queue=[]}cancel(){this.runner.return(),this.isCanceled=!0,this.parent=null,this.drain(e=>e.return())}pause(e){this.isPaused=e}}function Gg(r){return typeof(r==null?void 0:r.then)=="function"}Ei(jc,rt());function*jc(r,e){const t=ac(),s=r();Hn(s,"root");const n=new ta(s);e==null||e(n);let a=[n];for(;a.length>0;){const h=[],l=[...a],u=t.deltaTime;for(;l.length>0;){const d=l.pop();if(!d||d.canceled)continue;const p=d.next();if(p.done){d.cancel();continue}if(Yc(p.value)){const g=new ta(p.value);d.value=p.value,d.add(g),l.push(d),l.push(g)}else p.value?(d.value=yield p.value,l.push(d)):(d.update(u),d.drain(g=>{const y=new ta(g);d.add(y),h.unshift(y)}),h.unshift(d))}a=h.filter(d=>!d.canceled),a.length>0&&(yield)}}var Mt;(function(r){r[r.BeforeRender=0]="BeforeRender",r[r.BeginRender=1]="BeginRender",r[r.FinishRender=2]="FinishRender",r[r.AfterRender=3]="AfterRender"})(Mt||(Mt={}));class zg{get onBeforeRender(){return this.beforeRender.subscribable}get onBeginRender(){return this.beginRender.subscribable}get onFinishRender(){return this.finishRender.subscribable}get onAfterRender(){return this.afterRender.subscribable}constructor(e){this.scene=e,this.beforeRender=new Zt,this.beginRender=new Zt,this.finishRender=new Zt,this.afterRender=new Zt,this.scene.onRenderLifecycle.subscribe(([t,s])=>{switch(t){case Mt.BeforeRender:return this.beforeRender.dispatch(s);case Mt.BeginRender:return this.beginRender.dispatch(s);case Mt.FinishRender:return this.finishRender.dispatch(s);case Mt.AfterRender:return this.afterRender.dispatch(s)}}),this.scene.onReset.subscribe(()=>{this.beforeRender.clear(),this.beginRender.clear(),this.finishRender.clear(),this.afterRender.clear()})}}var ze;(function(r){r[r.Initial=0]="Initial",r[r.AfterTransitionIn=1]="AfterTransitionIn",r[r.CanTransitionOut=2]="CanTransitionOut",r[r.Finished=3]="Finished"})(ze||(ze={}));const Hg="resolution",Vg="destinationTexture",Kg="sourceTexture",Cl="time",Yg="deltaTime",Wg="framerate",jg="sourceMatrix",qg="destinationMatrix",Xg=`#version 300 es
|
|
61
61
|
|
|
62
62
|
in vec2 position;
|
|
63
63
|
|
|
@@ -78,7 +78,7 @@ void main() {
|
|
|
78
78
|
|
|
79
79
|
gl_Position = (position_screen - 0.5) * 2.0;
|
|
80
80
|
}
|
|
81
|
-
`;class Ag{constructor(e,t){this.scene=e,this.sharedContext=t,this.gl=null,this.positionBuffer=null,this.sourceTexture=null,this.destinationTexture=null,this.positionLocation=0,this.quadPositions=new Float32Array([-1,1,-1,-1,1,1,1,-1]),this.handleReload=()=>{this.gl&&this.updateViewport()},e.onReloaded.subscribe(this.handleReload)}setup(e){this.gl=e,this.updateViewport(),this.positionBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.bufferData(e.ARRAY_BUFFER,this.quadPositions,e.STATIC_DRAW),e.vertexAttribPointer(this.positionLocation,2,e.FLOAT,!1,0,0),e.enableVertexAttribArray(this.positionLocation),this.sourceTexture=e.createTexture(),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.sourceTexture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),this.destinationTexture=e.createTexture(),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,this.destinationTexture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}teardown(e){e.deleteBuffer(this.positionBuffer),e.disableVertexAttribArray(this.positionLocation),e.deleteTexture(this.sourceTexture),e.deleteTexture(this.destinationTexture),this.positionBuffer=null,this.sourceTexture=null,this.destinationTexture=null,this.gl=null}updateViewport(){if(this.gl){const e=this.scene.getRealSize();this.gl.canvas.width=e.width,this.gl.canvas.height=e.height,this.gl.viewport(0,0,e.width,e.height)}}getGL(){return this.gl??this.sharedContext.borrow(this)}getProgram(e){const t=this.sharedContext.getProgram(e,bg);if(!t)return null;const s=this.scene.getRealSize(),n=this.getGL();return n.useProgram(t),n.uniform1i(n.getUniformLocation(t,vg),0),n.uniform1i(n.getUniformLocation(t,xg),1),n.uniform2f(n.getUniformLocation(t,yg),s.x,s.y),n.uniform1f(n.getUniformLocation(t,Sg),this.scene.playback.deltaTime),n.uniform1f(n.getUniformLocation(t,_g),this.scene.playback.fps),t}copyTextures(e,t){this.copyTexture(t,this.sourceTexture),this.copyTexture(e,this.destinationTexture)}clear(){const e=this.getGL();e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT)}render(){const e=this.getGL();e.drawArrays(e.TRIANGLE_STRIP,0,4)}copyTexture(e,t){const s=this.getGL();s.bindTexture(s.TEXTURE_2D,t),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,e),s.generateMipmap(s.TEXTURE_2D)}}class Ig{get onChanged(){return this.slides.subscribable}constructor(e){this.scene=e,this.slides=new ga([]),this.lookup=new Map,this.collisionLookup=new Set,this.current=null,this.canResume=!1,this.waitsForId=null,this.targetId=null,this.handleReload=()=>{this.lookup.clear(),this.collisionLookup.clear(),this.current=null,this.waitsForId=null,this.targetId=null},this.handleReset=()=>{this.collisionLookup.clear(),this.current=null,this.waitsForId=null},this.handleRecalculated=()=>{this.slides.current=[...this.lookup.values()]},this.scene.onReloaded.subscribe(this.handleReload),this.scene.onReset.subscribe(this.handleReset),this.scene.onRecalculated.subscribe(this.handleRecalculated)}setTarget(e){this.targetId=e}resume(){this.canResume=!0}isWaitingFor(e){return this.waitsForId===e}isWaiting(){return this.waitsForId!==null}didHappen(e){var t;if(this.current===null)return!1;for(const s of this.lookup.keys()){if(s===e)return!0;if(s===((t=this.current)==null?void 0:t.id))return!1}return!1}getCurrent(){return this.current}register(e,t){if(this.waitsForId!==null)throw new Error(`The animation already waits for a slide: ${this.waitsForId}.`);const s=this.toId(e);this.scene.playback.state!==xt.Presenting&&(this.lookup.has(s)||this.lookup.set(s,{id:s,name:e,time:t,scene:this.scene,stack:new Error().stack}),this.collisionLookup.has(e)?this.scene.logger.warn({message:`A slide named "${e}" already exists.`,stack:new Error().stack}):this.collisionLookup.add(e)),this.waitsForId=s,this.current=this.lookup.get(s)??null,this.canResume=!1}shouldWait(e){const t=this.toId(e);if(this.waitsForId!==t)throw new Error(`The animation waits for a different slide: ${this.waitsForId}.`);if(!this.lookup.get(t))throw new Error(`Could not find the "${e}" slide.`);let n=this.canResume;return this.scene.playback.state!==xt.Presenting&&(n=t!==this.targetId),n&&(this.waitsForId=null),!n}toId(e){return`${this.scene.name}:${e}`}}class wg{constructor(e){this.scene=e,this.signals={},this.variables={},this.handleReset=()=>{this.signals={}},e.onReset.subscribe(this.handleReset)}get(e,t){var s;return(s=this.signals)[e]??(s[e]=ss(this.variables[e]??t)),()=>this.signals[e]()}updateSignals(e){this.variables=e,Object.keys(e).map(t=>{t in this.signals&&this.signals[t](e[t])})}}class Lg{get firstFrame(){return this.cache.current.firstFrame}get lastFrame(){return this.firstFrame+this.cache.current.duration}get onCacheChanged(){return this.cache.subscribable}get onReloaded(){return this.reloaded.subscribable}get onRecalculated(){return this.recalculated.subscribable}get onThreadChanged(){return this.thread.subscribable}get onRenderLifecycle(){return this.renderLifecycle.subscribable}get onReset(){return this.afterReset.subscribable}get LifecycleEvents(){return this.logger.warn("LifecycleEvents is deprecated. Use lifecycleEvents instead."),this.lifecycleEvents}get previous(){return this.previousScene}getMediaAssets(){return[]}stopAllMedia(){}constructor(e){this.cache=new ga({firstFrame:0,transitionDuration:0,duration:0,lastFrame:0}),this.reloaded=new Ht,this.recalculated=new Ht,this.thread=new ga(null),this.renderLifecycle=new Ht,this.afterReset=new Ht,this.lifecycleEvents=new mg(this),this.previousScene=null,this.runner=null,this.state=$e.Initial,this.cached=!1,this.counters={},this.name=e.name,this.size=e.size,this.resolutionScale=e.resolutionScale,this.logger=e.logger,this.playback=e.playback,this.runnerFactory=e.config,this.creationStack=e.stack,this.experimentalFeatures=e.experimentalFeatures??!1,mi(this.runnerFactory,et(this.name)),this.variables=new wg(this),this.shaders=new Ag(this,e.sharedWebGLContext),this.slides=new Ig(this),this.previousOnTop=!1}update(){}async render(e){let t=0;do t++,await be.consumePromises(),e.save(),e.clearRect(0,0,e.canvas.width,e.canvas.height),await this.draw(e),e.restore();while(be.hasPromises()&&t<10);t>1&&this.logger.debug(`render iterations: ${t}`)}reload({config:e,size:t,stack:s,resolutionScale:n}={}){e&&(this.runnerFactory=e),t&&(this.size=t),n&&(this.resolutionScale=n),s&&(this.creationStack=s),this.cached=!1,this.reloaded.dispatch()}async recalculate(e){const t=this.cache.current;if(t.firstFrame=this.playback.frame,t.lastFrame=t.firstFrame+t.duration,this.isCached()){e(t.lastFrame),this.cache.current={...t};return}for(t.transitionDuration=-1,await this.reset();!this.canTransitionOut();)t.transitionDuration<0&&this.state===$e.AfterTransitionIn&&(t.transitionDuration=this.playback.frame-t.firstFrame),e(this.playback.frame+1),await this.next();t.transitionDuration===-1&&(t.transitionDuration=0),t.lastFrame=this.playback.frame,t.duration=t.lastFrame-t.firstFrame,await new Promise(s=>setTimeout(s,0)),this.cached=!0,this.cache.current={...t},this.recalculated.dispatch()}async next(){var t;if(!this.runner)return;let e=this.execute(()=>this.runner.next());for(this.update();e.value;){if(fg(e.value)){const s=await e.value.toPromise();e=this.execute(()=>this.runner.next(s))}else if(gg(e.value)){const s=await e.value;e=this.execute(()=>this.runner.next(s))}else this.logger.warn({message:"Invalid value yielded by the scene.",object:e.value}),e=this.execute(()=>this.runner.next(e.value));this.update()}if(be.hasPromises()){const s=await be.consumePromises();this.logger.warn({message:"Tried to access an asynchronous property before the node was ready. Make sure to yield the node before accessing the property.",stack:s[0].stack,inspect:((t=s[0].owner)==null?void 0:t.key)??void 0})}e.done&&(this.state=$e.Finished)}async reset(e=null){this.counters={},this.previousScene=e,this.previousOnTop=!1,this.runner=Dc(()=>this.runnerFactory(this.getView()),t=>{this.thread.current=t}),this.state=$e.AfterTransitionIn,this.afterReset.dispatch(),await this.next()}getSize(){return this.size}getRealSize(){return this.size.mul(this.resolutionScale)}isAfterTransitionIn(){return this.state===$e.AfterTransitionIn}canTransitionOut(){return this.state===$e.CanTransitionOut||this.state===$e.Finished}isFinished(){return this.state===$e.Finished}enterInitial(){this.state===$e.AfterTransitionIn?this.state=$e.Initial:this.logger.warn(`Scene ${this.name} entered initial in an unexpected state: ${this.state}`)}enterAfterTransitionIn(){this.state===$e.Initial?this.state=$e.AfterTransitionIn:this.logger.warn(`Scene ${this.name} transitioned in an unexpected state: ${this.state}`)}enterCanTransitionOut(){this.state===$e.AfterTransitionIn||this.state===$e.Initial?this.state=$e.CanTransitionOut:this.logger.warn(`Scene ${this.name} was marked as finished in an unexpected state: ${this.state}`)}isCached(){return this.cached}execute(e){let t;Tu(this),Cu(this.playback);try{t=e()}finally{Du(this.playback),bu(this)}return t}}function Rg(r){var e;return!!((e=r.prototype)!=null&&e.isClass)}const Cg=({children:r})=>r;function Ce(r,e,t){const{ref:s,children:n,...a}=e,h=Array.isArray(n)?n.flat():n;if(r===Cg)return h;if(Rg(r)){const l=new r({...a,children:h,key:t});return s==null||s(l),l}else return r({...a,ref:s,children:h,key:t})}const yl={invert:{name:"invert"},sepia:{name:"sepia"},grayscale:{name:"grayscale"},brightness:{name:"brightness",default:1},contrast:{name:"contrast",default:1},saturate:{name:"saturate",default:1},hue:{name:"hue-rotate",unit:"deg",scale:1},blur:{name:"blur",transform:!0,unit:"px",scale:1}};class Dg{get name(){return this.props.name}get default(){return this.props.default}constructor(e){this.props={name:"invert",default:0,unit:"%",scale:100,transform:!1,...e,value:e.value??e.default??0},this.value=ss(this.props.value,ne,this)}isActive(){return this.value()!==this.props.default}serialize(e){let t=this.value();return this.props.transform&&(t=ba(t,e)),`${this.props.name}(${t*this.props.scale}${this.props.unit})`}}const Nt=Symbol.for("@twick/2d/decorators/initializers");function zs(r,e){if(!r[Nt])r[Nt]=[];else if(r[Nt]&&!Object.prototype.hasOwnProperty.call(r,Nt)){const t=Object.getPrototypeOf(r);r[Nt]=[...t[Nt]]}r[Nt].push(e)}function Pg(r,e){if(r[Nt])try{r[Nt].forEach(t=>t(r,e))}catch(t){throw t.inspect??(t.inspect=r.key),t}}function J(){return(r,e)=>{zs(r,t=>{const s=Object.getPrototypeOf(t)[e];t[e]=mf(s.bind(t),t)})}}function Aa(r={},e,t){const s={};if(t&&e){const n=r.setter??(e==null?void 0:e[`set${Li(t)}`]);n&&(s.setter=n.bind(e));const a=r.getter??(e==null?void 0:e[`get${Li(t)}`]);a&&(s.getter=a.bind(e));const h=r.tweener??(e==null?void 0:e[`tween${Li(t)}`]);h&&(s.tweener=h.bind(e))}return s}const $t=Symbol.for("@twick/2d/decorators/properties");function Ui(r,e){var t;return((t=r[$t])==null?void 0:t[e])??null}function oo(r,e){let t;return r[$t]?r[$t]&&!Object.prototype.hasOwnProperty.call(r,$t)?r[$t]=t=Object.fromEntries(Object.entries(r[$t]).map(([s,n])=>[s,{...n}])):t=r[$t]:r[$t]=t={},t[e]??(t[e]={cloneable:!0,inspectable:!0,compoundEntries:[]}),t[e]}function Pc(r){return r&&typeof r=="object"?r[$t]??{}:{}}function lo(r,e){Pg(r);for(const[t,s]of Object.entries(Pc(r))){const n=r[t];if(n.reset(),e[t]!==void 0&&n(e[t]),s.compoundEntries!==void 0)for(const[a,h]of s.compoundEntries)h in e&&n[a](e[h])}}function N(){return(r,e)=>{const t=oo(r,e);zs(r,s=>{var l;let n=t.default;const a=s[`getDefault${Li(e)}`];a&&(n=()=>a.call(s,t.default));const h=new Di(n,t.interpolationFunction??ts,s,(l=t.parser)==null?void 0:l.bind(s),Aa(t,s,e));s[e]=h.toSignal()})}}function V(r){return(e,t)=>{const s=Ui(e,t);if(!s){Me().error(`Missing property decorator for "${t.toString()}"`);return}s.default=r}}function ho(r){return(e,t)=>{const s=Ui(e,t);if(!s){Me().error(`Missing property decorator for "${t.toString()}"`);return}s.interpolationFunction=r}}function co(r){return(e,t)=>{const s=Ui(e,t);if(!s){Me().error(`Missing property decorator for "${t.toString()}"`);return}s.parser=r}}function Hs(r){return(e,t)=>{const s=Ui(e,t);if(!s){Me().error(`Missing property decorator for "${t.toString()}"`);return}s.parser=n=>new r(n),"lerp"in r&&(s.interpolationFunction??(s.interpolationFunction=r.lerp))}}function ds(r=!0){return(e,t)=>{const s=Ui(e,t);if(!s){Me().error(`Missing property decorator for "${t.toString()}"`);return}s.cloneable=r}}function kc(r=!0){return(e,t)=>{const s=Ui(e,t);if(!s){Me().error(`Missing property decorator for "${t.toString()}"`);return}s.inspectable=r}}function Mc(r){return(e,t)=>{const s=oo(e,t);s.compound=!0,s.compoundEntries=Object.entries(r),zs(e,n=>{if(!s.parser){Me().error(`Missing parser decorator for "${t.toString()}"`);return}const a=s.default,h=s.parser.bind(n),l=new Jn(s.compoundEntries.map(([u,d])=>{const p=new Di(qi(a,g=>h(g)[u]),ne,n,void 0,Aa(void 0,n,d)).toSignal();return[u,p]}),h,a,s.interpolationFunction??ts,n,Aa(s,n,t));n[t]=l.toSignal()})}}function Qt(r){return(e,t)=>{Mc(typeof r=="object"?r:{x:r?`${r}X`:"x",y:r?`${r}Y`:"y"})(e,t),Hs(R)(e,t)}}var yi=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};class Ft{constructor(e){lo(this,e)}canvasGradient(e){let t;switch(this.type()){case"linear":t=e.createLinearGradient(this.from.x(),this.from.y(),this.to.x(),this.to.y());break;case"conic":t=e.createConicGradient(this.angle(),this.from.x(),this.from.y());break;case"radial":t=e.createRadialGradient(this.from.x(),this.from.y(),this.fromRadius(),this.to.x(),this.to.y(),this.toRadius());break}for(const{offset:s,color:n}of this.stops())t.addColorStop(is(s),new Le(is(n)).serialize());return t}}yi([V("linear"),N()],Ft.prototype,"type",void 0);yi([Qt("from")],Ft.prototype,"from",void 0);yi([Qt("to")],Ft.prototype,"to",void 0);yi([V(0),N()],Ft.prototype,"angle",void 0);yi([V(0),N()],Ft.prototype,"fromRadius",void 0);yi([V(0),N()],Ft.prototype,"toRadius",void 0);yi([V([]),N()],Ft.prototype,"stops",void 0);yi([J()],Ft.prototype,"canvasGradient",null);var uo=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};class Vs{constructor(e){lo(this,e)}canvasPattern(e){return e.createPattern(this.image(),this.repetition())}}uo([N()],Vs.prototype,"image",void 0);uo([V(null),N()],Vs.prototype,"repetition",void 0);uo([J()],Vs.prototype,"canvasPattern",null);function kg(r){return r===null?null:r instanceof Ft||r instanceof Vs?r:new Le(r)}function Ia(r,e){return r===null?"":r instanceof Le?r.serialize():r instanceof Ft?r.canvasGradient(e):r instanceof Vs?r.canvasPattern(e)??"":""}function xl(r,e,t,s,n){if(t.top===0&&t.right===0&&t.bottom===0&&t.left===0){Mg(r,e);return}const a=hi(t.top,t.right,t.left,e),h=hi(t.right,t.top,t.bottom,e),l=hi(t.bottom,t.left,t.right,e),u=hi(t.left,t.bottom,t.top,e);if(s){const d=p=>{const g=p*n;return p-g};r.moveTo(e.left+a,e.top),r.lineTo(e.right-h,e.top),r.bezierCurveTo(e.right-d(h),e.top,e.right,e.top+d(h),e.right,e.top+h),r.lineTo(e.right,e.bottom-l),r.bezierCurveTo(e.right,e.bottom-d(l),e.right-d(l),e.bottom,e.right-l,e.bottom),r.lineTo(e.left+u,e.bottom),r.bezierCurveTo(e.left+d(u),e.bottom,e.left,e.bottom-d(u),e.left,e.bottom-u),r.lineTo(e.left,e.top+a),r.bezierCurveTo(e.left,e.top+d(a),e.left+d(a),e.top,e.left+a,e.top);return}r.moveTo(e.left+a,e.top),r.arcTo(e.right,e.top,e.right,e.bottom,h),r.arcTo(e.right,e.bottom,e.left,e.bottom,l),r.arcTo(e.left,e.bottom,e.left,e.top,u),r.arcTo(e.left,e.top,e.right,e.top,a)}function hi(r,e,t,s){const n=r+e>s.width?s.width*(r/(r+e)):r,a=r+t>s.height?s.height*(r/(r+t)):r;return Math.min(n,a)}function Mg(r,e){r.rect(e.x,e.y,e.width,e.height)}function Fc(r,e,t,s){r.drawImage(e,t.x,t.y,t.width,t.height)}function dr(r,e){r.moveTo(e.x,e.y)}function Kt(r,e){r.lineTo(e.x,e.y)}function Ii(r,e){if(!(e.length<2)){dr(r,e[0]);for(const t of e.slice(1))Kt(r,t)}}function Fg(r,e,t=8){Kt(r,e.addY(-t)),Kt(r,e.addY(t)),Kt(r,e),Kt(r,e.addX(-t)),Ug(r,e,t)}function Ug(r,e,t,s=0,n=Math.PI*2,a=!1){r.arc(e.x,e.y,t,s,n,a)}function Og(r,e,t,s){r.bezierCurveTo(e.x,e.y,t.x,t.y,s.x,s.y)}function Uc(r){return e=>e instanceof r}function Oc(){return(r,e)=>{N()(r,e),co(kg)(r,e),ho(Le.lerp)(r,e),V(null)(r,e)}}function Bc(){return(r,e)=>{N()(r,e),Hs(Le)(r,e)}}function xi(r,e=t=>t){return(t,s)=>{t[`getDefault${Li(s)}`]=function(){this.requestLayoutUpdate();const n=this.element.style[r];this.element.style[r]="";const a=e.call(this,this.styles.getPropertyValue(r));return this.element.style[r]=n,a}}}class Bg extends Di{constructor(e,t){super(e,ts,t);for(const s in yl){const n=yl[s];Object.defineProperty(this.invokable,s,{value:(a,h,l=Ls)=>{var d,p,g;if(a===void 0)return((p=(d=this.get())==null?void 0:d.find(y=>y.name===n.name))==null?void 0:p.value())??n.default??0;let u=(g=this.get())==null?void 0:g.find(y=>y.name===n.name);return u||(u=new Dg(n),this.set([...this.get(),u])),h===void 0?(u.value(a),this.owner):u.value(a,h,l)}})}}*tweener(e,t,s){const n=this.get(),a=is(e);if($g(n,a)){yield*_e(...n.map((u,d)=>u.value(a[d].value(),t,s))),this.set(a);return}for(const u of a)u.value(u.default);const h=a.map(u=>u.value.context.raw()),l=n.length>0&&a.length>0?t/2:t;n.length>0&&(yield*_e(...n.map(u=>u.value(u.default,l,s)))),this.set(a),a.length>0&&(yield*_e(...a.map((u,d)=>u.value(h[d],l,s))))}}function Ng(){return(r,e)=>{const t=oo(r,e);zs(r,s=>{s[e]=new Bg(t.default??[],s).toSignal()})}}function $g(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t].name!==e[t].name)return!1;return!0}const Gg=Symbol.for("@twick/2d/nodeName");function nt(r){return function(e){e.prototype[Gg]=r}}let ur=class{};class zg extends ur{constructor(e,t,s,n,a){super(),this.center=e,this.radius=t,this.from=s,this.to=n,this.counter=a,this.angle=Math.acos(ye(-1,1,s.dot(n))),this.length=Math.abs(this.angle*t);const h=new R(1,1).scale(t);this.points=[e.sub(h),e.add(h)]}get arcLength(){return this.length}draw(e,t,s){const n=this.counter?-1:1,a=this.from.radians+t*this.angle*n,h=this.to.radians-(1-s)*this.angle*n;Math.abs(this.angle)>1e-4&&e.arc(this.center.x,this.center.y,this.radius,a,h,this.counter);const l=R.fromRadians(a),u=R.fromRadians(h);return[{position:this.center.add(l.scale(this.radius)),tangent:this.counter?l:l.flipped,normal:this.counter?l.flipped:l},{position:this.center.add(u.scale(this.radius)),tangent:this.counter?u.flipped:u,normal:this.counter?u.flipped:u}]}getPoint(e){const t=this.counter?-1:1,s=this.from.radians+e*this.angle*t,n=R.fromRadians(s);return{position:this.center.add(n.scale(this.radius)),tangent:this.counter?n:n.flipped,normal:this.counter?n:n.flipped}}}class je{static constant(e){return new je(e)}static linear(e,t){return new je(e,t)}static quadratic(e,t,s){return new je(e,t,s)}static cubic(e,t,s,n){return new je(e,t,s,n)}get degree(){return this.c3!==0?3:this.c2!==0?2:this.c1!==0?1:0}constructor(e,t,s,n){this.c0=e,this.c1=t??0,this.c2=s??0,this.c3=n??0}differentiate(e=1){switch(e){case 0:return this;case 1:return new je(this.c1,2*this.c2,3*this.c3,0);case 2:return new je(2*this.c2,6*this.c3,0,0);case 3:return new je(6*this.c3,0,0,0);default:throw new Error("Unsupported derivative")}}eval(e,t=0){return t!==0?this.differentiate(t).eval(e):this.c3*(e*e*e)+this.c2*(e*e)+this.c1*e+this.c0}split(e){const t=1-e,s=new je(this.c0,this.c1*e,this.c2*e*e,this.c3*e*e*e),n=new je(this.eval(0),t*this.differentiate(1).eval(e),t*t/2*this.differentiate(2).eval(e),t*t*t/6*this.differentiate(3).eval(e));return[s,n]}roots(){switch(this.degree){case 3:return this.solveCubicRoots();case 2:return this.solveQuadraticRoots();case 1:return this.solveLinearRoot();case 0:return[];default:throw new Error(`Unsupported polynomial degree: ${this.degree}`)}}localExtrema(){return this.differentiate().roots()}localExtrema01(){const e=this.localExtrema(),t=[];for(let s=0;s<e.length;s++){const n=e[s];n>=0&&n<=1&&t.push(e[s])}return t}outputRange01(){let e=[this.eval(0),this.eval(1)];const t=s=>{e[1]>e[0]?e=[Math.min(e[0],s),Math.max(e[1],s)]:e=[Math.min(e[1],s),Math.max(e[0],s)]};return this.localExtrema01().forEach(s=>t(this.eval(s))),e}solveCubicRoots(){const e=this.c0,t=this.c1,s=this.c2,n=this.c3,a=e*e,h=e*s,l=t*t,u=(3*h-l)/(3*a),d=(2*l*t-9*h*t+27*a*n)/(27*a*e),p=this.solveDepressedCubicRoots(u,d),g=y=>y-t/(3*e);switch(p.length){case 1:return[g(p[0])];case 2:return[g(p[0]),g(p[1])];case 3:return[g(p[0]),g(p[1]),g(p[2])];default:return[]}}solveDepressedCubicRoots(e,t){if(this.almostZero(e))return[Math.cbrt(-t)];const s=Math.PI*2,n=4*e*e*e+27*t*t;if(n<1e-5){const a=2*Math.sqrt(-e/3),h=3*t/(2*e)*Math.sqrt(-3/e),l=u=>a*Math.cos(1/3*Math.acos(ye(-1,1,h))-s/3*u);return h>=.9999?[l(0),l(2)]:h<=-.9999?[l(1),l(2)]:[l(0),l(1),l(2)]}if(n>0&&e<0){const a=.3333333333333333*Math.acosh(-3*Math.abs(t)/(2*e)*Math.sqrt(-3/e));return[-2*Math.sign(t)*Math.sqrt(-e/3)*Math.cosh(a)]}if(e>0){const a=.3333333333333333*Math.asinh(3*t/(2*e)*Math.sqrt(3/e));return[-2*Math.sqrt(e/3)*Math.sinh(a)]}return[]}solveQuadraticRoots(){const e=this.c2,t=this.c1,s=this.c0,n=t*t-4*e*s;if(this.almostZero(n))return[-t/(2*e)];if(n>=0){const a=Math.sqrt(n),h=(-t-a)/(2*e),l=(-t+a)/(2*e);return[Math.min(h,l),Math.max(h,l)]}return[]}solveLinearRoot(){return[-this.c0/this.c1]}almostZero(e){return Math.abs(0-e)<=Number.EPSILON}}class Ts{constructor(e,t,s,n){this.c0=e,this.c1=t,this.c2=s,this.c3=n,e instanceof je?(this.x=e,this.y=t):n!==void 0?(this.x=new je(e.x,t.x,s.x,n.x),this.y=new je(e.y,t.y,s.y,n.y)):(this.x=new je(e.x,t.x,s.x),this.y=new je(e.y,t.y,s.y))}eval(e,t=0){return new R(this.x.differentiate(t).eval(e),this.y.differentiate(t).eval(e))}split(e){const[t,s]=this.x.split(e),[n,a]=this.y.split(e);return[new Ts(t,n),new Ts(s,a)]}differentiate(e=1){return new Ts(this.x.differentiate(e),this.y.differentiate(e))}evalDerivative(e){return this.differentiate().eval(e)}getBounds(){const e=this.x.outputRange01(),t=this.y.outputRange01();return fe.fromPoints(new R(Math.min(...e),Math.max(...t)),new R(Math.max(...e),Math.min(...t)))}}class Hg{constructor(e,t=20){this.curve=e,this.sampledDistances=[],this.resample(t)}resample(e){this.sampledDistances=[0];let t=0,s=this.curve.eval(0).position;for(let n=1;n<e;n++){const a=n/(e-1),h=this.curve.eval(a),l=s.sub(h.position).magnitude;t+=l,this.sampledDistances.push(t),s=h.position}this.sampledDistances[this.sampledDistances.length-1]=this.curve.arcLength}pointAtDistance(e){return this.curve.eval(this.distanceToT(e))}distanceToT(e){const t=this.sampledDistances.length;e=ye(0,this.curve.arcLength,e);for(let s=0;s<t;s++){const n=this.sampledDistances[s],a=this.sampledDistances[s+1];if(e>=n&&e<=a)return Eu(n,a,s/(t-1),(s+1)/(t-1),e)}return 1}}class Vg extends ur{get arcLength(){return this.length}constructor(e,t){super(),this.curve=e,this.length=t,this.pointSampler=new Hg(this)}getBBox(){return this.curve.getBounds()}eval(e){const t=this.tangent(e);return{position:this.curve.eval(e),tangent:t,normal:t.perpendicular}}getPoint(e){const t=this.pointSampler.pointAtDistance(this.arcLength*e);return{position:t.position,tangent:t.tangent,normal:t.tangent.perpendicular}}transformPoints(e){return this.points.map(t=>Pt(t,e))}tangent(e){return this.curve.evalDerivative(e).normalized}draw(e,t=0,s=1,n=!0){let a=null,h=t,l=s,u=this.points;if(t!==0||s!==1){const g=this.length*t,y=this.length*s;h=this.pointSampler.distanceToT(g),l=this.pointSampler.distanceToT(y);const v=(l-h)/(1-h),[,x]=this.split(h);[a]=x.split(v),u=a.points}n&&dr(e,u[0]),(a??this).doDraw(e);const d=this.tangent(h),p=this.tangent(l);return[{position:u[0],tangent:d,normal:d.perpendicular},{position:u.at(-1),tangent:p,normal:p.perpendicular}]}}var Kg=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};class ai extends Vg{get points(){return[this.p0,this.p1,this.p2,this.p3]}constructor(e,t,s,n){super(new Ts(e,e.flipped.add(t).scale(3),e.scale(3).sub(t.scale(6)).add(s.scale(3)),e.flipped.add(t.scale(3)).sub(s.scale(3)).add(n)),ai.getLength(e,t,s,n)),this.p0=e,this.p1=t,this.p2=s,this.p3=n}split(e){const t=new R(this.p0.x+(this.p1.x-this.p0.x)*e,this.p0.y+(this.p1.y-this.p0.y)*e),s=new R(this.p1.x+(this.p2.x-this.p1.x)*e,this.p1.y+(this.p2.y-this.p1.y)*e),n=new R(this.p2.x+(this.p3.x-this.p2.x)*e,this.p2.y+(this.p3.y-this.p2.y)*e),a=new R(t.x+(s.x-t.x)*e,t.y+(s.y-t.y)*e),h=new R(s.x+(n.x-s.x)*e,s.y+(n.y-s.y)*e),l=new R(a.x+(h.x-a.x)*e,a.y+(h.y-a.y)*e),u=new ai(this.p0,t,a,l),d=new ai(l,h,n,this.p3);return[u,d]}doDraw(e){Og(e,this.p1,this.p2,this.p3)}static getLength(e,t,s,n){return ai.el.setAttribute("d",`M ${e.x} ${e.y} C ${t.x} ${t.y} ${s.x} ${s.y} ${n.x} ${n.y}`),ai.el.getTotalLength()}}Kg([Zn(()=>document.createElementNS("http://www.w3.org/2000/svg","path"))],ai,"el",void 0);class Ki extends ur{constructor(e,t){super(),this.from=e,this.to=t,this.vector=t.sub(e),this.length=this.vector.magnitude,this.normal=this.vector.perpendicular.normalized.safe,this.points=[e,t]}get arcLength(){return this.length}draw(e,t=0,s=1,n=!1){const a=this.from.add(this.vector.scale(t)),h=this.from.add(this.vector.scale(s));return n&&dr(e,a),Kt(e,h),[{position:a,tangent:this.normal.flipped,normal:this.normal},{position:h,tangent:this.normal,normal:this.normal}]}getPoint(e){return{position:this.from.add(this.vector.scale(e)),tangent:this.normal.flipped,normal:this.normal}}}function Yg(r,e,t,s){const n={arcLength:0,segments:[],minSin:1},a=hi(e.top,e.right,e.left,r),h=hi(e.right,e.top,e.bottom,r),l=hi(e.bottom,e.left,e.right,r),u=hi(e.left,e.bottom,e.top,r);let d=new R(r.left+a,r.top),p=new R(r.right-h,r.top);return Yi(n,new Ki(d,p)),d=new R(r.right,r.top+h),p=new R(r.right,r.bottom-l),h>0&&tn(n,d.addX(-h),h,R.down,R.right,t,s),Yi(n,new Ki(d,p)),d=new R(r.right-l,r.bottom),p=new R(r.left+u,r.bottom),l>0&&tn(n,d.addY(-l),l,R.right,R.up,t,s),Yi(n,new Ki(d,p)),d=new R(r.left,r.bottom-u),p=new R(r.left,r.top+a),u>0&&tn(n,d.addX(u),u,R.up,R.left,t,s),Yi(n,new Ki(d,p)),d=new R(r.left+a,r.top),a>0&&tn(n,d.addY(a),a,R.left,R.down,t,s),n}function Yi(r,e){r.segments.push(e),r.arcLength+=e.arcLength}function tn(r,e,t,s,n,a,h){const l=e.add(s.scale(t)),u=e.add(n.scale(t));a?Yi(r,new ai(l,l.add(n.scale(h*t)),u.add(s.scale(h*t)),u)):Yi(r,new zg(e,t,s,n,!1))}function fr(r){return(e,t)=>{Mc({top:r?`${r}Top`:"top",right:r?`${r}Right`:"right",bottom:r?`${r}Bottom`:"bottom",left:r?`${r}Left`:"left"})(e,t),Hs(mt)(e,t)}}function vl(r,e){const t=ye(0,r.arcLength,e);let s=0;for(const n of r.segments){const a=s;if(s+=n.arcLength,s>=t){const h=(t-a)/n.arcLength;return n.getPoint(ye(0,1,h))}}return{position:R.zero,tangent:R.up,normal:R.up}}function Wg(r){let e;return r?typeof r=="string"?e=[{fragment:r}]:Array.isArray(r)?e=r.map(t=>typeof t=="string"?{fragment:t}:t):e=[r]:e=[],!Dn().experimentalFeatures&&e.length>0&&(e=[],Me().log({...Lu("Node uses experimental shaders."),inspect:this.key})),e}function xn(){return Dn()}var de=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},vn;let le=vn=class{get x(){return this.position.x}get y(){return this.position.y}getAbsolutePosition(){const e=this.localToWorld();return new R(e.m41,e.m42)}setAbsolutePosition(e){this.position(qi(e,t=>Pt(new R(t),this.worldToParent())))}getAbsoluteRotation(){const e=this.localToWorld();return R.degrees(e.m11,e.m12)}setAbsoluteRotation(e){this.rotation(qi(e,t=>hg(t,this.worldToParent())))}getAbsoluteScale(){const e=this.localToWorld();return new R(R.magnitude(e.m11,e.m12),R.magnitude(e.m21,e.m22))}setAbsoluteScale(e){this.scale(qi(e,t=>this.getRelativeScale(new R(t))))}getRelativeScale(e){var s;const t=((s=this.parent())==null?void 0:s.absoluteScale())??R.one;return e.div(t)}*tweenCompositeOperation(e,t,s){const n=is(e);n==="source-over"?(yield*this.compositeOverride(1,t,s),this.compositeOverride(0),this.compositeOperation(n)):(this.compositeOperation(n),this.compositeOverride(1),yield*this.compositeOverride(0,t,s))}absoluteOpacity(){var e;return(((e=this.parent())==null?void 0:e.absoluteOpacity())??1)*this.opacity()}hasFilters(){return!!this.filters().find(e=>e.isActive())}hasShadow(){return!!this.shadowColor()&&(this.shadowBlur()>0||this.shadowOffset.x()!==0||this.shadowOffset.y()!==0)}filterString(){let e="";const t=this.compositeToWorld();for(const s of this.filters())s.isActive()&&(e+=" "+s.serialize(t));return e}getSpawner(){return this.children()}setSpawner(e){this.children(e)}setChildren(e){if(this.children.context.raw()!==e){if(this.children.context.setter(e),!Dt(e))this.spawnChildren(!1,e);else if(!this.hasSpawnedChildren)for(const t of this.realChildren)t.parent(null)}}getChildren(){return this.children.context.getter(),this.spawnedChildren()}spawnedChildren(){const e=this.children.context.getter();return Dt(this.children.context.raw())&&this.spawnChildren(!0,e),this.realChildren}sortedChildren(){return[...this.children()].sort((e,t)=>Math.sign(e.zIndex()-t.zIndex()))}constructor({children:e,spawner:t,key:s,...n}){this.compositeOverride=ss(0),this.stateStack=[],this.realChildren=[],this.hasSpawnedChildren=!1,this.parent=ss(null),this.properties=Pc(this);const a=xn();[this.key,this.unregister]=a.registerNode(this,s),this.view2D=a.getView(),this.creationStack=new Error().stack,lo(this,n),t&&Me().warn({message:"Node.spawner() has been deprecated.",remarks:"Use <code>Node.children()</code> instead.",inspect:this.key,stack:new Error().stack}),this.children(t??e)}localToWorld(){const e=this.parent();return e?e.localToWorld().multiply(this.localToParent()):this.localToParent()}worldToLocal(){return this.localToWorld().inverse()}worldToParent(){var e;return((e=this.parent())==null?void 0:e.worldToLocal())??new DOMMatrix}localToParent(){const e=new DOMMatrix;return e.translateSelf(this.x(),this.y()),e.rotateSelf(0,0,this.rotation()),e.scaleSelf(this.scale.x(),this.scale.y()),e.skewXSelf(this.skew.x()),e.skewYSelf(this.skew.y()),e}compositeToWorld(){var e;return((e=this.compositeRoot())==null?void 0:e.localToWorld())??new DOMMatrix}compositeRoot(){var e;return this.composite()?this:((e=this.parent())==null?void 0:e.compositeRoot())??null}compositeToLocal(){const e=this.compositeRoot();if(e){const t=this.worldToLocal();return t.m44=1,e.localToWorld().multiply(t)}return new DOMMatrix}view(){return this.view2D}add(e){return this.insert(e,1/0)}insert(e,t=0){const s=Array.isArray(e)?e:[e];if(s.length===0)return this;const n=this.children(),a=n.slice(0,t);for(const h of s)h instanceof vn&&(a.push(h),h.remove(),h.parent(this));return a.push(...n.slice(t)),this.setParsedChildren(a),this}remove(){const e=this.parent();return e===null?this:(e.removeChild(this),this.parent(null),this)}move(e=1){const t=this.parent();if(e===0||!t)return this;const s=t.children(),n=[];if(e>0)for(let a=0;a<s.length;a++){const h=s[a];if(h===this){const l=a+e;for(;a<l&&a+1<s.length;a++)n[a]=s[a+1]}n[a]=h}else for(let a=s.length-1;a>=0;a--){const h=s[a];if(h===this){const l=a+e;for(;a>l&&a>0;a--)n[a]=s[a-1]}n[a]=h}return t.setParsedChildren(n),this}moveUp(){return this.move(1)}moveDown(){return this.move(-1)}moveToTop(){return this.move(1/0)}moveToBottom(){return this.move(-1/0)}moveTo(e){const t=this.parent();if(!t)return this;const s=t.children().indexOf(this),n=e-s;return this.move(n)}moveBelow(e,t=!1){const s=this.parent();if(!s)return this;if(e.parent()!==s)return Me().error("Cannot position nodes relative to each other if they don't belong to the same parent."),this;const n=s.children(),a=n.indexOf(this),h=n.indexOf(e);if(!t&&a<h)return this;const l=h-a-1;return this.move(l)}moveAbove(e,t=!1){const s=this.parent();if(!s)return this;if(e.parent()!==s)return Me().error("Cannot position nodes relative to each other if they don't belong to the same parent."),this;const n=s.children(),a=n.indexOf(this),h=n.indexOf(e);if(!t&&a>h)return this;const l=h-a+1;return this.move(l)}reparent(e){const t=this.absolutePosition(),s=this.absoluteRotation(),n=this.absoluteScale();e.add(this),this.absolutePosition(t),this.absoluteRotation(s),this.absoluteScale(n)}removeChildren(){for(const e of this.realChildren)e.parent(null);this.setParsedChildren([])}peekChildren(){return this.realChildren}findAll(e){const t=[],s=this.reversedChildren();for(;s.length>0;){const n=s.pop();e(n)&&t.push(n);const a=n.children();for(let h=a.length-1;h>=0;h--)s.push(a[h])}return t}findFirst(e){const t=this.reversedChildren();for(;t.length>0;){const s=t.pop();if(e(s))return s;const n=s.children();for(let a=n.length-1;a>=0;a--)t.push(n[a])}return null}findLast(e){const t=[],s=this.reversedChildren();for(;s.length>0;){const n=s.pop();t.push(n);const a=n.children();for(let h=a.length-1;h>=0;h--)s.push(a[h])}for(;t.length>0;){const n=t.pop();if(e(n))return n}return null}findAncestor(e){let t=this.parent();for(;t;){if(e(t))return t;t=t.parent()}return null}childAs(e){return this.children()[e]??null}childrenAs(){return this.children()}parentAs(){return this.parent()??null}dispose(){if(this.unregister){this.stateStack=[],this.unregister(),this.unregister=null;for(const{signal:e}of this)e==null||e.context.dispose();for(const e of this.realChildren)e.dispose()}}clone(e={}){const t={...e};Dt(this.children.context.raw())?t.children??(t.children=this.children.context.raw()):this.children().length>0&&(t.children??(t.children=this.children().map(s=>s.clone())));for(const{key:s,meta:n,signal:a}of this)if(!(!n.cloneable||s in t))if(n.compound)for(const[h,l]of n.compoundEntries){if(l in t)continue;const u=a[h];u.context.isInitial()||(t[l]=u.context.raw())}else a.context.isInitial()||(t[s]=a.context.raw());return this.instantiate(t)}snapshotClone(e={}){const t={...this.getState(),...e};return this.children().length>0&&(t.children??(t.children=this.children().map(s=>s.snapshotClone()))),this.instantiate(t)}reactiveClone(e={}){const t={...e};this.children().length>0&&(t.children??(t.children=this.children().map(s=>s.reactiveClone())));for(const{key:s,meta:n,signal:a}of this)!n.cloneable||s in t||(t[s]=()=>a());return this.instantiate(t)}instantiate(e={}){return new this.constructor(e)}setParsedChildren(e){this.children.context.setter(e),this.realChildren=e}spawnChildren(e,t){const s=this.parseChildren(t),n=new Set;for(const a of s){const h=a.parent.context.raw();h&&h!==this&&h.removeChild(a),n.add(a.key),a.parent(this)}for(const a of this.realChildren)n.has(a.key)||a.parent(null);this.hasSpawnedChildren=e,this.realChildren=s}parseChildren(e){const t=[],s=Array.isArray(e)?e:[e];for(const n of s)n instanceof vn&&t.push(n);return t}removeChild(e){this.setParsedChildren(this.children().filter(t=>t!==e))}requiresCache(){return this.cache()||this.opacity()<1||this.compositeOperation()!=="source-over"||this.hasFilters()||this.hasShadow()||this.shaders().length>0}cacheCanvas(){const e=document.createElement("canvas").getContext("2d");if(!e)throw new Error("Could not create a cache canvas");return e}async cachedCanvas(){const e=this.cacheCanvas(),t=this.worldSpaceCacheBBox(),s=this.localToWorld();return e.canvas.width=t.width,e.canvas.height=t.height,e.setTransform(s.a,s.b,s.c,s.d,s.e-t.x,s.f-t.y),await this.draw(e),e}getCacheBBox(){return new fe}cacheBBox(){const e=this.getCacheBBox(),t=this.children(),s=this.cachePadding();if(t.length===0)return e.addSpacing(s);const n=e.corners;for(const h of t){const l=h.fullCacheBBox(),u=h.localToParent();n.push(...l.corners.map(d=>Pt(d,u)))}return fe.fromPoints(...n).addSpacing(s)}fullCacheBBox(){const e=this.compositeToLocal(),t=Vt(this.shadowOffset(),e),s=ba(this.shadowBlur(),e),n=this.cacheBBox().expand(this.filters.blur()*2+s);return t.x<0?(n.x+=t.x,n.width-=t.x):n.width+=t.x,t.y<0?(n.y+=t.y,n.height-=t.y):n.height+=t.y,n}worldSpaceCacheBBox(){const e=fe.fromSizeCentered(this.view().size()),t=fe.fromPoints(...e.transformCorners(this.view().localToWorld())),s=fe.fromPoints(...this.cacheBBox().transformCorners(this.localToWorld())).pixelPerfect.expand(2);return t.intersection(s)}parentWorldSpaceCacheBBox(){var e;return((e=this.findAncestor(t=>t.requiresCache()))==null?void 0:e.worldSpaceCacheBBox())??new fe(R.zero,xn().getSize())}setupDrawFromCache(e){if(e.globalCompositeOperation=this.compositeOperation(),e.globalAlpha*=this.opacity(),this.hasFilters()&&(e.filter=this.filterString()),this.hasShadow()){const s=this.compositeToWorld(),n=Vt(this.shadowOffset(),s),a=ba(this.shadowBlur(),s);e.shadowColor=this.shadowColor().serialize(),e.shadowBlur=a,e.shadowOffsetX=n.x,e.shadowOffsetY=n.y}const t=this.worldToLocal();e.transform(t.a,t.b,t.c,t.d,t.e,t.f)}renderFromSource(e,t,s,n){this.setupDrawFromCache(e);const a=this.compositeOverride();e.drawImage(t,s,n),a>0&&(e.save(),e.globalAlpha*=a,e.globalCompositeOperation="source-over",e.drawImage(t,s,n),e.restore())}shaderCanvas(e,t){var g,y;const s=this.shaders();if(s.length===0)return null;const n=xn(),a=n.getRealSize(),h=this.parentWorldSpaceCacheBBox(),l=new DOMMatrix().scaleSelf(a.width/h.width,a.height/-h.height).translateSelf(h.x/-a.width,h.y/a.height-1),u=this.worldSpaceCacheBBox(),d=new DOMMatrix().scaleSelf(a.width/u.width,a.height/-u.height).translateSelf(u.x/-a.width,u.y/a.height-1).invertSelf(),p=n.shaders.getGL();n.shaders.copyTextures(e,t),n.shaders.clear();for(const v of s){const x=n.shaders.getProgram(v.fragment);if(x){if(v.uniforms)for(const[E,o]of Object.entries(v.uniforms)){const c=p.getUniformLocation(x,E);if(c===null)continue;const f=is(o);typeof f=="number"?p.uniform1f(c,f):"toUniform"in f?f.toUniform(p,c):f.length===1?p.uniform1f(c,f[0]):f.length===2?p.uniform2f(c,f[0],f[1]):f.length===3?p.uniform3f(c,f[0],f[1],f[2]):f.length===4&&p.uniform4f(c,f[0],f[1],f[2],f[3])}p.uniform1f(p.getUniformLocation(x,ml),this.view2D.globalTime()),p.uniform1i(p.getUniformLocation(x,ml),n.playback.frame),p.uniformMatrix4fv(p.getUniformLocation(x,Eg),!1,d.toFloat32Array()),p.uniformMatrix4fv(p.getUniformLocation(x,Tg),!1,l.toFloat32Array()),(g=v.setup)==null||g.call(v,p,x),n.shaders.render(),(y=v.teardown)==null||y.call(v,p,x)}}return p.canvas}async render(e){if(!(this.absoluteOpacity()<=0)){if(e.save(),this.transformContext(e),this.requiresCache()){const t=this.worldSpaceCacheBBox();if(t.width!==0&&t.height!==0){const s=(await this.cachedCanvas()).canvas,n=this.shaderCanvas(e.canvas,s);n?this.renderFromSource(e,n,0,0):this.renderFromSource(e,s,t.position.x,t.position.y)}}else await this.draw(e);e.restore()}}async draw(e){await this.drawChildren(e)}async drawChildren(e){for(const t of this.sortedChildren())await t.render(e)}drawOverlay(e,t){const s=this.cacheBBox().transformCorners(t),n=this.getCacheBBox().transformCorners(t);e.strokeStyle="white",e.lineWidth=1,e.beginPath(),Ii(e,s),e.closePath(),e.stroke(),e.strokeStyle="blue",e.beginPath(),Ii(e,n),e.closePath(),e.stroke()}transformContext(e){const t=this.localToParent();e.transform(t.a,t.b,t.c,t.d,t.e,t.f)}hit(e){let t=null;const s=Pt(e,this.localToParent().inverse()),n=this.children();for(let a=n.length-1;a>=0&&(t=n[a].hit(s),!t);a--);return t}collectAsyncResources(){for(const e of this.children())e.collectAsyncResources()}async toPromise(){do await be.consumePromises(),this.collectAsyncResources();while(be.hasPromises());return this}getState(){const e={};for(const{key:t,meta:s,signal:n}of this)!s.cloneable||t in e||(e[t]=n());return e}applyState(e,t,s=Ls){if(t===void 0)for(const a in e){const h=this.signalByKey(a);h&&h(e[a])}const n=[];for(const a in e){const h=this.signalByKey(a);e[a]!==h.context.raw()&&n.push(h(e[a],t,s))}return _e(...n)}save(){this.stateStack.push(this.getState())}restore(e,t=Ls){const s=this.stateStack.pop();if(s!==void 0)return this.applyState(s,e,t)}*[Symbol.iterator](){for(const e in this.properties){const t=this.properties[e],s=this.signalByKey(e);yield{meta:t,signal:s,key:e}}}signalByKey(e){return this[e]}reversedChildren(){const e=this.children(),t=[];for(let s=e.length-1;s>=0;s--)t.push(e[s]);return t}};de([Qt()],le.prototype,"position",void 0);de([Hs(R),ds(!1),N()],le.prototype,"absolutePosition",void 0);de([V(0),N()],le.prototype,"rotation",void 0);de([ds(!1),N()],le.prototype,"absoluteRotation",void 0);de([V(R.one),Qt("scale")],le.prototype,"scale",void 0);de([V(R.zero),Qt("skew")],le.prototype,"skew",void 0);de([Hs(R),ds(!1),N()],le.prototype,"absoluteScale",void 0);de([V(0),N()],le.prototype,"zIndex",void 0);de([V(!1),N()],le.prototype,"cache",void 0);de([fr("cachePadding")],le.prototype,"cachePadding",void 0);de([V(!1),N()],le.prototype,"composite",void 0);de([V("source-over"),N()],le.prototype,"compositeOperation",void 0);de([et()],le.prototype,"tweenCompositeOperation",null);de([V(1),co(r=>ye(0,1,r)),N()],le.prototype,"opacity",void 0);de([J()],le.prototype,"absoluteOpacity",null);de([Ng()],le.prototype,"filters",void 0);de([V("#0000"),Bc()],le.prototype,"shadowColor",void 0);de([V(0),N()],le.prototype,"shadowBlur",void 0);de([Qt("shadowOffset")],le.prototype,"shadowOffset",void 0);de([V([]),co(Wg),N()],le.prototype,"shaders",void 0);de([J()],le.prototype,"hasFilters",null);de([J()],le.prototype,"hasShadow",null);de([J()],le.prototype,"filterString",null);de([kc(!1),ds(!1),N()],le.prototype,"spawner",void 0);de([kc(!1),ds(!1),N()],le.prototype,"children",void 0);de([J()],le.prototype,"spawnedChildren",null);de([J()],le.prototype,"sortedChildren",null);de([J()],le.prototype,"localToWorld",null);de([J()],le.prototype,"worldToLocal",null);de([J()],le.prototype,"worldToParent",null);de([J()],le.prototype,"localToParent",null);de([J()],le.prototype,"compositeToWorld",null);de([J()],le.prototype,"compositeRoot",null);de([J()],le.prototype,"compositeToLocal",null);de([J()],le.prototype,"cacheCanvas",null);de([J()],le.prototype,"cachedCanvas",null);de([J()],le.prototype,"cacheBBox",null);de([J()],le.prototype,"fullCacheBBox",null);de([J()],le.prototype,"worldSpaceCacheBBox",null);de([J()],le.prototype,"parentWorldSpaceCacheBBox",null);le=vn=de([nt("Node")],le);le.prototype.isClass=!0;var Z=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},Sn;let q=Sn=class extends le{get columnGap(){return this.gap.x}get rowGap(){return this.gap.y}getX(){return this.isLayoutRoot()?this.x.context.getter():this.computedPosition().x}setX(e){this.x.context.setter(e)}getY(){return this.isLayoutRoot()?this.y.context.getter():this.computedPosition().y}setY(e){this.y.context.setter(e)}get width(){return this.size.x}get height(){return this.size.y}getWidth(){return this.computedSize().width}setWidth(e){this.width.context.setter(e)}*tweenWidth(e,t,s,n){const a=this.desiredSize().x,h=typeof a!="number"||typeof e!="number";let l;h?l=this.size.x():l=a;let u;h?(this.size.x(e),u=this.size.x()):u=e,this.size.x(l),h&&this.lockSize(),yield*_s(t,d=>this.size.x(n(l,u,s(d)))),this.size.x(e),h&&this.releaseSize()}getHeight(){return this.computedSize().height}setHeight(e){this.height.context.setter(e)}*tweenHeight(e,t,s,n){const a=this.desiredSize().y,h=typeof a!="number"||typeof e!="number";let l;h?l=this.size.y():l=a;let u;h?(this.size.y(e),u=this.size.y()):u=e,this.size.y(l),h&&this.lockSize(),yield*_s(t,d=>this.size.y(n(l,u,s(d)))),this.size.y(e),h&&this.releaseSize()}desiredSize(){return{x:this.width.context.getter(),y:this.height.context.getter()}}*tweenSize(e,t,s,n){const a=this.desiredSize();let h;typeof a.x!="number"||typeof a.y!="number"?h=this.size():h=new R(a);let l;typeof e=="object"&&typeof e.x=="number"&&typeof e.y=="number"?l=new R(e):(this.size(e),l=this.size()),this.size(h),this.lockSize(),yield*_s(t,u=>this.size(n(h,l,s(u)))),this.releaseSize(),this.size(e)}constructor(e){super(e),this.element.dataset.motionCanvasKey=this.key}lockSize(){this.sizeLockCounter(this.sizeLockCounter()+1)}releaseSize(){this.sizeLockCounter(this.sizeLockCounter()-1)}parentTransform(){return this.findAncestor(Uc(Sn))}anchorPosition(){const e=this.computedSize(),t=this.offset();return e.scale(.5).mul(t)}layoutEnabled(){var e;return this.layout()??((e=this.parentTransform())==null?void 0:e.layoutEnabled())??!1}isLayoutRoot(){var e;return!this.layoutEnabled()||!((e=this.parentTransform())!=null&&e.layoutEnabled())}localToParent(){const e=super.localToParent(),t=this.offset();if(!t.exactlyEquals(R.zero)){const s=this.size().mul(t).scale(-.5);e.translateSelf(s.x,s.y)}return e}scalingRotationMatrix(){const e=new DOMMatrix;e.rotateSelf(0,0,this.rotation()),e.scaleSelf(this.scale.x(),this.scale.y());const t=this.offset();if(!t.exactlyEquals(R.zero)){const s=this.size().mul(t).scale(-.5);e.translateSelf(s.x,s.y)}return e}getComputedLayout(){return new fe(this.element.getBoundingClientRect())}computedPosition(){this.requestLayoutUpdate();const e=this.getComputedLayout(),t=new R(e.x+e.width/2*this.offset.x(),e.y+e.height/2*this.offset.y()),s=this.parentTransform();if(s){const n=s.getComputedLayout();t.x-=n.x+(n.width-e.width)/2,t.y-=n.y+(n.height-e.height)/2}return t}computedSize(){return this.requestLayoutUpdate(),this.getComputedLayout().size}requestLayoutUpdate(){const e=this.parentTransform();this.appendedToView()?(e==null||e.requestFontUpdate(),this.updateLayout()):e.requestLayoutUpdate()}appendedToView(){const e=this.isLayoutRoot();return e&&this.view().element.append(this.element),e}updateLayout(){if(this.applyFont(),this.applyFlex(),this.layoutEnabled()){const e=this.layoutChildren();for(const t of e)t.updateLayout()}}layoutChildren(){const e=[...this.children()],t=[],s=[];for(;e.length;){const n=e.shift();n instanceof Sn?n.layoutEnabled()&&(t.push(n),s.push(n.element)):n&&e.unshift(...n.children())}return this.element.replaceChildren(...s),t}requestFontUpdate(){var e;this.appendedToView(),(e=this.parentTransform())==null||e.requestFontUpdate(),this.applyFont()}getCacheBBox(){return fe.fromSizeCentered(this.computedSize())}async draw(e){var t;if(await((t=document.fonts)==null?void 0:t.ready),this.clip()){const s=this.computedSize();if(s.width===0||s.height===0)return;e.beginPath(),e.rect(s.width/-2,s.height/-2,s.width,s.height),e.closePath(),e.clip()}await this.drawChildren(e)}drawOverlay(e,t){const s=this.computedSize(),n=s.mul(this.offset()).scale(.5),a=Pt(n,t),h=fe.fromSizeCentered(s),l=h.transformCorners(t),u=h.addSpacing(this.padding().scale(-1)).transformCorners(t),d=h.addSpacing(this.margin()).transformCorners(t);e.beginPath(),Ii(e,d),Ii(e,l),e.closePath(),e.fillStyle="rgba(255,193,125,0.6)",e.fill("evenodd"),e.beginPath(),Ii(e,l),Ii(e,u),e.closePath(),e.fillStyle="rgba(180,255,147,0.6)",e.fill("evenodd"),e.beginPath(),Ii(e,l),e.closePath(),e.lineWidth=1,e.strokeStyle="white",e.stroke(),e.beginPath(),Fg(e,a),e.stroke()}getOriginDelta(e){const t=this.computedSize().scale(.5),s=this.offset().mul(t);return e===Ze.Middle?s.flipped:cg(e).mul(t).sub(s)}moveOffset(e){const t=this.computedSize().scale(.5),s=this.offset().mul(t),n=e.mul(t);this.offset(e),this.position(this.position().add(n).sub(s))}parsePixels(e){return e===null?"":`${e}px`}parseLength(e){return e===null?"":typeof e=="string"?e:`${e}px`}applyFlex(){this.element.style.position=this.isLayoutRoot()?"absolute":"relative";const e=this.desiredSize();this.element.style.width=this.parseLength(e.x),this.element.style.height=this.parseLength(e.y),this.element.style.maxWidth=this.parseLength(this.maxWidth()),this.element.style.minWidth=this.parseLength(this.minWidth()),this.element.style.maxHeight=this.parseLength(this.maxHeight()),this.element.style.minHeight=this.parseLength(this.minHeight()),this.element.style.aspectRatio=this.ratio()===null?"":this.ratio().toString(),this.element.style.marginTop=this.parsePixels(this.margin.top()),this.element.style.marginBottom=this.parsePixels(this.margin.bottom()),this.element.style.marginLeft=this.parsePixels(this.margin.left()),this.element.style.marginRight=this.parsePixels(this.margin.right()),this.element.style.paddingTop=this.parsePixels(this.padding.top()),this.element.style.paddingBottom=this.parsePixels(this.padding.bottom()),this.element.style.paddingLeft=this.parsePixels(this.padding.left()),this.element.style.paddingRight=this.parsePixels(this.padding.right()),this.element.style.flexDirection=this.direction(),this.element.style.flexBasis=this.parseLength(this.basis()),this.element.style.flexWrap=this.wrap(),this.element.style.justifyContent=this.justifyContent(),this.element.style.alignContent=this.alignContent(),this.element.style.alignItems=this.alignItems(),this.element.style.alignSelf=this.alignSelf(),this.element.style.columnGap=this.parseLength(this.gap.x()),this.element.style.rowGap=this.parseLength(this.gap.y()),this.sizeLockCounter()>0?(this.element.style.flexGrow="0",this.element.style.flexShrink="0"):(this.element.style.flexGrow=this.grow().toString(),this.element.style.flexShrink=this.shrink().toString())}applyFont(){if((document.fonts?Array.from(document.fonts).filter(s=>s.status==="loading"):[]).length>0&&be.collectPromise((async()=>{var s;await((s=document.fonts)==null?void 0:s.ready)})()),this.element.style.fontFamily=this.fontFamily.isInitial()?"":this.fontFamily(),this.element.style.fontSize=this.fontSize.isInitial()?"":`${this.fontSize()}px`,this.element.style.fontStyle=this.fontStyle.isInitial()?"":this.fontStyle(),this.lineHeight.isInitial())this.element.style.lineHeight="";else{const s=this.lineHeight();this.element.style.lineHeight=typeof s=="string"?(parseFloat(s)/100).toString():`${s}px`}if(this.element.style.fontWeight=this.fontWeight.isInitial()?"":this.fontWeight().toString(),this.element.style.letterSpacing=this.letterSpacing.isInitial()?"":`${this.letterSpacing()}px`,this.element.style.textAlign=this.textAlign.isInitial()?"":this.textAlign(),this.textWrap.isInitial()){this.element.style.whiteSpace="";return}const t=this.textWrap();if(typeof t=="boolean"){this.element.style.whiteSpace=t?"normal":"nowrap";return}if(t==="pre"){this.element.style.whiteSpace=t;return}if(t==="balance"){this.element.style.whiteSpace="normal",this.element.style.textWrap=t;return}}dispose(){var e;super.dispose(),(e=this.sizeLockCounter)==null||e.context.dispose(),this.element&&(this.element.remove(),this.element.innerHTML=""),this.element=null,this.styles=null}hit(e){const t=Pt(e,this.localToParent().inverse());return this.cacheBBox().includes(t)?super.hit(e)??this:null}};Z([V(null),ho(Pu),N()],q.prototype,"layout",void 0);Z([V(null),N()],q.prototype,"maxWidth",void 0);Z([V(null),N()],q.prototype,"maxHeight",void 0);Z([V(null),N()],q.prototype,"minWidth",void 0);Z([V(null),N()],q.prototype,"minHeight",void 0);Z([V(null),N()],q.prototype,"ratio",void 0);Z([fr("margin")],q.prototype,"margin",void 0);Z([fr("padding")],q.prototype,"padding",void 0);Z([V("row"),N()],q.prototype,"direction",void 0);Z([V(null),N()],q.prototype,"basis",void 0);Z([V(0),N()],q.prototype,"grow",void 0);Z([V(1),N()],q.prototype,"shrink",void 0);Z([V("nowrap"),N()],q.prototype,"wrap",void 0);Z([V("start"),N()],q.prototype,"justifyContent",void 0);Z([V("normal"),N()],q.prototype,"alignContent",void 0);Z([V("stretch"),N()],q.prototype,"alignItems",void 0);Z([V("auto"),N()],q.prototype,"alignSelf",void 0);Z([V(0),Qt({x:"columnGap",y:"rowGap"})],q.prototype,"gap",void 0);Z([xi("font-family"),N()],q.prototype,"fontFamily",void 0);Z([xi("font-size",parseFloat),N()],q.prototype,"fontSize",void 0);Z([xi("font-style"),N()],q.prototype,"fontStyle",void 0);Z([xi("font-weight",parseInt),N()],q.prototype,"fontWeight",void 0);Z([xi("line-height",parseFloat),N()],q.prototype,"lineHeight",void 0);Z([xi("letter-spacing",r=>r==="normal"?0:parseFloat(r)),N()],q.prototype,"letterSpacing",void 0);Z([xi("white-space",r=>r==="pre"?"pre":r==="normal"),N()],q.prototype,"textWrap",void 0);Z([V("inherit"),N()],q.prototype,"textDirection",void 0);Z([xi("text-align"),N()],q.prototype,"textAlign",void 0);Z([V({x:null,y:null}),Qt({x:"width",y:"height"})],q.prototype,"size",void 0);Z([et()],q.prototype,"tweenWidth",null);Z([et()],q.prototype,"tweenHeight",null);Z([J()],q.prototype,"desiredSize",null);Z([et()],q.prototype,"tweenSize",null);Z([Qt("offset")],q.prototype,"offset",void 0);Z([Zt(Ze.Middle)],q.prototype,"middle",void 0);Z([Zt(Ze.Top)],q.prototype,"top",void 0);Z([Zt(Ze.Bottom)],q.prototype,"bottom",void 0);Z([Zt(Ze.Left)],q.prototype,"left",void 0);Z([Zt(Ze.Right)],q.prototype,"right",void 0);Z([Zt(Ze.TopLeft)],q.prototype,"topLeft",void 0);Z([Zt(Ze.TopRight)],q.prototype,"topRight",void 0);Z([Zt(Ze.BottomLeft)],q.prototype,"bottomLeft",void 0);Z([Zt(Ze.BottomRight)],q.prototype,"bottomRight",void 0);Z([V(!1),N()],q.prototype,"clip",void 0);Z([V(0),N()],q.prototype,"sizeLockCounter",void 0);Z([J()],q.prototype,"parentTransform",null);Z([J()],q.prototype,"anchorPosition",null);Z([J()],q.prototype,"layoutEnabled",null);Z([J()],q.prototype,"isLayoutRoot",null);Z([J()],q.prototype,"scalingRotationMatrix",null);Z([J()],q.prototype,"computedPosition",null);Z([J()],q.prototype,"computedSize",null);Z([J()],q.prototype,"requestLayoutUpdate",null);Z([J()],q.prototype,"appendedToView",null);Z([J()],q.prototype,"updateLayout",null);Z([J()],q.prototype,"layoutChildren",null);Z([J()],q.prototype,"requestFontUpdate",null);Z([J()],q.prototype,"applyFlex",null);Z([J()],q.prototype,"applyFont",null);q=Sn=Z([nt("Layout")],q);function Zt(r){return(e,t)=>{N()(e,t),ds(!1)(e,t);const s=Ui(e,t);s.parser=n=>new R(n),s.getter=function(){const n=this.computedSize().getOriginOffset(r);return Pt(n,this.localToParent())},s.setter=function(n){return this.position(qi(n,a=>{const h=this.getOriginDelta(r);return Vt(h,this.scalingRotationMatrix()).flipped.add(a)})),this}}}zs(q.prototype,r=>{r.element=document.createElement("div"),r.element.style.display="flex",r.element.style.boxSizing="border-box",r.styles=getComputedStyle(r.element)});var rt=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};let ze=class extends q{rippleSize(){return Yh(this.rippleStrength(),0,50)}constructor(e){super(e),this.rippleStrength=ss(0)}applyText(e){e.direction=this.textDirection(),this.element.dir=this.textDirection()}applyStyle(e){e.fillStyle=Ia(this.fill(),e),e.strokeStyle=Ia(this.stroke(),e),e.lineWidth=this.lineWidth(),e.lineJoin=this.lineJoin(),e.lineCap=this.lineCap(),e.setLineDash(this.lineDash()),e.lineDashOffset=this.lineDashOffset(),this.antialiased()||(e.filter="url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxmaWx0ZXIgaWQ9ImZpbHRlciIgeD0iMCIgeT0iMCIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj48ZmVDb21wb25lbnRUcmFuc2Zlcj48ZmVGdW5jUiB0eXBlPSJpZGVudGl0eSIvPjxmZUZ1bmNHIHR5cGU9ImlkZW50aXR5Ii8+PGZlRnVuY0IgdHlwZT0iaWRlbnRpdHkiLz48ZmVGdW5jQSB0eXBlPSJkaXNjcmV0ZSIgdGFibGVWYWx1ZXM9IjAgMSIvPjwvZmVDb21wb25lbnRUcmFuc2Zlcj48L2ZpbHRlcj48L3N2Zz4=#filter)")}async draw(e){this.drawShape(e),this.clip()&&e.clip(this.getPath()),await this.drawChildren(e)}drawShape(e){const t=this.getPath(),s=this.lineWidth()>0&&this.stroke()!==null,n=this.fill()!==null;e.save(),this.applyStyle(e),this.drawRipple(e),this.strokeFirst()?(s&&e.stroke(t),n&&e.fill(t)):(n&&e.fill(t),s&&e.stroke(t)),e.restore()}getCacheBBox(){return super.getCacheBBox().expand(this.lineWidth()/2)}getPath(){return new Path2D}getRipplePath(){return new Path2D}drawRipple(e){const t=this.rippleStrength();if(t>0){const s=this.getRipplePath();e.save(),e.globalAlpha*=ne(.54,0,t),e.fill(s),e.restore()}}*ripple(e=1){this.rippleStrength(0),yield*this.rippleStrength(1,e,Wh),this.rippleStrength(0)}};rt([Oc()],ze.prototype,"fill",void 0);rt([Oc()],ze.prototype,"stroke",void 0);rt([V(!1),N()],ze.prototype,"strokeFirst",void 0);rt([V(0),N()],ze.prototype,"lineWidth",void 0);rt([V("miter"),N()],ze.prototype,"lineJoin",void 0);rt([V("butt"),N()],ze.prototype,"lineCap",void 0);rt([V([]),N()],ze.prototype,"lineDash",void 0);rt([V(0),N()],ze.prototype,"lineDashOffset",void 0);rt([V(!0),N()],ze.prototype,"antialiased",void 0);rt([J()],ze.prototype,"rippleSize",null);rt([J()],ze.prototype,"getPath",null);rt([et()],ze.prototype,"ripple",null);ze=rt([nt("Shape")],ze);var vt=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};let Je=class extends ze{desiredSize(){return this.childrenBBox().size}constructor(e){super(e),this.canHaveSubpath=!1}percentageToDistance(e){return ye(0,this.baseArcLength(),this.startOffset()+this.offsetArcLength()*e)}distanceToPercentage(e){return(e-this.startOffset())/this.offsetArcLength()}baseArcLength(){return this.profile().arcLength}offsetArcLength(){const e=this.startOffset(),t=this.endOffset(),s=this.baseArcLength();return ye(0,s,s-e-t)}arcLength(){return this.offsetArcLength()*Math.abs(this.start()-this.end())}completion(){return Math.abs(this.start()-this.end())}processSubpath(e,t,s){}curveDrawingInfo(){const e=new Path2D;let t=new Path2D;const s=this.profile();let n=this.percentageToDistance(this.start()),a=this.percentageToDistance(this.end());n>a&&([n,a]=[a,n]);const h=a-n,l=Math.min(h/2,this.arrowSize());this.startArrow()&&(n+=l/2),this.endArrow()&&(a-=l/2);let u=0,d=null,p=null,g=null,y=null;for(const v of s.segments){const x=u;if(u+=v.arcLength,u<n)continue;const E=(n-x)/v.arcLength,o=(a-x)/v.arcLength,c=ye(0,1,E),f=ye(0,1,o);this.canHaveSubpath&&g&&!v.getPoint(0).position.equals(g)&&(e.addPath(t),this.processSubpath(t,d,g),t=new Path2D,d=null);const[m,S]=v.draw(t,c,f,d===null);if(d===null&&(d=m.position,p=m.normal.flipped.perpendicular),g=S.position,y=S.normal.flipped.perpendicular,u>a)break}return this.closed()&&this.start.isInitial()&&this.end.isInitial()&&this.startOffset.isInitial()&&this.endOffset.isInitial()&&t.closePath(),this.processSubpath(t,d,g),e.addPath(t),{startPoint:d??R.zero,startTangent:p??R.right,endPoint:g??R.zero,endTangent:y??R.right,arrowSize:l,path:e,startOffset:n}}getPointAtDistance(e){return vl(this.profile(),e+this.startOffset())}getPointAtPercentage(e){return vl(this.profile(),this.percentageToDistance(e))}getComputedLayout(){return this.offsetComputedLayout(super.getComputedLayout())}offsetComputedLayout(e){return e.position=e.position.sub(this.childrenBBox().center),e}getPath(){return this.curveDrawingInfo().path}getCacheBBox(){const e=this.childrenBBox(),t=this.startArrow()||this.endArrow()?this.arrowSize():0,s=this.lineWidth(),n=this.lineWidthCoefficient();return e.expand(Math.max(0,t,s*n))}lineWidthCoefficient(){return this.lineCap()==="square"?.5*1.4143:.5}requiresProfile(){return!this.start.isInitial()||!this.startOffset.isInitial()||!this.startArrow.isInitial()||!this.end.isInitial()||!this.endOffset.isInitial()||!this.endArrow.isInitial()}drawShape(e){super.drawShape(e),(this.startArrow()||this.endArrow())&&this.drawArrows(e)}drawArrows(e){const{startPoint:t,startTangent:s,endPoint:n,endTangent:a,arrowSize:h}=this.curveDrawingInfo();h<.001||(e.save(),e.beginPath(),this.endArrow()&&this.drawArrow(e,n,a.flipped,h),this.startArrow()&&this.drawArrow(e,t,s,h),e.fillStyle=Ia(this.stroke(),e),e.closePath(),e.fill(),e.restore())}drawArrow(e,t,s,n){const a=s.perpendicular,h=t.add(s.scale(-n/2));dr(e,h),Kt(e,h.add(s.add(a).scale(n))),Kt(e,h.add(s.sub(a).scale(n))),Kt(e,h),e.closePath()}};vt([V(!1),N()],Je.prototype,"closed",void 0);vt([V(0),N()],Je.prototype,"start",void 0);vt([V(0),N()],Je.prototype,"startOffset",void 0);vt([V(!1),N()],Je.prototype,"startArrow",void 0);vt([V(1),N()],Je.prototype,"end",void 0);vt([V(0),N()],Je.prototype,"endOffset",void 0);vt([V(!1),N()],Je.prototype,"endArrow",void 0);vt([V(24),N()],Je.prototype,"arrowSize",void 0);vt([J()],Je.prototype,"arcLength",null);vt([J()],Je.prototype,"curveDrawingInfo",null);Je=vt([nt("Curve")],Je);var Ks=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};let Ke=class extends Je{constructor(e){super(e)}profile(){return Yg(this.childrenBBox(),this.radius(),this.smoothCorners(),this.cornerSharpness())}desiredSize(){return{x:this.width.context.getter(),y:this.height.context.getter()}}offsetComputedLayout(e){return e}childrenBBox(){return fe.fromSizeCentered(this.computedSize())}getPath(){if(this.requiresProfile())return this.curveDrawingInfo().path;const e=new Path2D,t=this.radius(),s=this.smoothCorners(),n=this.cornerSharpness(),a=fe.fromSizeCentered(this.size());return xl(e,a,t,s,n),e}getCacheBBox(){return super.getCacheBBox().expand(this.rippleSize())}getRipplePath(){const e=new Path2D,t=this.rippleSize(),s=this.radius().addScalar(t),n=this.smoothCorners(),a=this.cornerSharpness(),h=fe.fromSizeCentered(this.size()).expand(t);return xl(e,h,s,n,a),e}};Ks([fr("radius")],Ke.prototype,"radius",void 0);Ks([V(!1),N()],Ke.prototype,"smoothCorners",void 0);Ks([V(.6),N()],Ke.prototype,"cornerSharpness",void 0);Ks([J()],Ke.prototype,"profile",null);Ke=Ks([nt("Rect")],Ke);var Ut=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},Hi;const jg="\nThe `playbackRate` of a `Video` cannot be reactive.\n\nMake sure to use a concrete value and not a function:\n\n```ts wrong\nvideo.playbackRate(() => 7);\n```\n\n```ts correct\nvideo.playbackRate(7);\n```\n\nIf you're using a signal, extract its value before passing it to the property:\n\n```ts wrong\nvideo.playbackRate(mySignal);\n```\n\n```ts correct\nvideo.playbackRate(mySignal());\n```\n";let Ye=Hi=class extends Ke{constructor(e){super(e),this.lastTime=-1,this.awaitCanPlay()||this.scheduleSeek(this.time()),e.play&&this.play(),this.volume=e.volume??1,this.setVolume(this.volume)}isPlaying(){return this.playing()}getCurrentTime(){return this.clampTime(this.time())}getDuration(){return this.mediaElement().duration}getVolume(){return this.volume}getUrl(){return this.mediaElement().src}dispose(){this.pause(),this.remove(),super.dispose()}completion(){return this.clampTime(this.time())/this.getDuration()}setCurrentTime(e){const t=this.mediaElement();t.readyState<2||(t.currentTime=e,this.lastTime=e,t.seeking&&be.collectPromise(new Promise(s=>{const n=()=>{s(),t.removeEventListener("seeked",n)};t.addEventListener("seeked",n)})))}setVolume(e){e<0&&console.warn("volumes cannot be negative - the value will be clamped to 0.");const t=this.mediaElement();if(t.volume=Math.min(Math.max(e,0),1),e>1){if(this.allowVolumeAmplificationInPreview()){this.amplify(t,e);return}console.warn(`you have set the volume of node ${this.key} to ${e} - your video will be exported with the correct volume, but the browser does not support volumes higher than 1 by default. To enable volume amplification in the preview, set the "allowVolumeAmplificationInPreview" of your <Video/> or <Audio/> tag to true. Note that amplification for previews will not work if you use autoplay within the player due to browser autoplay policies: https://developer.chrome.com/blog/autoplay/#webaudio.`)}}amplify(e,t){const s=`${this.src()}/${this.key}`;if(Hi.amplificationPool[s]){Hi.amplificationPool[s].gainNode.gain.value=t;return}const n=new AudioContext,a=n.createMediaElementSource(e),h=n.createGain();if(h.gain.value=t,a.connect(h),h.connect(n.destination),Hi.amplificationPool[s]={audioContext:n,sourceNode:a,gainNode:h},typeof window>"u"||n.state!=="suspended")return;const l=()=>{Hi.amplificationPool[s].audioContext.resume(),window.removeEventListener("click",l)};window.addEventListener("click",l)}setPlaybackRate(e){let t;if(Dt(e)?(t=e(),Me().warn({message:"Invalid value set as the playback rate",remarks:jg,inspect:this.key,stack:new Error().stack})):t=e,this.playbackRate.context.setter(t),this.playing())if(t===0)this.pause();else{const s=ws().time,n=s(),a=this.time();this.time(()=>this.clampTime(a+(s()-n)*t))}}scheduleSeek(e){this.waitForCanPlay(this.mediaElement(),()=>{const t=this.mediaElement();t.currentTime=e})}waitForCanPlay(e,t){if(e.readyState>=2){t();return}const s=()=>{t(),e.removeEventListener("canplay",s)},n=()=>{var h;const a=this.getErrorReason((h=e.error)==null?void 0:h.code);console.log(`ERROR: Error loading video: ${this.src()}, ${a}`),e.removeEventListener("error",n)};e.addEventListener("canplay",s),e.addEventListener("error",n)}waitForCanPlayNecessary(e){return e.readyState>=2?!1:this.awaitCanPlay()||this.view().playbackState()===xt.Rendering}play(){const e=ws().time,t=e(),s=this.time(),n=this.playbackRate();this.playing(!0),this.time(()=>this.clampTime(s+(e()-t)*n))}pause(){this.playing(!1),this.time.save(),this.mediaElement().pause()}clampTime(e){const t=this.getDuration();return this.loop()&&(e%=t),ye(0,t,e)}collectAsyncResources(){super.collectAsyncResources(),this.seekedMedia()}getErrorReason(e){let t;switch(e){case 1:t="MEDIA_ERR_ABORTED";break;case 2:t="MEDIA_ERR_NETWORK. This might be a 404 error.";break;case 3:t="MEDIA_ERR_DECODE. This might be an issue with your video file.";break;case 4:t="MEDIA_ERR_SRC_NOT_SUPPORTED. If you are sure that the path to the video is correct, this might be a CORS error.";break;default:t="UNKNOWN"}return t}};Ye.amplificationPool={};Ut([N()],Ye.prototype,"src",void 0);Ut([V(!1),N()],Ye.prototype,"loop",void 0);Ut([V(1),N()],Ye.prototype,"playbackRate",void 0);Ut([V(0),N()],Ye.prototype,"time",void 0);Ut([V(!1),N()],Ye.prototype,"playing",void 0);Ut([V(!0),N()],Ye.prototype,"awaitCanPlay",void 0);Ut([V(!1),N()],Ye.prototype,"allowVolumeAmplificationInPreview",void 0);Ut([J()],Ye.prototype,"completion",null);Ut([J()],Ye.prototype,"amplify",null);Ye=Hi=Ut([nt("Media")],Ye);var pr=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},_n;let Wt=_n=class extends Ye{constructor(e){super(e)}mediaElement(){return this.audio()}seekedMedia(){return this.seekedAudio()}fastSeekedMedia(){return this.fastSeekedAudio()}audio(){const e=this.src(),t=`${this.key}/${e}`;let s=_n.pool[t];return s||(s=document.createElement("audio"),s.crossOrigin="anonymous",s.src=e,_n.pool[t]=s),this.waitForCanPlayNecessary(s)&&be.collectPromise(new Promise(a=>{this.waitForCanPlay(s,a)})),s}seekedAudio(){const e=this.audio();if(e.addEventListener("ended",()=>{this.pause()}),!(this.time()<e.duration))return this.pause(),e;const t=this.clampTime(this.time());return e.playbackRate=this.playbackRate(),e.paused||e.pause(),this.lastTime===t||this.setCurrentTime(t),e}fastSeekedAudio(){const e=this.audio();if(!(this.time()<e.duration))return this.pause(),e;const t=this.clampTime(this.time());if(e.playbackRate=this.playbackRate(),this.lastTime===t)return e;const s=this.playing()&&t<e.duration&&e.playbackRate>0;return s?e.paused&&be.collectPromise(e.play()):e.paused||e.pause(),Math.abs(e.currentTime-t)>.3?this.setCurrentTime(t):s||(e.currentTime=t),e}async draw(e){const t=this.view().playbackState();t===xt.Playing||t===xt.Presenting?this.fastSeekedAudio():this.seekedAudio(),e.save(),e.restore(),await this.drawChildren(e)}};Wt.pool={};pr([J()],Wt.prototype,"audio",null);pr([J()],Wt.prototype,"seekedAudio",null);pr([J()],Wt.prototype,"fastSeekedAudio",null);Wt=_n=pr([nt("Audio")],Wt);var us=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},wa;let jt=wa=class extends Ke{constructor(e){super({composite:!0,fontFamily:"Roboto",fontSize:48,lineHeight:"120%",textWrap:!1,fontStyle:"normal",...e}),this.view2D=this,wa.shadowRoot.append(this.element),this.applyFlex()}dispose(){this.removeChildren(),super.dispose()}async render(e){this.computedSize(),this.computedPosition(),await super.render(e)}findKey(e){return xn().getNode(e)??null}requestLayoutUpdate(){this.updateLayout()}requestFontUpdate(){this.applyFont()}view(){return this}};us([V(xt.Paused),N()],jt.prototype,"playbackState",void 0);us([V(0),N()],jt.prototype,"globalTime",void 0);us([V(0),N()],jt.prototype,"fps",void 0);us([N()],jt.prototype,"assetHash",void 0);us([Zn(()=>{const r="twick-2d-frame";let e=document.querySelector(`#${r}`);return e||(e=document.createElement("div"),e.id=r,e.style.position="absolute",e.style.pointerEvents="none",e.style.top="0",e.style.left="0",e.style.fontFeatureSettings="normal",e.style.opacity="0",e.style.overflow="hidden",document.body.prepend(e)),e.shadowRoot??e.attachShadow({mode:"open"})})],jt,"shadowRoot",void 0);jt=wa=us([nt("View2D")],jt);var qg=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};class Qi extends ur{constructor(e,t,s,n,a,h){super(),this.startPoint=e,this.radius=t,this.xAxisRotationDegree=s,this.largeArcFlag=n,this.sweepFlag=a,this.endPoint=h,this.xAxisRotation=this.xAxisRotationDegree*li,this.radius=new R(Math.abs(t.x),Math.abs(t.y));const l=we.fromRotation(-s).domMatrix,u=Vt(e.sub(h).div(2),l),d=u.x*u.x/(t.x*t.x)+u.y*u.y/(t.y*t.y);if(d>1){const E=Math.sqrt(d);t.x=E*t.x,t.y=E*t.y}const p=new R(t.ctg*u.y,t.perpendicular.ctg*u.x).scale(Math.sqrt(1/(u.x*u.x/(t.x*t.x)+u.y*u.y/(t.y*t.y))-1)*(n===a?-1:1));this.xAxisRotationMatrix=we.fromRotation(s).domMatrix;const g=Vt(p,this.xAxisRotationMatrix);this.center=g.add(e.add(h).div(2));const y=u.sub(p).div(t),v=u.scale(-1).sub(p).div(t);this.startAngle=y.radians,this.deltaAngle=R.angleBetween(y,v)%(Math.PI*2),this.sweepFlag===0&&this.deltaAngle>0&&(this.deltaAngle-=Math.PI*2),this.sweepFlag===1&&this.deltaAngle<0&&(this.deltaAngle+=Math.PI*2),Qi.el.setAttribute("d",`M ${this.startPoint.x} ${this.startPoint.y} A ${this.radius.x} ${this.radius.y} ${this.xAxisRotationDegree} ${this.largeArcFlag} ${this.sweepFlag} ${this.endPoint.x} ${this.endPoint.y}`),this.length=Qi.el.getTotalLength();const x=new fe(Qi.el.getBBox());this.points=[x.topLeft,x.bottomRight]}getAnglePosition(e){return Vt(this.radius.mul(R.fromRadians(e)),this.xAxisRotationMatrix).add(this.center)}getAngleDerivative(e){const t=new R(-this.radius.x*Math.sin(e),this.radius.y*Math.cos(e));return Vt(t,this.xAxisRotationMatrix)}draw(e,t,s,n){const a=this.startAngle+this.deltaAngle*t,h=this.startAngle+this.deltaAngle*s,l=this.getPoint(t),u=this.getPoint(s);return n&&e.moveTo(l.position.x,l.position.y),e.ellipse(this.center.x,this.center.y,this.radius.x,this.radius.y,this.xAxisRotation,a,h,this.sweepFlag===0),[l,u]}getPoint(e){const t=this.startAngle+e*this.deltaAngle,s=this.getAngleDerivative(t).normalized;return{position:e===0?this.startPoint:e===1?this.endPoint:this.getAnglePosition(t),tangent:s,normal:s.perpendicular}}get arcLength(){return this.length}}qg([Zn(()=>{const r=document.createElementNS("http://www.w3.org/2000/svg","svg"),e=document.createElementNS("http://www.w3.org/2000/svg","path");return r.appendChild(e),jt.shadowRoot.appendChild(r),e})],Qi,"el",void 0);function Xg(r,e,t,s,n=!1){const a={arcLength:0,minSin:1,segments:[]};if(t<e){const p=Math.floor((e-t)/(Math.PI*2))+1;t+=Math.PI*2*p}else if(t>e+Math.PI*2){const p=Math.floor((t-e)/(Math.PI*2));t-=Math.PI*2*p}const h=(e+t)/2,l=r.mul(R.fromRadians(e)),u=r.mul(R.fromRadians(t)),d=r.mul(R.fromRadians(h)).scale(n?-1:1);return s&&La(a,new Ki(R.zero,l)),Sl(a,r,l,d,e,h,n),Sl(a,r,d,u,h,t,n),s&&La(a,new Ki(u,R.zero)),a}function La(r,e){r.segments.push(e),r.arcLength+=e.arcLength}function Sl(r,e,t,s,n,a,h){const l=Math.abs(n-a)<=180?1:0,u=n>a?0:1,d=h?0:1;La(r,new Qi(t,e,0,0,l^d^u,s))}var Ys=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};let Pi=class extends Je{constructor(e){super(e)}profile(){return Xg(this.size().scale(.5),this.startAngle()*li,this.endAngle()*li,this.closed(),this.counterclockwise())}desiredSize(){return{x:this.width.context.getter(),y:this.height.context.getter()}}offsetComputedLayout(e){return e}childrenBBox(){return fe.fromSizeCentered(this.computedSize())}getPath(){return this.requiresProfile()?this.curveDrawingInfo().path:this.createPath()}getRipplePath(){return this.createPath(this.rippleSize())}getCacheBBox(){return super.getCacheBBox().expand(this.rippleSize())}createPath(e=0){const t=new Path2D,s=this.startAngle()*li;let n=this.endAngle()*li;const a=this.size().scale(.5).add(e),h=this.closed();if(n>s+Math.PI*2){const l=Math.floor((n-s)/(Math.PI*2));n-=Math.PI*2*l}return h&&t.moveTo(0,0),t.ellipse(0,0,a.x,a.y,0,s,n,this.counterclockwise()),h&&t.closePath(),t}};Ys([V(0),N()],Pi.prototype,"startAngle",void 0);Ys([V(360),N()],Pi.prototype,"endAngle",void 0);Ys([V(!1),N()],Pi.prototype,"counterclockwise",void 0);Ys([J()],Pi.prototype,"profile",null);Pi=Ys([nt("Circle")],Pi);var vi=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},En;const Qg=`
|
|
81
|
+
`;class Qg{constructor(e,t){this.scene=e,this.sharedContext=t,this.gl=null,this.positionBuffer=null,this.sourceTexture=null,this.destinationTexture=null,this.positionLocation=0,this.quadPositions=new Float32Array([-1,1,-1,-1,1,1,1,-1]),this.handleReload=()=>{this.gl&&this.updateViewport()},e.onReloaded.subscribe(this.handleReload)}setup(e){this.gl=e,this.updateViewport(),this.positionBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.bufferData(e.ARRAY_BUFFER,this.quadPositions,e.STATIC_DRAW),e.vertexAttribPointer(this.positionLocation,2,e.FLOAT,!1,0,0),e.enableVertexAttribArray(this.positionLocation),this.sourceTexture=e.createTexture(),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.sourceTexture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),this.destinationTexture=e.createTexture(),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,this.destinationTexture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}teardown(e){e.deleteBuffer(this.positionBuffer),e.disableVertexAttribArray(this.positionLocation),e.deleteTexture(this.sourceTexture),e.deleteTexture(this.destinationTexture),this.positionBuffer=null,this.sourceTexture=null,this.destinationTexture=null,this.gl=null}updateViewport(){if(this.gl){const e=this.scene.getRealSize();this.gl.canvas.width=e.width,this.gl.canvas.height=e.height,this.gl.viewport(0,0,e.width,e.height)}}getGL(){return this.gl??this.sharedContext.borrow(this)}getProgram(e){const t=this.sharedContext.getProgram(e,Xg);if(!t)return null;const s=this.scene.getRealSize(),n=this.getGL();return n.useProgram(t),n.uniform1i(n.getUniformLocation(t,Kg),0),n.uniform1i(n.getUniformLocation(t,Vg),1),n.uniform2f(n.getUniformLocation(t,Hg),s.x,s.y),n.uniform1f(n.getUniformLocation(t,Yg),this.scene.playback.deltaTime),n.uniform1f(n.getUniformLocation(t,Wg),this.scene.playback.fps),t}copyTextures(e,t){this.copyTexture(t,this.sourceTexture),this.copyTexture(e,this.destinationTexture)}clear(){const e=this.getGL();e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT)}render(){const e=this.getGL();e.drawArrays(e.TRIANGLE_STRIP,0,4)}copyTexture(e,t){const s=this.getGL();s.bindTexture(s.TEXTURE_2D,t),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,e),s.generateMipmap(s.TEXTURE_2D)}}class Zg{get onChanged(){return this.slides.subscribable}constructor(e){this.scene=e,this.slides=new wa([]),this.lookup=new Map,this.collisionLookup=new Set,this.current=null,this.canResume=!1,this.waitsForId=null,this.targetId=null,this.handleReload=()=>{this.lookup.clear(),this.collisionLookup.clear(),this.current=null,this.waitsForId=null,this.targetId=null},this.handleReset=()=>{this.collisionLookup.clear(),this.current=null,this.waitsForId=null},this.handleRecalculated=()=>{this.slides.current=[...this.lookup.values()]},this.scene.onReloaded.subscribe(this.handleReload),this.scene.onReset.subscribe(this.handleReset),this.scene.onRecalculated.subscribe(this.handleRecalculated)}setTarget(e){this.targetId=e}resume(){this.canResume=!0}isWaitingFor(e){return this.waitsForId===e}isWaiting(){return this.waitsForId!==null}didHappen(e){var t;if(this.current===null)return!1;for(const s of this.lookup.keys()){if(s===e)return!0;if(s===((t=this.current)==null?void 0:t.id))return!1}return!1}getCurrent(){return this.current}register(e,t){if(this.waitsForId!==null)throw new Error(`The animation already waits for a slide: ${this.waitsForId}.`);const s=this.toId(e);this.scene.playback.state!==tt.Presenting&&(this.lookup.has(s)||this.lookup.set(s,{id:s,name:e,time:t,scene:this.scene,stack:new Error().stack}),this.collisionLookup.has(e)?this.scene.logger.warn({message:`A slide named "${e}" already exists.`,stack:new Error().stack}):this.collisionLookup.add(e)),this.waitsForId=s,this.current=this.lookup.get(s)??null,this.canResume=!1}shouldWait(e){const t=this.toId(e);if(this.waitsForId!==t)throw new Error(`The animation waits for a different slide: ${this.waitsForId}.`);if(!this.lookup.get(t))throw new Error(`Could not find the "${e}" slide.`);let n=this.canResume;return this.scene.playback.state!==tt.Presenting&&(n=t!==this.targetId),n&&(this.waitsForId=null),!n}toId(e){return`${this.scene.name}:${e}`}}class Jg{constructor(e){this.scene=e,this.signals={},this.variables={},this.handleReset=()=>{this.signals={}},e.onReset.subscribe(this.handleReset)}get(e,t){var s;return(s=this.signals)[e]??(s[e]=ps(this.variables[e]??t)),()=>this.signals[e]()}updateSignals(e){this.variables=e,Object.keys(e).map(t=>{t in this.signals&&this.signals[t](e[t])})}}class e0{get firstFrame(){return this.cache.current.firstFrame}get lastFrame(){return this.firstFrame+this.cache.current.duration}get onCacheChanged(){return this.cache.subscribable}get onReloaded(){return this.reloaded.subscribable}get onRecalculated(){return this.recalculated.subscribable}get onThreadChanged(){return this.thread.subscribable}get onRenderLifecycle(){return this.renderLifecycle.subscribable}get onReset(){return this.afterReset.subscribable}get LifecycleEvents(){return this.logger.warn("LifecycleEvents is deprecated. Use lifecycleEvents instead."),this.lifecycleEvents}get previous(){return this.previousScene}getMediaAssets(){return[]}stopAllMedia(){}constructor(e){this.cache=new wa({firstFrame:0,transitionDuration:0,duration:0,lastFrame:0}),this.reloaded=new Zt,this.recalculated=new Zt,this.thread=new wa(null),this.renderLifecycle=new Zt,this.afterReset=new Zt,this.lifecycleEvents=new zg(this),this.previousScene=null,this.runner=null,this.state=ze.Initial,this.cached=!1,this.counters={},this.name=e.name,this.size=e.size,this.resolutionScale=e.resolutionScale,this.logger=e.logger,this.playback=e.playback,this.runnerFactory=e.config,this.creationStack=e.stack,this.experimentalFeatures=e.experimentalFeatures??!1,Ei(this.runnerFactory,rt(this.name)),this.variables=new Jg(this),this.shaders=new Qg(this,e.sharedWebGLContext),this.slides=new Zg(this),this.previousOnTop=!1}update(){}async render(e){let t=0;do t++,await ye.consumePromises(),e.save(),e.clearRect(0,0,e.canvas.width,e.canvas.height),await this.draw(e),e.restore();while(ye.hasPromises()&&t<10);t>1&&this.logger.debug(`render iterations: ${t}`)}reload({config:e,size:t,stack:s,resolutionScale:n}={}){e&&(this.runnerFactory=e),t&&(this.size=t),n&&(this.resolutionScale=n),s&&(this.creationStack=s),this.cached=!1,this.reloaded.dispatch()}async recalculate(e){const t=this.cache.current;if(t.firstFrame=this.playback.frame,t.lastFrame=t.firstFrame+t.duration,this.isCached()){e(t.lastFrame),this.cache.current={...t};return}for(t.transitionDuration=-1,await this.reset();!this.canTransitionOut();)t.transitionDuration<0&&this.state===ze.AfterTransitionIn&&(t.transitionDuration=this.playback.frame-t.firstFrame),e(this.playback.frame+1),await this.next();t.transitionDuration===-1&&(t.transitionDuration=0),t.lastFrame=this.playback.frame,t.duration=t.lastFrame-t.firstFrame,await new Promise(s=>setTimeout(s,0)),this.cached=!0,this.cache.current={...t},this.recalculated.dispatch()}async next(){var t;if(!this.runner)return;let e=this.execute(()=>this.runner.next());for(this.update();e.value;){if(Ng(e.value)){const s=await e.value.toPromise();e=this.execute(()=>this.runner.next(s))}else if(Gg(e.value)){const s=await e.value;e=this.execute(()=>this.runner.next(s))}else this.logger.warn({message:"Invalid value yielded by the scene.",object:e.value}),e=this.execute(()=>this.runner.next(e.value));this.update()}if(ye.hasPromises()){const s=await ye.consumePromises();this.logger.warn({message:"Tried to access an asynchronous property before the node was ready. Make sure to yield the node before accessing the property.",stack:s[0].stack,inspect:((t=s[0].owner)==null?void 0:t.key)??void 0})}e.done&&(this.state=ze.Finished)}async reset(e=null){this.counters={},this.previousScene=e,this.previousOnTop=!1,this.runner=jc(()=>this.runnerFactory(this.getView()),t=>{this.thread.current=t}),this.state=ze.AfterTransitionIn,this.afterReset.dispatch(),await this.next()}getSize(){return this.size}getRealSize(){return this.size.mul(this.resolutionScale)}isAfterTransitionIn(){return this.state===ze.AfterTransitionIn}canTransitionOut(){return this.state===ze.CanTransitionOut||this.state===ze.Finished}isFinished(){return this.state===ze.Finished}enterInitial(){this.state===ze.AfterTransitionIn?this.state=ze.Initial:this.logger.warn(`Scene ${this.name} entered initial in an unexpected state: ${this.state}`)}enterAfterTransitionIn(){this.state===ze.Initial?this.state=ze.AfterTransitionIn:this.logger.warn(`Scene ${this.name} transitioned in an unexpected state: ${this.state}`)}enterCanTransitionOut(){this.state===ze.AfterTransitionIn||this.state===ze.Initial?this.state=ze.CanTransitionOut:this.logger.warn(`Scene ${this.name} was marked as finished in an unexpected state: ${this.state}`)}isCached(){return this.cached}execute(e){let t;qu(this),sf(this.playback);try{t=e()}finally{nf(this.playback),Xu(this)}return t}}function t0(r){var e;return!!((e=r.prototype)!=null&&e.isClass)}const i0=({children:r})=>r;function ke(r,e,t){const{ref:s,children:n,...a}=e,h=Array.isArray(n)?n.flat():n;if(r===i0)return h;if(t0(r)){const l=new r({...a,children:h,key:t});return s==null||s(l),l}else return r({...a,ref:s,children:h,key:t})}const Pl={invert:{name:"invert"},sepia:{name:"sepia"},grayscale:{name:"grayscale"},brightness:{name:"brightness",default:1},contrast:{name:"contrast",default:1},saturate:{name:"saturate",default:1},hue:{name:"hue-rotate",unit:"deg",scale:1},blur:{name:"blur",transform:!0,unit:"px",scale:1}};class s0{get name(){return this.props.name}get default(){return this.props.default}constructor(e){this.props={name:"invert",default:0,unit:"%",scale:100,transform:!1,...e,value:e.value??e.default??0},this.value=ps(this.props.value,se,this)}isActive(){return this.value()!==this.props.default}serialize(e){let t=this.value();return this.props.transform&&(t=Ua(t,e)),`${this.props.name}(${t*this.props.scale}${this.props.unit})`}}const Wt=Symbol.for("@twick/2d/decorators/initializers");function Qs(r,e){if(!r[Wt])r[Wt]=[];else if(r[Wt]&&!Object.prototype.hasOwnProperty.call(r,Wt)){const t=Object.getPrototypeOf(r);r[Wt]=[...t[Wt]]}r[Wt].push(e)}function n0(r,e){if(r[Wt])try{r[Wt].forEach(t=>t(r,e))}catch(t){throw t.inspect??(t.inspect=r.key),t}}function te(){return(r,e)=>{Qs(r,t=>{const s=Object.getPrototypeOf(t)[e];t[e]=zf(s.bind(t),t)})}}function Oa(r={},e,t){const s={};if(t&&e){const n=r.setter??(e==null?void 0:e[`set${Ui(t)}`]);n&&(s.setter=n.bind(e));const a=r.getter??(e==null?void 0:e[`get${Ui(t)}`]);a&&(s.getter=a.bind(e));const h=r.tweener??(e==null?void 0:e[`tween${Ui(t)}`]);h&&(s.tweener=h.bind(e))}return s}const jt=Symbol.for("@twick/2d/decorators/properties");function Ki(r,e){var t;return((t=r[jt])==null?void 0:t[e])??null}function _o(r,e){let t;return r[jt]?r[jt]&&!Object.prototype.hasOwnProperty.call(r,jt)?r[jt]=t=Object.fromEntries(Object.entries(r[jt]).map(([s,n])=>[s,{...n}])):t=r[jt]:r[jt]=t={},t[e]??(t[e]={cloneable:!0,inspectable:!0,compoundEntries:[]}),t[e]}function qc(r){return r&&typeof r=="object"?r[jt]??{}:{}}function Eo(r,e){n0(r);for(const[t,s]of Object.entries(qc(r))){const n=r[t];if(n.reset(),e[t]!==void 0&&n(e[t]),s.compoundEntries!==void 0)for(const[a,h]of s.compoundEntries)h in e&&n[a](e[h])}}function N(){return(r,e)=>{const t=_o(r,e);Qs(r,s=>{var l;let n=t.default;const a=s[`getDefault${Ui(e)}`];a&&(n=()=>a.call(s,t.default));const h=new $i(n,t.interpolationFunction??us,s,(l=t.parser)==null?void 0:l.bind(s),Oa(t,s,e));s[e]=h.toSignal()})}}function W(r){return(e,t)=>{const s=Ki(e,t);if(!s){Ue().error(`Missing property decorator for "${t.toString()}"`);return}s.default=r}}function To(r){return(e,t)=>{const s=Ki(e,t);if(!s){Ue().error(`Missing property decorator for "${t.toString()}"`);return}s.interpolationFunction=r}}function bo(r){return(e,t)=>{const s=Ki(e,t);if(!s){Ue().error(`Missing property decorator for "${t.toString()}"`);return}s.parser=r}}function Zs(r){return(e,t)=>{const s=Ki(e,t);if(!s){Ue().error(`Missing property decorator for "${t.toString()}"`);return}s.parser=n=>new r(n),"lerp"in r&&(s.interpolationFunction??(s.interpolationFunction=r.lerp))}}function _s(r=!0){return(e,t)=>{const s=Ki(e,t);if(!s){Ue().error(`Missing property decorator for "${t.toString()}"`);return}s.cloneable=r}}function Xc(r=!0){return(e,t)=>{const s=Ki(e,t);if(!s){Ue().error(`Missing property decorator for "${t.toString()}"`);return}s.inspectable=r}}function Qc(r){return(e,t)=>{const s=_o(e,t);s.compound=!0,s.compoundEntries=Object.entries(r),Qs(e,n=>{if(!s.parser){Ue().error(`Missing parser decorator for "${t.toString()}"`);return}const a=s.default,h=s.parser.bind(n),l=new cr(s.compoundEntries.map(([u,d])=>{const p=new $i(rs(a,g=>h(g)[u]),se,n,void 0,Oa(void 0,n,d)).toSignal();return[u,p]}),h,a,s.interpolationFunction??us,n,Oa(s,n,t));n[t]=l.toSignal()})}}function ri(r){return(e,t)=>{Qc(typeof r=="object"?r:{x:r?`${r}X`:"x",y:r?`${r}Y`:"y"})(e,t),Zs(C)(e,t)}}var Ti=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};class Ht{constructor(e){Eo(this,e)}canvasGradient(e){let t;switch(this.type()){case"linear":t=e.createLinearGradient(this.from.x(),this.from.y(),this.to.x(),this.to.y());break;case"conic":t=e.createConicGradient(this.angle(),this.from.x(),this.from.y());break;case"radial":t=e.createRadialGradient(this.from.x(),this.from.y(),this.fromRadius(),this.to.x(),this.to.y(),this.toRadius());break}for(const{offset:s,color:n}of this.stops())t.addColorStop(fs(s),new we(fs(n)).serialize());return t}}Ti([W("linear"),N()],Ht.prototype,"type",void 0);Ti([ri("from")],Ht.prototype,"from",void 0);Ti([ri("to")],Ht.prototype,"to",void 0);Ti([W(0),N()],Ht.prototype,"angle",void 0);Ti([W(0),N()],Ht.prototype,"fromRadius",void 0);Ti([W(0),N()],Ht.prototype,"toRadius",void 0);Ti([W([]),N()],Ht.prototype,"stops",void 0);Ti([te()],Ht.prototype,"canvasGradient",null);var Ao=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};class Js{constructor(e){Eo(this,e)}canvasPattern(e){return e.createPattern(this.image(),this.repetition())}}Ao([N()],Js.prototype,"image",void 0);Ao([W(null),N()],Js.prototype,"repetition",void 0);Ao([te()],Js.prototype,"canvasPattern",null);function r0(r){return r===null?null:r instanceof Ht||r instanceof Js?r:new we(r)}function Ba(r,e){return r===null?"":r instanceof we?r.serialize():r instanceof Ht?r.canvasGradient(e):r instanceof Js?r.canvasPattern(e)??"":""}function Dl(r,e,t,s,n){if(t.top===0&&t.right===0&&t.bottom===0&&t.left===0){a0(r,e);return}const a=gi(t.top,t.right,t.left,e),h=gi(t.right,t.top,t.bottom,e),l=gi(t.bottom,t.left,t.right,e),u=gi(t.left,t.bottom,t.top,e);if(s){const d=p=>{const g=p*n;return p-g};r.moveTo(e.left+a,e.top),r.lineTo(e.right-h,e.top),r.bezierCurveTo(e.right-d(h),e.top,e.right,e.top+d(h),e.right,e.top+h),r.lineTo(e.right,e.bottom-l),r.bezierCurveTo(e.right,e.bottom-d(l),e.right-d(l),e.bottom,e.right-l,e.bottom),r.lineTo(e.left+u,e.bottom),r.bezierCurveTo(e.left+d(u),e.bottom,e.left,e.bottom-d(u),e.left,e.bottom-u),r.lineTo(e.left,e.top+a),r.bezierCurveTo(e.left,e.top+d(a),e.left+d(a),e.top,e.left+a,e.top);return}r.moveTo(e.left+a,e.top),r.arcTo(e.right,e.top,e.right,e.bottom,h),r.arcTo(e.right,e.bottom,e.left,e.bottom,l),r.arcTo(e.left,e.bottom,e.left,e.top,u),r.arcTo(e.left,e.top,e.right,e.top,a)}function gi(r,e,t,s){const n=r+e>s.width?s.width*(r/(r+e)):r,a=r+t>s.height?s.height*(r/(r+t)):r;return Math.min(n,a)}function a0(r,e){r.rect(e.x,e.y,e.width,e.height)}function Zc(r,e,t,s){r.drawImage(e,t.x,t.y,t.width,t.height)}function Er(r,e){r.moveTo(e.x,e.y)}function ei(r,e){r.lineTo(e.x,e.y)}function Mi(r,e){if(!(e.length<2)){Er(r,e[0]);for(const t of e.slice(1))ei(r,t)}}function o0(r,e,t=8){ei(r,e.addY(-t)),ei(r,e.addY(t)),ei(r,e),ei(r,e.addX(-t)),l0(r,e,t)}function l0(r,e,t,s=0,n=Math.PI*2,a=!1){r.arc(e.x,e.y,t,s,n,a)}function h0(r,e,t,s){r.bezierCurveTo(e.x,e.y,t.x,t.y,s.x,s.y)}function Jc(r){return e=>e instanceof r}function ed(){return(r,e)=>{N()(r,e),bo(r0)(r,e),To(we.lerp)(r,e),W(null)(r,e)}}function td(){return(r,e)=>{N()(r,e),Zs(we)(r,e)}}function bi(r,e=t=>t){return(t,s)=>{t[`getDefault${Ui(s)}`]=function(){this.requestLayoutUpdate();const n=this.element.style[r];this.element.style[r]="";const a=e.call(this,this.styles.getPropertyValue(r));return this.element.style[r]=n,a}}}class c0 extends $i{constructor(e,t){super(e,us,t);for(const s in Pl){const n=Pl[s];Object.defineProperty(this.invokable,s,{value:(a,h,l=Bs)=>{var d,p,g;if(a===void 0)return((p=(d=this.get())==null?void 0:d.find(y=>y.name===n.name))==null?void 0:p.value())??n.default??0;let u=(g=this.get())==null?void 0:g.find(y=>y.name===n.name);return u||(u=new s0(n),this.set([...this.get(),u])),h===void 0?(u.value(a),this.owner):u.value(a,h,l)}})}}*tweener(e,t,s){const n=this.get(),a=fs(e);if(u0(n,a)){yield*Se(...n.map((u,d)=>u.value(a[d].value(),t,s))),this.set(a);return}for(const u of a)u.value(u.default);const h=a.map(u=>u.value.context.raw()),l=n.length>0&&a.length>0?t/2:t;n.length>0&&(yield*Se(...n.map(u=>u.value(u.default,l,s)))),this.set(a),a.length>0&&(yield*Se(...a.map((u,d)=>u.value(h[d],l,s))))}}function d0(){return(r,e)=>{const t=_o(r,e);Qs(r,s=>{s[e]=new c0(t.default??[],s).toSignal()})}}function u0(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t].name!==e[t].name)return!1;return!0}const f0=Symbol.for("@twick/2d/nodeName");function ut(r){return function(e){e.prototype[f0]=r}}let Tr=class{};class p0 extends Tr{constructor(e,t,s,n,a){super(),this.center=e,this.radius=t,this.from=s,this.to=n,this.counter=a,this.angle=Math.acos(me(-1,1,s.dot(n))),this.length=Math.abs(this.angle*t);const h=new C(1,1).scale(t);this.points=[e.sub(h),e.add(h)]}get arcLength(){return this.length}draw(e,t,s){const n=this.counter?-1:1,a=this.from.radians+t*this.angle*n,h=this.to.radians-(1-s)*this.angle*n;Math.abs(this.angle)>1e-4&&e.arc(this.center.x,this.center.y,this.radius,a,h,this.counter);const l=C.fromRadians(a),u=C.fromRadians(h);return[{position:this.center.add(l.scale(this.radius)),tangent:this.counter?l:l.flipped,normal:this.counter?l.flipped:l},{position:this.center.add(u.scale(this.radius)),tangent:this.counter?u.flipped:u,normal:this.counter?u.flipped:u}]}getPoint(e){const t=this.counter?-1:1,s=this.from.radians+e*this.angle*t,n=C.fromRadians(s);return{position:this.center.add(n.scale(this.radius)),tangent:this.counter?n:n.flipped,normal:this.counter?n:n.flipped}}}class Qe{static constant(e){return new Qe(e)}static linear(e,t){return new Qe(e,t)}static quadratic(e,t,s){return new Qe(e,t,s)}static cubic(e,t,s,n){return new Qe(e,t,s,n)}get degree(){return this.c3!==0?3:this.c2!==0?2:this.c1!==0?1:0}constructor(e,t,s,n){this.c0=e,this.c1=t??0,this.c2=s??0,this.c3=n??0}differentiate(e=1){switch(e){case 0:return this;case 1:return new Qe(this.c1,2*this.c2,3*this.c3,0);case 2:return new Qe(2*this.c2,6*this.c3,0,0);case 3:return new Qe(6*this.c3,0,0,0);default:throw new Error("Unsupported derivative")}}eval(e,t=0){return t!==0?this.differentiate(t).eval(e):this.c3*(e*e*e)+this.c2*(e*e)+this.c1*e+this.c0}split(e){const t=1-e,s=new Qe(this.c0,this.c1*e,this.c2*e*e,this.c3*e*e*e),n=new Qe(this.eval(0),t*this.differentiate(1).eval(e),t*t/2*this.differentiate(2).eval(e),t*t*t/6*this.differentiate(3).eval(e));return[s,n]}roots(){switch(this.degree){case 3:return this.solveCubicRoots();case 2:return this.solveQuadraticRoots();case 1:return this.solveLinearRoot();case 0:return[];default:throw new Error(`Unsupported polynomial degree: ${this.degree}`)}}localExtrema(){return this.differentiate().roots()}localExtrema01(){const e=this.localExtrema(),t=[];for(let s=0;s<e.length;s++){const n=e[s];n>=0&&n<=1&&t.push(e[s])}return t}outputRange01(){let e=[this.eval(0),this.eval(1)];const t=s=>{e[1]>e[0]?e=[Math.min(e[0],s),Math.max(e[1],s)]:e=[Math.min(e[1],s),Math.max(e[0],s)]};return this.localExtrema01().forEach(s=>t(this.eval(s))),e}solveCubicRoots(){const e=this.c0,t=this.c1,s=this.c2,n=this.c3,a=e*e,h=e*s,l=t*t,u=(3*h-l)/(3*a),d=(2*l*t-9*h*t+27*a*n)/(27*a*e),p=this.solveDepressedCubicRoots(u,d),g=y=>y-t/(3*e);switch(p.length){case 1:return[g(p[0])];case 2:return[g(p[0]),g(p[1])];case 3:return[g(p[0]),g(p[1]),g(p[2])];default:return[]}}solveDepressedCubicRoots(e,t){if(this.almostZero(e))return[Math.cbrt(-t)];const s=Math.PI*2,n=4*e*e*e+27*t*t;if(n<1e-5){const a=2*Math.sqrt(-e/3),h=3*t/(2*e)*Math.sqrt(-3/e),l=u=>a*Math.cos(1/3*Math.acos(me(-1,1,h))-s/3*u);return h>=.9999?[l(0),l(2)]:h<=-.9999?[l(1),l(2)]:[l(0),l(1),l(2)]}if(n>0&&e<0){const a=.3333333333333333*Math.acosh(-3*Math.abs(t)/(2*e)*Math.sqrt(-3/e));return[-2*Math.sign(t)*Math.sqrt(-e/3)*Math.cosh(a)]}if(e>0){const a=.3333333333333333*Math.asinh(3*t/(2*e)*Math.sqrt(3/e));return[-2*Math.sqrt(e/3)*Math.sinh(a)]}return[]}solveQuadraticRoots(){const e=this.c2,t=this.c1,s=this.c0,n=t*t-4*e*s;if(this.almostZero(n))return[-t/(2*e)];if(n>=0){const a=Math.sqrt(n),h=(-t-a)/(2*e),l=(-t+a)/(2*e);return[Math.min(h,l),Math.max(h,l)]}return[]}solveLinearRoot(){return[-this.c0/this.c1]}almostZero(e){return Math.abs(0-e)<=Number.EPSILON}}class ks{constructor(e,t,s,n){this.c0=e,this.c1=t,this.c2=s,this.c3=n,e instanceof Qe?(this.x=e,this.y=t):n!==void 0?(this.x=new Qe(e.x,t.x,s.x,n.x),this.y=new Qe(e.y,t.y,s.y,n.y)):(this.x=new Qe(e.x,t.x,s.x),this.y=new Qe(e.y,t.y,s.y))}eval(e,t=0){return new C(this.x.differentiate(t).eval(e),this.y.differentiate(t).eval(e))}split(e){const[t,s]=this.x.split(e),[n,a]=this.y.split(e);return[new ks(t,n),new ks(s,a)]}differentiate(e=1){return new ks(this.x.differentiate(e),this.y.differentiate(e))}evalDerivative(e){return this.differentiate().eval(e)}getBounds(){const e=this.x.outputRange01(),t=this.y.outputRange01();return pe.fromPoints(new C(Math.min(...e),Math.max(...t)),new C(Math.max(...e),Math.min(...t)))}}class g0{constructor(e,t=20){this.curve=e,this.sampledDistances=[],this.resample(t)}resample(e){this.sampledDistances=[0];let t=0,s=this.curve.eval(0).position;for(let n=1;n<e;n++){const a=n/(e-1),h=this.curve.eval(a),l=s.sub(h.position).magnitude;t+=l,this.sampledDistances.push(t),s=h.position}this.sampledDistances[this.sampledDistances.length-1]=this.curve.arcLength}pointAtDistance(e){return this.curve.eval(this.distanceToT(e))}distanceToT(e){const t=this.sampledDistances.length;e=me(0,this.curve.arcLength,e);for(let s=0;s<t;s++){const n=this.sampledDistances[s],a=this.sampledDistances[s+1];if(e>=n&&e<=a)return ju(n,a,s/(t-1),(s+1)/(t-1),e)}return 1}}class m0 extends Tr{get arcLength(){return this.length}constructor(e,t){super(),this.curve=e,this.length=t,this.pointSampler=new g0(this)}getBBox(){return this.curve.getBounds()}eval(e){const t=this.tangent(e);return{position:this.curve.eval(e),tangent:t,normal:t.perpendicular}}getPoint(e){const t=this.pointSampler.pointAtDistance(this.arcLength*e);return{position:t.position,tangent:t.tangent,normal:t.tangent.perpendicular}}transformPoints(e){return this.points.map(t=>Nt(t,e))}tangent(e){return this.curve.evalDerivative(e).normalized}draw(e,t=0,s=1,n=!0){let a=null,h=t,l=s,u=this.points;if(t!==0||s!==1){const g=this.length*t,y=this.length*s;h=this.pointSampler.distanceToT(g),l=this.pointSampler.distanceToT(y);const x=(l-h)/(1-h),[,v]=this.split(h);[a]=v.split(x),u=a.points}n&&Er(e,u[0]),(a??this).doDraw(e);const d=this.tangent(h),p=this.tangent(l);return[{position:u[0],tangent:d,normal:d.perpendicular},{position:u.at(-1),tangent:p,normal:p.perpendicular}]}}var y0=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};class fi extends m0{get points(){return[this.p0,this.p1,this.p2,this.p3]}constructor(e,t,s,n){super(new ks(e,e.flipped.add(t).scale(3),e.scale(3).sub(t.scale(6)).add(s.scale(3)),e.flipped.add(t.scale(3)).sub(s.scale(3)).add(n)),fi.getLength(e,t,s,n)),this.p0=e,this.p1=t,this.p2=s,this.p3=n}split(e){const t=new C(this.p0.x+(this.p1.x-this.p0.x)*e,this.p0.y+(this.p1.y-this.p0.y)*e),s=new C(this.p1.x+(this.p2.x-this.p1.x)*e,this.p1.y+(this.p2.y-this.p1.y)*e),n=new C(this.p2.x+(this.p3.x-this.p2.x)*e,this.p2.y+(this.p3.y-this.p2.y)*e),a=new C(t.x+(s.x-t.x)*e,t.y+(s.y-t.y)*e),h=new C(s.x+(n.x-s.x)*e,s.y+(n.y-s.y)*e),l=new C(a.x+(h.x-a.x)*e,a.y+(h.y-a.y)*e),u=new fi(this.p0,t,a,l),d=new fi(l,h,n,this.p3);return[u,d]}doDraw(e){h0(e,this.p1,this.p2,this.p3)}static getLength(e,t,s,n){return fi.el.setAttribute("d",`M ${e.x} ${e.y} C ${t.x} ${t.y} ${s.x} ${s.y} ${n.x} ${n.y}`),fi.el.getTotalLength()}}y0([hr(()=>document.createElementNS("http://www.w3.org/2000/svg","path"))],fi,"el",void 0);class ts extends Tr{constructor(e,t){super(),this.from=e,this.to=t,this.vector=t.sub(e),this.length=this.vector.magnitude,this.normal=this.vector.perpendicular.normalized.safe,this.points=[e,t]}get arcLength(){return this.length}draw(e,t=0,s=1,n=!1){const a=this.from.add(this.vector.scale(t)),h=this.from.add(this.vector.scale(s));return n&&Er(e,a),ei(e,h),[{position:a,tangent:this.normal.flipped,normal:this.normal},{position:h,tangent:this.normal,normal:this.normal}]}getPoint(e){return{position:this.from.add(this.vector.scale(e)),tangent:this.normal.flipped,normal:this.normal}}}function v0(r,e,t,s){const n={arcLength:0,segments:[],minSin:1},a=gi(e.top,e.right,e.left,r),h=gi(e.right,e.top,e.bottom,r),l=gi(e.bottom,e.left,e.right,r),u=gi(e.left,e.bottom,e.top,r);let d=new C(r.left+a,r.top),p=new C(r.right-h,r.top);return is(n,new ts(d,p)),d=new C(r.right,r.top+h),p=new C(r.right,r.bottom-l),h>0&&dn(n,d.addX(-h),h,C.down,C.right,t,s),is(n,new ts(d,p)),d=new C(r.right-l,r.bottom),p=new C(r.left+u,r.bottom),l>0&&dn(n,d.addY(-l),l,C.right,C.up,t,s),is(n,new ts(d,p)),d=new C(r.left,r.bottom-u),p=new C(r.left,r.top+a),u>0&&dn(n,d.addX(u),u,C.up,C.left,t,s),is(n,new ts(d,p)),d=new C(r.left+a,r.top),a>0&&dn(n,d.addY(a),a,C.left,C.down,t,s),n}function is(r,e){r.segments.push(e),r.arcLength+=e.arcLength}function dn(r,e,t,s,n,a,h){const l=e.add(s.scale(t)),u=e.add(n.scale(t));a?is(r,new fi(l,l.add(n.scale(h*t)),u.add(s.scale(h*t)),u)):is(r,new p0(e,t,s,n,!1))}function br(r){return(e,t)=>{Qc({top:r?`${r}Top`:"top",right:r?`${r}Right`:"right",bottom:r?`${r}Bottom`:"bottom",left:r?`${r}Left`:"left"})(e,t),Zs(bt)(e,t)}}function kl(r,e){const t=me(0,r.arcLength,e);let s=0;for(const n of r.segments){const a=s;if(s+=n.arcLength,s>=t){const h=(t-a)/n.arcLength;return n.getPoint(me(0,1,h))}}return{position:C.zero,tangent:C.up,normal:C.up}}function x0(r){let e;return r?typeof r=="string"?e=[{fragment:r}]:Array.isArray(r)?e=r.map(t=>typeof t=="string"?{fragment:t}:t):e=[r]:e=[],!zn().experimentalFeatures&&e.length>0&&(e=[],Ue().log({...ef("Node uses experimental shaders."),inspect:this.key})),e}function Rn(){return zn()}var he=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},Cn;let le=Cn=class{get x(){return this.position.x}get y(){return this.position.y}getAbsolutePosition(){const e=this.localToWorld();return new C(e.m41,e.m42)}setAbsolutePosition(e){this.position(rs(e,t=>Nt(new C(t),this.worldToParent())))}getAbsoluteRotation(){const e=this.localToWorld();return C.degrees(e.m11,e.m12)}setAbsoluteRotation(e){this.rotation(rs(e,t=>Fg(t,this.worldToParent())))}getAbsoluteScale(){const e=this.localToWorld();return new C(C.magnitude(e.m11,e.m12),C.magnitude(e.m21,e.m22))}setAbsoluteScale(e){this.scale(rs(e,t=>this.getRelativeScale(new C(t))))}getRelativeScale(e){var s;const t=((s=this.parent())==null?void 0:s.absoluteScale())??C.one;return e.div(t)}*tweenCompositeOperation(e,t,s){const n=fs(e);n==="source-over"?(yield*this.compositeOverride(1,t,s),this.compositeOverride(0),this.compositeOperation(n)):(this.compositeOperation(n),this.compositeOverride(1),yield*this.compositeOverride(0,t,s))}absoluteOpacity(){var e;return(((e=this.parent())==null?void 0:e.absoluteOpacity())??1)*this.opacity()}hasFilters(){return!!this.filters().find(e=>e.isActive())}hasShadow(){return!!this.shadowColor()&&(this.shadowBlur()>0||this.shadowOffset.x()!==0||this.shadowOffset.y()!==0)}filterString(){let e="";const t=this.compositeToWorld();for(const s of this.filters())s.isActive()&&(e+=" "+s.serialize(t));return e}getSpawner(){return this.children()}setSpawner(e){this.children(e)}setChildren(e){if(this.children.context.raw()!==e){if(this.children.context.setter(e),!Bt(e))this.spawnChildren(!1,e);else if(!this.hasSpawnedChildren)for(const t of this.realChildren)t.parent(null)}}getChildren(){return this.children.context.getter(),this.spawnedChildren()}spawnedChildren(){const e=this.children.context.getter();return Bt(this.children.context.raw())&&this.spawnChildren(!0,e),this.realChildren}sortedChildren(){return[...this.children()].sort((e,t)=>Math.sign(e.zIndex()-t.zIndex()))}constructor({children:e,spawner:t,key:s,...n}){this.compositeOverride=ps(0),this.stateStack=[],this.realChildren=[],this.hasSpawnedChildren=!1,this.parent=ps(null),this.properties=qc(this);const a=Rn();[this.key,this.unregister]=a.registerNode(this,s),this.view2D=a.getView(),this.creationStack=new Error().stack,Eo(this,n),t&&Ue().warn({message:"Node.spawner() has been deprecated.",remarks:"Use <code>Node.children()</code> instead.",inspect:this.key,stack:new Error().stack}),this.children(t??e)}localToWorld(){const e=this.parent();return e?e.localToWorld().multiply(this.localToParent()):this.localToParent()}worldToLocal(){return this.localToWorld().inverse()}worldToParent(){var e;return((e=this.parent())==null?void 0:e.worldToLocal())??new DOMMatrix}localToParent(){const e=new DOMMatrix;return e.translateSelf(this.x(),this.y()),e.rotateSelf(0,0,this.rotation()),e.scaleSelf(this.scale.x(),this.scale.y()),e.skewXSelf(this.skew.x()),e.skewYSelf(this.skew.y()),e}compositeToWorld(){var e;return((e=this.compositeRoot())==null?void 0:e.localToWorld())??new DOMMatrix}compositeRoot(){var e;return this.composite()?this:((e=this.parent())==null?void 0:e.compositeRoot())??null}compositeToLocal(){const e=this.compositeRoot();if(e){const t=this.worldToLocal();return t.m44=1,e.localToWorld().multiply(t)}return new DOMMatrix}view(){return this.view2D}add(e){return this.insert(e,1/0)}insert(e,t=0){const s=Array.isArray(e)?e:[e];if(s.length===0)return this;const n=this.children(),a=n.slice(0,t);for(const h of s)h instanceof Cn&&(a.push(h),h.remove(),h.parent(this));return a.push(...n.slice(t)),this.setParsedChildren(a),this}remove(){const e=this.parent();return e===null?this:(e.removeChild(this),this.parent(null),this)}move(e=1){const t=this.parent();if(e===0||!t)return this;const s=t.children(),n=[];if(e>0)for(let a=0;a<s.length;a++){const h=s[a];if(h===this){const l=a+e;for(;a<l&&a+1<s.length;a++)n[a]=s[a+1]}n[a]=h}else for(let a=s.length-1;a>=0;a--){const h=s[a];if(h===this){const l=a+e;for(;a>l&&a>0;a--)n[a]=s[a-1]}n[a]=h}return t.setParsedChildren(n),this}moveUp(){return this.move(1)}moveDown(){return this.move(-1)}moveToTop(){return this.move(1/0)}moveToBottom(){return this.move(-1/0)}moveTo(e){const t=this.parent();if(!t)return this;const s=t.children().indexOf(this),n=e-s;return this.move(n)}moveBelow(e,t=!1){const s=this.parent();if(!s)return this;if(e.parent()!==s)return Ue().error("Cannot position nodes relative to each other if they don't belong to the same parent."),this;const n=s.children(),a=n.indexOf(this),h=n.indexOf(e);if(!t&&a<h)return this;const l=h-a-1;return this.move(l)}moveAbove(e,t=!1){const s=this.parent();if(!s)return this;if(e.parent()!==s)return Ue().error("Cannot position nodes relative to each other if they don't belong to the same parent."),this;const n=s.children(),a=n.indexOf(this),h=n.indexOf(e);if(!t&&a>h)return this;const l=h-a+1;return this.move(l)}reparent(e){const t=this.absolutePosition(),s=this.absoluteRotation(),n=this.absoluteScale();e.add(this),this.absolutePosition(t),this.absoluteRotation(s),this.absoluteScale(n)}removeChildren(){for(const e of this.realChildren)e.parent(null);this.setParsedChildren([])}peekChildren(){return this.realChildren}findAll(e){const t=[],s=this.reversedChildren();for(;s.length>0;){const n=s.pop();e(n)&&t.push(n);const a=n.children();for(let h=a.length-1;h>=0;h--)s.push(a[h])}return t}findFirst(e){const t=this.reversedChildren();for(;t.length>0;){const s=t.pop();if(e(s))return s;const n=s.children();for(let a=n.length-1;a>=0;a--)t.push(n[a])}return null}findLast(e){const t=[],s=this.reversedChildren();for(;s.length>0;){const n=s.pop();t.push(n);const a=n.children();for(let h=a.length-1;h>=0;h--)s.push(a[h])}for(;t.length>0;){const n=t.pop();if(e(n))return n}return null}findAncestor(e){let t=this.parent();for(;t;){if(e(t))return t;t=t.parent()}return null}childAs(e){return this.children()[e]??null}childrenAs(){return this.children()}parentAs(){return this.parent()??null}dispose(){if(this.unregister){this.stateStack=[],this.unregister(),this.unregister=null;for(const{signal:e}of this)e==null||e.context.dispose();for(const e of this.realChildren)e.dispose()}}clone(e={}){const t={...e};Bt(this.children.context.raw())?t.children??(t.children=this.children.context.raw()):this.children().length>0&&(t.children??(t.children=this.children().map(s=>s.clone())));for(const{key:s,meta:n,signal:a}of this)if(!(!n.cloneable||s in t))if(n.compound)for(const[h,l]of n.compoundEntries){if(l in t)continue;const u=a[h];u.context.isInitial()||(t[l]=u.context.raw())}else a.context.isInitial()||(t[s]=a.context.raw());return this.instantiate(t)}snapshotClone(e={}){const t={...this.getState(),...e};return this.children().length>0&&(t.children??(t.children=this.children().map(s=>s.snapshotClone()))),this.instantiate(t)}reactiveClone(e={}){const t={...e};this.children().length>0&&(t.children??(t.children=this.children().map(s=>s.reactiveClone())));for(const{key:s,meta:n,signal:a}of this)!n.cloneable||s in t||(t[s]=()=>a());return this.instantiate(t)}instantiate(e={}){return new this.constructor(e)}setParsedChildren(e){this.children.context.setter(e),this.realChildren=e}spawnChildren(e,t){const s=this.parseChildren(t),n=new Set;for(const a of s){const h=a.parent.context.raw();h&&h!==this&&h.removeChild(a),n.add(a.key),a.parent(this)}for(const a of this.realChildren)n.has(a.key)||a.parent(null);this.hasSpawnedChildren=e,this.realChildren=s}parseChildren(e){const t=[],s=Array.isArray(e)?e:[e];for(const n of s)n instanceof Cn&&t.push(n);return t}removeChild(e){this.setParsedChildren(this.children().filter(t=>t!==e))}requiresCache(){return this.cache()||this.opacity()<1||this.compositeOperation()!=="source-over"||this.hasFilters()||this.hasShadow()||this.shaders().length>0}cacheCanvas(){const e=document.createElement("canvas").getContext("2d");if(!e)throw new Error("Could not create a cache canvas");return e}async cachedCanvas(){const e=this.cacheCanvas(),t=this.worldSpaceCacheBBox(),s=this.localToWorld();return e.canvas.width=t.width,e.canvas.height=t.height,e.setTransform(s.a,s.b,s.c,s.d,s.e-t.x,s.f-t.y),await this.draw(e),e}getCacheBBox(){return new pe}cacheBBox(){const e=this.getCacheBBox(),t=this.children(),s=this.cachePadding();if(t.length===0)return e.addSpacing(s);const n=e.corners;for(const h of t){const l=h.fullCacheBBox(),u=h.localToParent();n.push(...l.corners.map(d=>Nt(d,u)))}return pe.fromPoints(...n).addSpacing(s)}fullCacheBBox(){const e=this.compositeToLocal(),t=Jt(this.shadowOffset(),e),s=Ua(this.shadowBlur(),e),n=this.cacheBBox().expand(this.filters.blur()*2+s);return t.x<0?(n.x+=t.x,n.width-=t.x):n.width+=t.x,t.y<0?(n.y+=t.y,n.height-=t.y):n.height+=t.y,n}worldSpaceCacheBBox(){const e=pe.fromSizeCentered(this.view().size()),t=pe.fromPoints(...e.transformCorners(this.view().localToWorld())),s=pe.fromPoints(...this.cacheBBox().transformCorners(this.localToWorld())).pixelPerfect.expand(2);return t.intersection(s)}parentWorldSpaceCacheBBox(){var e;return((e=this.findAncestor(t=>t.requiresCache()))==null?void 0:e.worldSpaceCacheBBox())??new pe(C.zero,Rn().getSize())}setupDrawFromCache(e){if(e.globalCompositeOperation=this.compositeOperation(),e.globalAlpha*=this.opacity(),this.hasFilters()&&(e.filter=this.filterString()),this.hasShadow()){const s=this.compositeToWorld(),n=Jt(this.shadowOffset(),s),a=Ua(this.shadowBlur(),s);e.shadowColor=this.shadowColor().serialize(),e.shadowBlur=a,e.shadowOffsetX=n.x,e.shadowOffsetY=n.y}const t=this.worldToLocal();e.transform(t.a,t.b,t.c,t.d,t.e,t.f)}renderFromSource(e,t,s,n){this.setupDrawFromCache(e);const a=this.compositeOverride();e.drawImage(t,s,n),a>0&&(e.save(),e.globalAlpha*=a,e.globalCompositeOperation="source-over",e.drawImage(t,s,n),e.restore())}shaderCanvas(e,t){var g,y;const s=this.shaders();if(s.length===0)return null;const n=Rn(),a=n.getRealSize(),h=this.parentWorldSpaceCacheBBox(),l=new DOMMatrix().scaleSelf(a.width/h.width,a.height/-h.height).translateSelf(h.x/-a.width,h.y/a.height-1),u=this.worldSpaceCacheBBox(),d=new DOMMatrix().scaleSelf(a.width/u.width,a.height/-u.height).translateSelf(u.x/-a.width,u.y/a.height-1).invertSelf(),p=n.shaders.getGL();n.shaders.copyTextures(e,t),n.shaders.clear();for(const x of s){const v=n.shaders.getProgram(x.fragment);if(v){if(x.uniforms)for(const[_,o]of Object.entries(x.uniforms)){const c=p.getUniformLocation(v,_);if(c===null)continue;const f=fs(o);typeof f=="number"?p.uniform1f(c,f):"toUniform"in f?f.toUniform(p,c):f.length===1?p.uniform1f(c,f[0]):f.length===2?p.uniform2f(c,f[0],f[1]):f.length===3?p.uniform3f(c,f[0],f[1],f[2]):f.length===4&&p.uniform4f(c,f[0],f[1],f[2],f[3])}p.uniform1f(p.getUniformLocation(v,Cl),this.view2D.globalTime()),p.uniform1i(p.getUniformLocation(v,Cl),n.playback.frame),p.uniformMatrix4fv(p.getUniformLocation(v,jg),!1,d.toFloat32Array()),p.uniformMatrix4fv(p.getUniformLocation(v,qg),!1,l.toFloat32Array()),(g=x.setup)==null||g.call(x,p,v),n.shaders.render(),(y=x.teardown)==null||y.call(x,p,v)}}return p.canvas}async render(e){if(!(this.absoluteOpacity()<=0)){if(e.save(),this.transformContext(e),this.requiresCache()){const t=this.worldSpaceCacheBBox();if(t.width!==0&&t.height!==0){const s=(await this.cachedCanvas()).canvas,n=this.shaderCanvas(e.canvas,s);n?this.renderFromSource(e,n,0,0):this.renderFromSource(e,s,t.position.x,t.position.y)}}else await this.draw(e);e.restore()}}async draw(e){await this.drawChildren(e)}async drawChildren(e){for(const t of this.sortedChildren())await t.render(e)}drawOverlay(e,t){const s=this.cacheBBox().transformCorners(t),n=this.getCacheBBox().transformCorners(t);e.strokeStyle="white",e.lineWidth=1,e.beginPath(),Mi(e,s),e.closePath(),e.stroke(),e.strokeStyle="blue",e.beginPath(),Mi(e,n),e.closePath(),e.stroke()}transformContext(e){const t=this.localToParent();e.transform(t.a,t.b,t.c,t.d,t.e,t.f)}hit(e){let t=null;const s=Nt(e,this.localToParent().inverse()),n=this.children();for(let a=n.length-1;a>=0&&(t=n[a].hit(s),!t);a--);return t}collectAsyncResources(){for(const e of this.children())e.collectAsyncResources()}async toPromise(){do await ye.consumePromises(),this.collectAsyncResources();while(ye.hasPromises());return this}getState(){const e={};for(const{key:t,meta:s,signal:n}of this)!s.cloneable||t in e||(e[t]=n());return e}applyState(e,t,s=Bs){if(t===void 0)for(const a in e){const h=this.signalByKey(a);h&&h(e[a])}const n=[];for(const a in e){const h=this.signalByKey(a);e[a]!==h.context.raw()&&n.push(h(e[a],t,s))}return Se(...n)}save(){this.stateStack.push(this.getState())}restore(e,t=Bs){const s=this.stateStack.pop();if(s!==void 0)return this.applyState(s,e,t)}*[Symbol.iterator](){for(const e in this.properties){const t=this.properties[e],s=this.signalByKey(e);yield{meta:t,signal:s,key:e}}}signalByKey(e){return this[e]}reversedChildren(){const e=this.children(),t=[];for(let s=e.length-1;s>=0;s--)t.push(e[s]);return t}};he([ri()],le.prototype,"position",void 0);he([Zs(C),_s(!1),N()],le.prototype,"absolutePosition",void 0);he([W(0),N()],le.prototype,"rotation",void 0);he([_s(!1),N()],le.prototype,"absoluteRotation",void 0);he([W(C.one),ri("scale")],le.prototype,"scale",void 0);he([W(C.zero),ri("skew")],le.prototype,"skew",void 0);he([Zs(C),_s(!1),N()],le.prototype,"absoluteScale",void 0);he([W(0),N()],le.prototype,"zIndex",void 0);he([W(!1),N()],le.prototype,"cache",void 0);he([br("cachePadding")],le.prototype,"cachePadding",void 0);he([W(!1),N()],le.prototype,"composite",void 0);he([W("source-over"),N()],le.prototype,"compositeOperation",void 0);he([rt()],le.prototype,"tweenCompositeOperation",null);he([W(1),bo(r=>me(0,1,r)),N()],le.prototype,"opacity",void 0);he([te()],le.prototype,"absoluteOpacity",null);he([d0()],le.prototype,"filters",void 0);he([W("#0000"),td()],le.prototype,"shadowColor",void 0);he([W(0),N()],le.prototype,"shadowBlur",void 0);he([ri("shadowOffset")],le.prototype,"shadowOffset",void 0);he([W([]),bo(x0),N()],le.prototype,"shaders",void 0);he([te()],le.prototype,"hasFilters",null);he([te()],le.prototype,"hasShadow",null);he([te()],le.prototype,"filterString",null);he([Xc(!1),_s(!1),N()],le.prototype,"spawner",void 0);he([Xc(!1),_s(!1),N()],le.prototype,"children",void 0);he([te()],le.prototype,"spawnedChildren",null);he([te()],le.prototype,"sortedChildren",null);he([te()],le.prototype,"localToWorld",null);he([te()],le.prototype,"worldToLocal",null);he([te()],le.prototype,"worldToParent",null);he([te()],le.prototype,"localToParent",null);he([te()],le.prototype,"compositeToWorld",null);he([te()],le.prototype,"compositeRoot",null);he([te()],le.prototype,"compositeToLocal",null);he([te()],le.prototype,"cacheCanvas",null);he([te()],le.prototype,"cachedCanvas",null);he([te()],le.prototype,"cacheBBox",null);he([te()],le.prototype,"fullCacheBBox",null);he([te()],le.prototype,"worldSpaceCacheBBox",null);he([te()],le.prototype,"parentWorldSpaceCacheBBox",null);le=Cn=he([ut("Node")],le);le.prototype.isClass=!0;var ee=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},Pn;let Q=Pn=class extends le{get columnGap(){return this.gap.x}get rowGap(){return this.gap.y}getX(){return this.isLayoutRoot()?this.x.context.getter():this.computedPosition().x}setX(e){this.x.context.setter(e)}getY(){return this.isLayoutRoot()?this.y.context.getter():this.computedPosition().y}setY(e){this.y.context.setter(e)}get width(){return this.size.x}get height(){return this.size.y}getWidth(){return this.computedSize().width}setWidth(e){this.width.context.setter(e)}*tweenWidth(e,t,s,n){const a=this.desiredSize().x,h=typeof a!="number"||typeof e!="number";let l;h?l=this.size.x():l=a;let u;h?(this.size.x(e),u=this.size.x()):u=e,this.size.x(l),h&&this.lockSize(),yield*Ps(t,d=>this.size.x(n(l,u,s(d)))),this.size.x(e),h&&this.releaseSize()}getHeight(){return this.computedSize().height}setHeight(e){this.height.context.setter(e)}*tweenHeight(e,t,s,n){const a=this.desiredSize().y,h=typeof a!="number"||typeof e!="number";let l;h?l=this.size.y():l=a;let u;h?(this.size.y(e),u=this.size.y()):u=e,this.size.y(l),h&&this.lockSize(),yield*Ps(t,d=>this.size.y(n(l,u,s(d)))),this.size.y(e),h&&this.releaseSize()}desiredSize(){return{x:this.width.context.getter(),y:this.height.context.getter()}}*tweenSize(e,t,s,n){const a=this.desiredSize();let h;typeof a.x!="number"||typeof a.y!="number"?h=this.size():h=new C(a);let l;typeof e=="object"&&typeof e.x=="number"&&typeof e.y=="number"?l=new C(e):(this.size(e),l=this.size()),this.size(h),this.lockSize(),yield*Ps(t,u=>this.size(n(h,l,s(u)))),this.releaseSize(),this.size(e)}constructor(e){super(e),this.element.dataset.motionCanvasKey=this.key}lockSize(){this.sizeLockCounter(this.sizeLockCounter()+1)}releaseSize(){this.sizeLockCounter(this.sizeLockCounter()-1)}parentTransform(){return this.findAncestor(Jc(Pn))}anchorPosition(){const e=this.computedSize(),t=this.offset();return e.scale(.5).mul(t)}layoutEnabled(){var e;return this.layout()??((e=this.parentTransform())==null?void 0:e.layoutEnabled())??!1}isLayoutRoot(){var e;return!this.layoutEnabled()||!((e=this.parentTransform())!=null&&e.layoutEnabled())}localToParent(){const e=super.localToParent(),t=this.offset();if(!t.exactlyEquals(C.zero)){const s=this.size().mul(t).scale(-.5);e.translateSelf(s.x,s.y)}return e}scalingRotationMatrix(){const e=new DOMMatrix;e.rotateSelf(0,0,this.rotation()),e.scaleSelf(this.scale.x(),this.scale.y());const t=this.offset();if(!t.exactlyEquals(C.zero)){const s=this.size().mul(t).scale(-.5);e.translateSelf(s.x,s.y)}return e}getComputedLayout(){return new pe(this.element.getBoundingClientRect())}computedPosition(){this.requestLayoutUpdate();const e=this.getComputedLayout(),t=new C(e.x+e.width/2*this.offset.x(),e.y+e.height/2*this.offset.y()),s=this.parentTransform();if(s){const n=s.getComputedLayout();t.x-=n.x+(n.width-e.width)/2,t.y-=n.y+(n.height-e.height)/2}return t}computedSize(){return this.requestLayoutUpdate(),this.getComputedLayout().size}requestLayoutUpdate(){const e=this.parentTransform();this.appendedToView()?(e==null||e.requestFontUpdate(),this.updateLayout()):e.requestLayoutUpdate()}appendedToView(){const e=this.isLayoutRoot();return e&&this.view().element.append(this.element),e}updateLayout(){if(this.applyFont(),this.applyFlex(),this.layoutEnabled()){const e=this.layoutChildren();for(const t of e)t.updateLayout()}}layoutChildren(){const e=[...this.children()],t=[],s=[];for(;e.length;){const n=e.shift();n instanceof Pn?n.layoutEnabled()&&(t.push(n),s.push(n.element)):n&&e.unshift(...n.children())}return this.element.replaceChildren(...s),t}requestFontUpdate(){var e;this.appendedToView(),(e=this.parentTransform())==null||e.requestFontUpdate(),this.applyFont()}getCacheBBox(){return pe.fromSizeCentered(this.computedSize())}async draw(e){var t;if(await((t=document.fonts)==null?void 0:t.ready),this.clip()){const s=this.computedSize();if(s.width===0||s.height===0)return;e.beginPath(),e.rect(s.width/-2,s.height/-2,s.width,s.height),e.closePath(),e.clip()}await this.drawChildren(e)}drawOverlay(e,t){const s=this.computedSize(),n=s.mul(this.offset()).scale(.5),a=Nt(n,t),h=pe.fromSizeCentered(s),l=h.transformCorners(t),u=h.addSpacing(this.padding().scale(-1)).transformCorners(t),d=h.addSpacing(this.margin()).transformCorners(t);e.beginPath(),Mi(e,d),Mi(e,l),e.closePath(),e.fillStyle="rgba(255,193,125,0.6)",e.fill("evenodd"),e.beginPath(),Mi(e,l),Mi(e,u),e.closePath(),e.fillStyle="rgba(180,255,147,0.6)",e.fill("evenodd"),e.beginPath(),Mi(e,l),e.closePath(),e.lineWidth=1,e.strokeStyle="white",e.stroke(),e.beginPath(),o0(e,a),e.stroke()}getOriginDelta(e){const t=this.computedSize().scale(.5),s=this.offset().mul(t);return e===st.Middle?s.flipped:Ug(e).mul(t).sub(s)}moveOffset(e){const t=this.computedSize().scale(.5),s=this.offset().mul(t),n=e.mul(t);this.offset(e),this.position(this.position().add(n).sub(s))}parsePixels(e){return e===null?"":`${e}px`}parseLength(e){return e===null?"":typeof e=="string"?e:`${e}px`}applyFlex(){this.element.style.position=this.isLayoutRoot()?"absolute":"relative";const e=this.desiredSize();this.element.style.width=this.parseLength(e.x),this.element.style.height=this.parseLength(e.y),this.element.style.maxWidth=this.parseLength(this.maxWidth()),this.element.style.minWidth=this.parseLength(this.minWidth()),this.element.style.maxHeight=this.parseLength(this.maxHeight()),this.element.style.minHeight=this.parseLength(this.minHeight()),this.element.style.aspectRatio=this.ratio()===null?"":this.ratio().toString(),this.element.style.marginTop=this.parsePixels(this.margin.top()),this.element.style.marginBottom=this.parsePixels(this.margin.bottom()),this.element.style.marginLeft=this.parsePixels(this.margin.left()),this.element.style.marginRight=this.parsePixels(this.margin.right()),this.element.style.paddingTop=this.parsePixels(this.padding.top()),this.element.style.paddingBottom=this.parsePixels(this.padding.bottom()),this.element.style.paddingLeft=this.parsePixels(this.padding.left()),this.element.style.paddingRight=this.parsePixels(this.padding.right()),this.element.style.flexDirection=this.direction(),this.element.style.flexBasis=this.parseLength(this.basis()),this.element.style.flexWrap=this.wrap(),this.element.style.justifyContent=this.justifyContent(),this.element.style.alignContent=this.alignContent(),this.element.style.alignItems=this.alignItems(),this.element.style.alignSelf=this.alignSelf(),this.element.style.columnGap=this.parseLength(this.gap.x()),this.element.style.rowGap=this.parseLength(this.gap.y()),this.sizeLockCounter()>0?(this.element.style.flexGrow="0",this.element.style.flexShrink="0"):(this.element.style.flexGrow=this.grow().toString(),this.element.style.flexShrink=this.shrink().toString())}applyFont(){if((document.fonts?Array.from(document.fonts).filter(s=>s.status==="loading"):[]).length>0&&ye.collectPromise((async()=>{var s;await((s=document.fonts)==null?void 0:s.ready)})()),this.element.style.fontFamily=this.fontFamily.isInitial()?"":this.fontFamily(),this.element.style.fontSize=this.fontSize.isInitial()?"":`${this.fontSize()}px`,this.element.style.fontStyle=this.fontStyle.isInitial()?"":this.fontStyle(),this.lineHeight.isInitial())this.element.style.lineHeight="";else{const s=this.lineHeight();this.element.style.lineHeight=typeof s=="string"?(parseFloat(s)/100).toString():`${s}px`}if(this.element.style.fontWeight=this.fontWeight.isInitial()?"":this.fontWeight().toString(),this.element.style.letterSpacing=this.letterSpacing.isInitial()?"":`${this.letterSpacing()}px`,this.element.style.textAlign=this.textAlign.isInitial()?"":this.textAlign(),this.textWrap.isInitial()){this.element.style.whiteSpace="";return}const t=this.textWrap();if(typeof t=="boolean"){this.element.style.whiteSpace=t?"normal":"nowrap";return}if(t==="pre"){this.element.style.whiteSpace=t;return}if(t==="balance"){this.element.style.whiteSpace="normal",this.element.style.textWrap=t;return}}dispose(){var e;super.dispose(),(e=this.sizeLockCounter)==null||e.context.dispose(),this.element&&(this.element.remove(),this.element.innerHTML=""),this.element=null,this.styles=null}hit(e){const t=Nt(e,this.localToParent().inverse());return this.cacheBBox().includes(t)?super.hit(e)??this:null}};ee([W(null),To(rf),N()],Q.prototype,"layout",void 0);ee([W(null),N()],Q.prototype,"maxWidth",void 0);ee([W(null),N()],Q.prototype,"maxHeight",void 0);ee([W(null),N()],Q.prototype,"minWidth",void 0);ee([W(null),N()],Q.prototype,"minHeight",void 0);ee([W(null),N()],Q.prototype,"ratio",void 0);ee([br("margin")],Q.prototype,"margin",void 0);ee([br("padding")],Q.prototype,"padding",void 0);ee([W("row"),N()],Q.prototype,"direction",void 0);ee([W(null),N()],Q.prototype,"basis",void 0);ee([W(0),N()],Q.prototype,"grow",void 0);ee([W(1),N()],Q.prototype,"shrink",void 0);ee([W("nowrap"),N()],Q.prototype,"wrap",void 0);ee([W("start"),N()],Q.prototype,"justifyContent",void 0);ee([W("normal"),N()],Q.prototype,"alignContent",void 0);ee([W("stretch"),N()],Q.prototype,"alignItems",void 0);ee([W("auto"),N()],Q.prototype,"alignSelf",void 0);ee([W(0),ri({x:"columnGap",y:"rowGap"})],Q.prototype,"gap",void 0);ee([bi("font-family"),N()],Q.prototype,"fontFamily",void 0);ee([bi("font-size",parseFloat),N()],Q.prototype,"fontSize",void 0);ee([bi("font-style"),N()],Q.prototype,"fontStyle",void 0);ee([bi("font-weight",parseInt),N()],Q.prototype,"fontWeight",void 0);ee([bi("line-height",parseFloat),N()],Q.prototype,"lineHeight",void 0);ee([bi("letter-spacing",r=>r==="normal"?0:parseFloat(r)),N()],Q.prototype,"letterSpacing",void 0);ee([bi("white-space",r=>r==="pre"?"pre":r==="normal"),N()],Q.prototype,"textWrap",void 0);ee([W("inherit"),N()],Q.prototype,"textDirection",void 0);ee([bi("text-align"),N()],Q.prototype,"textAlign",void 0);ee([W({x:null,y:null}),ri({x:"width",y:"height"})],Q.prototype,"size",void 0);ee([rt()],Q.prototype,"tweenWidth",null);ee([rt()],Q.prototype,"tweenHeight",null);ee([te()],Q.prototype,"desiredSize",null);ee([rt()],Q.prototype,"tweenSize",null);ee([ri("offset")],Q.prototype,"offset",void 0);ee([ai(st.Middle)],Q.prototype,"middle",void 0);ee([ai(st.Top)],Q.prototype,"top",void 0);ee([ai(st.Bottom)],Q.prototype,"bottom",void 0);ee([ai(st.Left)],Q.prototype,"left",void 0);ee([ai(st.Right)],Q.prototype,"right",void 0);ee([ai(st.TopLeft)],Q.prototype,"topLeft",void 0);ee([ai(st.TopRight)],Q.prototype,"topRight",void 0);ee([ai(st.BottomLeft)],Q.prototype,"bottomLeft",void 0);ee([ai(st.BottomRight)],Q.prototype,"bottomRight",void 0);ee([W(!1),N()],Q.prototype,"clip",void 0);ee([W(0),N()],Q.prototype,"sizeLockCounter",void 0);ee([te()],Q.prototype,"parentTransform",null);ee([te()],Q.prototype,"anchorPosition",null);ee([te()],Q.prototype,"layoutEnabled",null);ee([te()],Q.prototype,"isLayoutRoot",null);ee([te()],Q.prototype,"scalingRotationMatrix",null);ee([te()],Q.prototype,"computedPosition",null);ee([te()],Q.prototype,"computedSize",null);ee([te()],Q.prototype,"requestLayoutUpdate",null);ee([te()],Q.prototype,"appendedToView",null);ee([te()],Q.prototype,"updateLayout",null);ee([te()],Q.prototype,"layoutChildren",null);ee([te()],Q.prototype,"requestFontUpdate",null);ee([te()],Q.prototype,"applyFlex",null);ee([te()],Q.prototype,"applyFont",null);Q=Pn=ee([ut("Layout")],Q);function ai(r){return(e,t)=>{N()(e,t),_s(!1)(e,t);const s=Ki(e,t);s.parser=n=>new C(n),s.getter=function(){const n=this.computedSize().getOriginOffset(r);return Nt(n,this.localToParent())},s.setter=function(n){return this.position(rs(n,a=>{const h=this.getOriginDelta(r);return Jt(h,this.scalingRotationMatrix()).flipped.add(a)})),this}}}Qs(Q.prototype,r=>{r.element=document.createElement("div"),r.element.style.display="flex",r.element.style.boxSizing="border-box",r.styles=getComputedStyle(r.element)});var ft=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};let Ye=class extends Q{rippleSize(){return hc(this.rippleStrength(),0,50)}constructor(e){super(e),this.rippleStrength=ps(0)}applyText(e){e.direction=this.textDirection(),this.element.dir=this.textDirection()}applyStyle(e){e.fillStyle=Ba(this.fill(),e),e.strokeStyle=Ba(this.stroke(),e),e.lineWidth=this.lineWidth(),e.lineJoin=this.lineJoin(),e.lineCap=this.lineCap(),e.setLineDash(this.lineDash()),e.lineDashOffset=this.lineDashOffset(),this.antialiased()||(e.filter="url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxmaWx0ZXIgaWQ9ImZpbHRlciIgeD0iMCIgeT0iMCIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj48ZmVDb21wb25lbnRUcmFuc2Zlcj48ZmVGdW5jUiB0eXBlPSJpZGVudGl0eSIvPjxmZUZ1bmNHIHR5cGU9ImlkZW50aXR5Ii8+PGZlRnVuY0IgdHlwZT0iaWRlbnRpdHkiLz48ZmVGdW5jQSB0eXBlPSJkaXNjcmV0ZSIgdGFibGVWYWx1ZXM9IjAgMSIvPjwvZmVDb21wb25lbnRUcmFuc2Zlcj48L2ZpbHRlcj48L3N2Zz4=#filter)")}async draw(e){this.drawShape(e),this.clip()&&e.clip(this.getPath()),await this.drawChildren(e)}drawShape(e){const t=this.getPath(),s=this.lineWidth()>0&&this.stroke()!==null,n=this.fill()!==null;e.save(),this.applyStyle(e),this.drawRipple(e),this.strokeFirst()?(s&&e.stroke(t),n&&e.fill(t)):(n&&e.fill(t),s&&e.stroke(t)),e.restore()}getCacheBBox(){return super.getCacheBBox().expand(this.lineWidth()/2)}getPath(){return new Path2D}getRipplePath(){return new Path2D}drawRipple(e){const t=this.rippleStrength();if(t>0){const s=this.getRipplePath();e.save(),e.globalAlpha*=se(.54,0,t),e.fill(s),e.restore()}}*ripple(e=1){this.rippleStrength(0),yield*this.rippleStrength(1,e,cc),this.rippleStrength(0)}};ft([ed()],Ye.prototype,"fill",void 0);ft([ed()],Ye.prototype,"stroke",void 0);ft([W(!1),N()],Ye.prototype,"strokeFirst",void 0);ft([W(0),N()],Ye.prototype,"lineWidth",void 0);ft([W("miter"),N()],Ye.prototype,"lineJoin",void 0);ft([W("butt"),N()],Ye.prototype,"lineCap",void 0);ft([W([]),N()],Ye.prototype,"lineDash",void 0);ft([W(0),N()],Ye.prototype,"lineDashOffset",void 0);ft([W(!0),N()],Ye.prototype,"antialiased",void 0);ft([te()],Ye.prototype,"rippleSize",null);ft([te()],Ye.prototype,"getPath",null);ft([rt()],Ye.prototype,"ripple",null);Ye=ft([ut("Shape")],Ye);var It=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};let nt=class extends Ye{desiredSize(){return this.childrenBBox().size}constructor(e){super(e),this.canHaveSubpath=!1}percentageToDistance(e){return me(0,this.baseArcLength(),this.startOffset()+this.offsetArcLength()*e)}distanceToPercentage(e){return(e-this.startOffset())/this.offsetArcLength()}baseArcLength(){return this.profile().arcLength}offsetArcLength(){const e=this.startOffset(),t=this.endOffset(),s=this.baseArcLength();return me(0,s,s-e-t)}arcLength(){return this.offsetArcLength()*Math.abs(this.start()-this.end())}completion(){return Math.abs(this.start()-this.end())}processSubpath(e,t,s){}curveDrawingInfo(){const e=new Path2D;let t=new Path2D;const s=this.profile();let n=this.percentageToDistance(this.start()),a=this.percentageToDistance(this.end());n>a&&([n,a]=[a,n]);const h=a-n,l=Math.min(h/2,this.arrowSize());this.startArrow()&&(n+=l/2),this.endArrow()&&(a-=l/2);let u=0,d=null,p=null,g=null,y=null;for(const x of s.segments){const v=u;if(u+=x.arcLength,u<n)continue;const _=(n-v)/x.arcLength,o=(a-v)/x.arcLength,c=me(0,1,_),f=me(0,1,o);this.canHaveSubpath&&g&&!x.getPoint(0).position.equals(g)&&(e.addPath(t),this.processSubpath(t,d,g),t=new Path2D,d=null);const[m,S]=x.draw(t,c,f,d===null);if(d===null&&(d=m.position,p=m.normal.flipped.perpendicular),g=S.position,y=S.normal.flipped.perpendicular,u>a)break}return this.closed()&&this.start.isInitial()&&this.end.isInitial()&&this.startOffset.isInitial()&&this.endOffset.isInitial()&&t.closePath(),this.processSubpath(t,d,g),e.addPath(t),{startPoint:d??C.zero,startTangent:p??C.right,endPoint:g??C.zero,endTangent:y??C.right,arrowSize:l,path:e,startOffset:n}}getPointAtDistance(e){return kl(this.profile(),e+this.startOffset())}getPointAtPercentage(e){return kl(this.profile(),this.percentageToDistance(e))}getComputedLayout(){return this.offsetComputedLayout(super.getComputedLayout())}offsetComputedLayout(e){return e.position=e.position.sub(this.childrenBBox().center),e}getPath(){return this.curveDrawingInfo().path}getCacheBBox(){const e=this.childrenBBox(),t=this.startArrow()||this.endArrow()?this.arrowSize():0,s=this.lineWidth(),n=this.lineWidthCoefficient();return e.expand(Math.max(0,t,s*n))}lineWidthCoefficient(){return this.lineCap()==="square"?.5*1.4143:.5}requiresProfile(){return!this.start.isInitial()||!this.startOffset.isInitial()||!this.startArrow.isInitial()||!this.end.isInitial()||!this.endOffset.isInitial()||!this.endArrow.isInitial()}drawShape(e){super.drawShape(e),(this.startArrow()||this.endArrow())&&this.drawArrows(e)}drawArrows(e){const{startPoint:t,startTangent:s,endPoint:n,endTangent:a,arrowSize:h}=this.curveDrawingInfo();h<.001||(e.save(),e.beginPath(),this.endArrow()&&this.drawArrow(e,n,a.flipped,h),this.startArrow()&&this.drawArrow(e,t,s,h),e.fillStyle=Ba(this.stroke(),e),e.closePath(),e.fill(),e.restore())}drawArrow(e,t,s,n){const a=s.perpendicular,h=t.add(s.scale(-n/2));Er(e,h),ei(e,h.add(s.add(a).scale(n))),ei(e,h.add(s.sub(a).scale(n))),ei(e,h),e.closePath()}};It([W(!1),N()],nt.prototype,"closed",void 0);It([W(0),N()],nt.prototype,"start",void 0);It([W(0),N()],nt.prototype,"startOffset",void 0);It([W(!1),N()],nt.prototype,"startArrow",void 0);It([W(1),N()],nt.prototype,"end",void 0);It([W(0),N()],nt.prototype,"endOffset",void 0);It([W(!1),N()],nt.prototype,"endArrow",void 0);It([W(24),N()],nt.prototype,"arrowSize",void 0);It([te()],nt.prototype,"arcLength",null);It([te()],nt.prototype,"curveDrawingInfo",null);nt=It([ut("Curve")],nt);var en=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};let je=class extends nt{constructor(e){super(e)}profile(){return v0(this.childrenBBox(),this.radius(),this.smoothCorners(),this.cornerSharpness())}desiredSize(){return{x:this.width.context.getter(),y:this.height.context.getter()}}offsetComputedLayout(e){return e}childrenBBox(){return pe.fromSizeCentered(this.computedSize())}getPath(){if(this.requiresProfile())return this.curveDrawingInfo().path;const e=new Path2D,t=this.radius(),s=this.smoothCorners(),n=this.cornerSharpness(),a=pe.fromSizeCentered(this.size());return Dl(e,a,t,s,n),e}getCacheBBox(){return super.getCacheBBox().expand(this.rippleSize())}getRipplePath(){const e=new Path2D,t=this.rippleSize(),s=this.radius().addScalar(t),n=this.smoothCorners(),a=this.cornerSharpness(),h=pe.fromSizeCentered(this.size()).expand(t);return Dl(e,h,s,n,a),e}};en([br("radius")],je.prototype,"radius",void 0);en([W(!1),N()],je.prototype,"smoothCorners",void 0);en([W(.6),N()],je.prototype,"cornerSharpness",void 0);en([te()],je.prototype,"profile",null);je=en([ut("Rect")],je);var Vt=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},Zi;const S0="\nThe `playbackRate` of a `Video` cannot be reactive.\n\nMake sure to use a concrete value and not a function:\n\n```ts wrong\nvideo.playbackRate(() => 7);\n```\n\n```ts correct\nvideo.playbackRate(7);\n```\n\nIf you're using a signal, extract its value before passing it to the property:\n\n```ts wrong\nvideo.playbackRate(mySignal);\n```\n\n```ts correct\nvideo.playbackRate(mySignal());\n```\n";let qe=Zi=class extends je{constructor(e){super(e),this.lastTime=-1,this.isSchedulingPlay=!1,this.awaitCanPlay()||this.scheduleSeek(this.time()),e.play&&this.play(),this.volume=e.volume??1,this.awaitCanPlay()||this.setVolume(this.volume)}isPlaying(){return this.playing()}getCurrentTime(){return this.clampTime(this.time())}getDuration(){try{const e=this.mediaElement(),t=e instanceof HTMLVideoElement,s=e instanceof HTMLAudioElement;return this.isIOS()&&(t||s)?2:e.duration}catch{return 0}}getVolume(){return this.volume}getUrl(){try{return this.mediaElement().src}catch{return this.src()}}dispose(){this.playing(!1),this.time.save(),this.remove(),super.dispose()}completion(){return this.clampTime(this.time())/this.getDuration()}setCurrentTime(e){try{const t=this.mediaElement();if(t.readyState<2)return;t.currentTime=e,this.lastTime=e,t.seeking&&ye.collectPromise(new Promise(s=>{const n=()=>{s(),t.removeEventListener("seeked",n)};t.addEventListener("seeked",n)}))}catch{this.lastTime=e}}setVolume(e){e<0&&console.warn("volumes cannot be negative - the value will be clamped to 0."),this.volume=e;try{const t=this.mediaElement();if(t.volume=Math.min(Math.max(e,0),1),e>1){if(this.allowVolumeAmplificationInPreview()){this.amplify(t,e);return}console.warn(`you have set the volume of node ${this.key} to ${e} - your video will be exported with the correct volume, but the browser does not support volumes higher than 1 by default. To enable volume amplification in the preview, set the "allowVolumeAmplificationInPreview" of your <Video/> or <Audio/> tag to true. Note that amplification for previews will not work if you use autoplay within the player due to browser autoplay policies: https://developer.chrome.com/blog/autoplay/#webaudio.`)}}catch{}}amplify(e,t){const s=`${this.src()}/${this.key}`;if(Zi.amplificationPool[s]){Zi.amplificationPool[s].gainNode.gain.value=t;return}const n=new AudioContext,a=n.createMediaElementSource(e),h=n.createGain();if(h.gain.value=t,a.connect(h),h.connect(n.destination),Zi.amplificationPool[s]={audioContext:n,sourceNode:a,gainNode:h},typeof window>"u"||n.state!=="suspended")return;const l=()=>{Zi.amplificationPool[s].audioContext.resume(),window.removeEventListener("click",l)};window.addEventListener("click",l)}setPlaybackRate(e){let t;if(Bt(e)?(t=e(),Ue().warn({message:"Invalid value set as the playback rate",remarks:S0,inspect:this.key,stack:new Error().stack})):t=e,this.playbackRate.context.setter(t),this.playing())if(t===0)this.pause();else{const s=Os().time,n=s(),a=this.time();this.time(()=>this.clampTime(a+(s()-n)*t))}}scheduleSeek(e){setTimeout(()=>{try{const t=this.mediaElement();this.waitForCanPlay(t,()=>{t.currentTime=e})}catch{setTimeout(()=>this.scheduleSeek(e),50)}},0)}waitForCanPlay(e,t){if(e.readyState>=3){t();return}const s=()=>{t(),e.removeEventListener("canplay",s),e.removeEventListener("canplaythrough",s)},n=()=>{var l;const a=this.getErrorReason((l=e.error)==null?void 0:l.code),h=this.src();console.log(`ERROR: Error loading video: src="${h}", ${a}`),console.log(`Media element src: "${e.src}"`),e.removeEventListener("error",n),e.removeEventListener("canplay",s),e.removeEventListener("canplaythrough",s)};e.addEventListener("canplay",s),e.addEventListener("canplaythrough",s),e.addEventListener("error",n)}waitForCanPlayNecessary(e){return e.readyState>=2?!1:this.awaitCanPlay()||this.view().playbackState()===tt.Rendering}play(){console.log("=== Media.play() called ==="),this.playing(!0),this.schedulePlay()}schedulePlay(){if(this.isSchedulingPlay)return;this.isSchedulingPlay=!0;let e=null;try{e=Os().time}catch{this.isSchedulingPlay=!1,this.simplePlay();return}setTimeout(()=>{if(!this.playing()){this.isSchedulingPlay=!1;return}setTimeout(()=>{try{const s=this.mediaElement();this.waitForCanPlay(s,()=>{this.playing()&&e&&this.actuallyPlay(s,e),this.isSchedulingPlay=!1})}catch{this.isSchedulingPlay=!1,setTimeout(()=>this.schedulePlay(),100)}},10)},0)}simplePlay(){setTimeout(()=>{try{const e=this.mediaElement();if(!e.src||e.src.includes("undefined"))return;if(e.paused&&this.playing()){e.playbackRate=this.playbackRate();const t=e.play();t!==void 0&&t.then(()=>{console.log("Simple play started successfully")}).catch(s=>{s.name!=="AbortError"&&console.warn("Error in simple play:",s),this.playing(!1)})}}catch{return}},10)}actuallyPlay(e,t){if(console.log("=== actuallyPlay called ==="),console.log("Media element:",e),console.log("Media src:",e.src),console.log("Media paused:",e.paused),console.log("Media readyState:",e.readyState),!this.playing()){console.log("Playing state is false, aborting actuallyPlay");return}if(e.playbackRate=this.playbackRate(),e.paused){console.log("Media is paused, calling play()");const a=e.play();a!==void 0&&a.then(()=>{console.log("Media play() promise resolved - should be playing now"),console.log("Post-play media paused:",e.paused),console.log("Post-play media currentTime:",e.currentTime)}).catch(h=>{h.name!=="AbortError"&&console.warn("Error playing media:",h),this.playing(!1)})}else console.log("Media is already playing");const s=t(),n=e.currentTime;this.time(()=>this.clampTime(n+(t()-s)*this.playbackRate()))}pause(){this.playing(!1),this.time.save(),setTimeout(()=>{try{this.mediaElement().pause()}catch{}},0)}clampTime(e){const t=this.getDuration();return this.loop()&&(e%=t),me(0,t,e)}collectAsyncResources(){super.collectAsyncResources(),this.seekedMedia(),this.setVolume(this.volume)}autoPlayBasedOnTwick(){const e=this.view().playbackState();(e===tt.Playing||e===tt.Presenting)&&!this.playing()?(console.log("Auto-starting media playback via play() method"),this.play()):e===tt.Paused&&this.playing()&&(console.log("Auto-pausing media playback via pause() method"),this.pause())}getErrorReason(e){let t;switch(e){case 1:t="MEDIA_ERR_ABORTED";break;case 2:t="MEDIA_ERR_NETWORK. This might be a 404 error.";break;case 3:t="MEDIA_ERR_DECODE. This might be an issue with your video file.";break;case 4:t="MEDIA_ERR_SRC_NOT_SUPPORTED. If you are sure that the path to the video is correct, this might be a CORS error.";break;default:t="UNKNOWN"}return t}isIOS(){return typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}};qe.amplificationPool={};Vt([W(""),N()],qe.prototype,"src",void 0);Vt([W(!1),N()],qe.prototype,"loop",void 0);Vt([W(1),N()],qe.prototype,"playbackRate",void 0);Vt([W(0),N()],qe.prototype,"time",void 0);Vt([W(!1),N()],qe.prototype,"playing",void 0);Vt([W(!0),N()],qe.prototype,"awaitCanPlay",void 0);Vt([W(!1),N()],qe.prototype,"allowVolumeAmplificationInPreview",void 0);Vt([te()],qe.prototype,"completion",null);Vt([te()],qe.prototype,"amplify",null);qe=Zi=Vt([ut("Media")],qe);var Ar=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},Ji;let ti=Ji=class extends qe{constructor(e){super(e)}mediaElement(){return this.audio()}seekedMedia(){return this.seekedAudio()}fastSeekedMedia(){return this.fastSeekedAudio()}audio(){const e=this.src(),t=`${this.key}/${e||"pending"}`;let s=Ji.pool[t];if(!s)s=document.createElement("audio"),s.crossOrigin="anonymous",e&&e!=="undefined"&&(s.src=e),Ji.pool[t]=s;else if(e&&e!=="undefined"&&s.src!==e){s.src=e,delete Ji.pool[t];const a=`${this.key}/${e}`;Ji.pool[a]=s}return(!e||e==="undefined")&&ye.collectPromise(new Promise(a=>{const h=()=>{const l=this.src();l&&l!=="undefined"?a():setTimeout(h,10)};h()})),this.waitForCanPlayNecessary(s)&&ye.collectPromise(new Promise(a=>{this.waitForCanPlay(s,a)})),s}seekedAudio(){const e=this.audio();if(e.addEventListener("ended",()=>{this.pause()}),!(this.time()<e.duration))return this.pause(),e;const t=this.clampTime(this.time());return e.playbackRate=this.playbackRate(),e.paused||e.pause(),this.lastTime===t||this.setCurrentTime(t),e}fastSeekedAudio(){const e=this.audio();if(!(this.time()<e.duration))return this.pause(),e;const t=this.clampTime(this.time());if(e.playbackRate=this.playbackRate(),this.lastTime===t)return e;const s=this.playing()&&t<e.duration&&e.playbackRate>0;return s?e.paused&&ye.collectPromise(e.play()):e.paused||e.pause(),Math.abs(e.currentTime-t)>.3?this.setCurrentTime(t):s||(e.currentTime=t),e}async draw(e){this.autoPlayBasedOnTwick();const t=this.view().playbackState();t===tt.Playing||t===tt.Presenting?this.fastSeekedAudio():this.seekedAudio(),e.save(),e.restore(),await this.drawChildren(e)}};ti.pool={};Ar([te()],ti.prototype,"audio",null);Ar([te()],ti.prototype,"seekedAudio",null);Ar([te()],ti.prototype,"fastSeekedAudio",null);ti=Ji=Ar([ut("Audio")],ti);var Es=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},Na;let ii=Na=class extends je{constructor(e){super({composite:!0,fontFamily:"Roboto",fontSize:48,lineHeight:"120%",textWrap:!1,fontStyle:"normal",...e}),this.view2D=this,Na.shadowRoot.append(this.element),this.applyFlex()}dispose(){this.removeChildren(),super.dispose()}async render(e){this.computedSize(),this.computedPosition(),await super.render(e)}findKey(e){return Rn().getNode(e)??null}requestLayoutUpdate(){this.updateLayout()}requestFontUpdate(){this.applyFont()}view(){return this}};Es([W(tt.Paused),N()],ii.prototype,"playbackState",void 0);Es([W(0),N()],ii.prototype,"globalTime",void 0);Es([W(0),N()],ii.prototype,"fps",void 0);Es([N()],ii.prototype,"assetHash",void 0);Es([hr(()=>{const r="twick-2d-frame";let e=document.querySelector(`#${r}`);return e||(e=document.createElement("div"),e.id=r,e.style.position="absolute",e.style.pointerEvents="none",e.style.top="0",e.style.left="0",e.style.fontFeatureSettings="normal",e.style.opacity="0",e.style.overflow="hidden",document.body.prepend(e)),e.shadowRoot??e.attachShadow({mode:"open"})})],ii,"shadowRoot",void 0);ii=Na=Es([ut("View2D")],ii);var _0=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};class os extends Tr{constructor(e,t,s,n,a,h){super(),this.startPoint=e,this.radius=t,this.xAxisRotationDegree=s,this.largeArcFlag=n,this.sweepFlag=a,this.endPoint=h,this.xAxisRotation=this.xAxisRotationDegree*pi,this.radius=new C(Math.abs(t.x),Math.abs(t.y));const l=Ie.fromRotation(-s).domMatrix,u=Jt(e.sub(h).div(2),l),d=u.x*u.x/(t.x*t.x)+u.y*u.y/(t.y*t.y);if(d>1){const _=Math.sqrt(d);t.x=_*t.x,t.y=_*t.y}const p=new C(t.ctg*u.y,t.perpendicular.ctg*u.x).scale(Math.sqrt(1/(u.x*u.x/(t.x*t.x)+u.y*u.y/(t.y*t.y))-1)*(n===a?-1:1));this.xAxisRotationMatrix=Ie.fromRotation(s).domMatrix;const g=Jt(p,this.xAxisRotationMatrix);this.center=g.add(e.add(h).div(2));const y=u.sub(p).div(t),x=u.scale(-1).sub(p).div(t);this.startAngle=y.radians,this.deltaAngle=C.angleBetween(y,x)%(Math.PI*2),this.sweepFlag===0&&this.deltaAngle>0&&(this.deltaAngle-=Math.PI*2),this.sweepFlag===1&&this.deltaAngle<0&&(this.deltaAngle+=Math.PI*2),os.el.setAttribute("d",`M ${this.startPoint.x} ${this.startPoint.y} A ${this.radius.x} ${this.radius.y} ${this.xAxisRotationDegree} ${this.largeArcFlag} ${this.sweepFlag} ${this.endPoint.x} ${this.endPoint.y}`),this.length=os.el.getTotalLength();const v=new pe(os.el.getBBox());this.points=[v.topLeft,v.bottomRight]}getAnglePosition(e){return Jt(this.radius.mul(C.fromRadians(e)),this.xAxisRotationMatrix).add(this.center)}getAngleDerivative(e){const t=new C(-this.radius.x*Math.sin(e),this.radius.y*Math.cos(e));return Jt(t,this.xAxisRotationMatrix)}draw(e,t,s,n){const a=this.startAngle+this.deltaAngle*t,h=this.startAngle+this.deltaAngle*s,l=this.getPoint(t),u=this.getPoint(s);return n&&e.moveTo(l.position.x,l.position.y),e.ellipse(this.center.x,this.center.y,this.radius.x,this.radius.y,this.xAxisRotation,a,h,this.sweepFlag===0),[l,u]}getPoint(e){const t=this.startAngle+e*this.deltaAngle,s=this.getAngleDerivative(t).normalized;return{position:e===0?this.startPoint:e===1?this.endPoint:this.getAnglePosition(t),tangent:s,normal:s.perpendicular}}get arcLength(){return this.length}}_0([hr(()=>{const r=document.createElementNS("http://www.w3.org/2000/svg","svg"),e=document.createElementNS("http://www.w3.org/2000/svg","path");return r.appendChild(e),ii.shadowRoot.appendChild(r),e})],os,"el",void 0);function E0(r,e,t,s,n=!1){const a={arcLength:0,minSin:1,segments:[]};if(t<e){const p=Math.floor((e-t)/(Math.PI*2))+1;t+=Math.PI*2*p}else if(t>e+Math.PI*2){const p=Math.floor((t-e)/(Math.PI*2));t-=Math.PI*2*p}const h=(e+t)/2,l=r.mul(C.fromRadians(e)),u=r.mul(C.fromRadians(t)),d=r.mul(C.fromRadians(h)).scale(n?-1:1);return s&&$a(a,new ts(C.zero,l)),Ml(a,r,l,d,e,h,n),Ml(a,r,d,u,h,t,n),s&&$a(a,new ts(u,C.zero)),a}function $a(r,e){r.segments.push(e),r.arcLength+=e.arcLength}function Ml(r,e,t,s,n,a,h){const l=Math.abs(n-a)<=180?1:0,u=n>a?0:1,d=h?0:1;$a(r,new os(t,e,0,0,l^d^u,s))}var tn=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};let Gi=class extends nt{constructor(e){super(e)}profile(){return E0(this.size().scale(.5),this.startAngle()*pi,this.endAngle()*pi,this.closed(),this.counterclockwise())}desiredSize(){return{x:this.width.context.getter(),y:this.height.context.getter()}}offsetComputedLayout(e){return e}childrenBBox(){return pe.fromSizeCentered(this.computedSize())}getPath(){return this.requiresProfile()?this.curveDrawingInfo().path:this.createPath()}getRipplePath(){return this.createPath(this.rippleSize())}getCacheBBox(){return super.getCacheBBox().expand(this.rippleSize())}createPath(e=0){const t=new Path2D,s=this.startAngle()*pi;let n=this.endAngle()*pi;const a=this.size().scale(.5).add(e),h=this.closed();if(n>s+Math.PI*2){const l=Math.floor((n-s)/(Math.PI*2));n-=Math.PI*2*l}return h&&t.moveTo(0,0),t.ellipse(0,0,a.x,a.y,0,s,n,this.counterclockwise()),h&&t.closePath(),t}};tn([W(0),N()],Gi.prototype,"startAngle",void 0);tn([W(360),N()],Gi.prototype,"endAngle",void 0);tn([W(!1),N()],Gi.prototype,"counterclockwise",void 0);tn([te()],Gi.prototype,"profile",null);Gi=tn([ut("Circle")],Gi);var Ai=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},Dn;const T0=`
|
|
82
82
|
The image won't be visible unless you specify a source:
|
|
83
83
|
|
|
84
84
|
\`\`\`tsx
|
|
@@ -96,50 +96,50 @@ property to \`null\`:
|
|
|
96
96
|
|
|
97
97
|
[Learn more](https://motioncanvas.io/docs/media#images) about working with
|
|
98
98
|
images.
|
|
99
|
-
`;let
|
|
99
|
+
`;let mt=Dn=class extends je{constructor(e){super(e),"src"in e||Ue().warn({message:"No source specified for the image",remarks:T0,inspect:this.key})}desiredSize(){const e=super.desiredSize();if(e.x===null&&e.y===null){const t=this.image();return{x:t.naturalWidth,y:t.naturalHeight}}return e}image(){const e=this.src(),t=new URL(e,window.location.origin);if(t.origin===window.location.origin){const n=this.view().assetHash();t.searchParams.set("asset-hash",n)}let s=Dn.pool[e];return s||(s=document.createElement("img"),s.crossOrigin="anonymous",s.src=e,Dn.pool[e]=s),s.complete||ye.collectPromise(new Promise((n,a)=>{s.addEventListener("load",n),s.addEventListener("error",()=>a(new lo({message:"Failed to load an image",remarks:`The <code>src</code> property was set to:
|
|
100
100
|
<pre><code>${e}</code></pre>
|
|
101
101
|
Make sure that source is correct and that the image exists.<br/>
|
|
102
102
|
<a target='_blank' href='https://motioncanvas.io/docs/media#images'>Learn more</a>
|
|
103
|
-
about working with images.`,inspect:this.key})))})),s}imageCanvas(){const e=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});if(!e)throw new Error("Could not create an image canvas");return e}filledImageCanvas(){const e=this.imageCanvas(),t=this.image();return e.canvas.width=t.naturalWidth,e.canvas.height=t.naturalHeight,e.imageSmoothingEnabled=this.smoothing(),e.drawImage(t,0,0),e}async draw(e){this.drawShape(e);const t=this.alpha();if(t>0){const s=
|
|
103
|
+
about working with images.`,inspect:this.key})))})),s}imageCanvas(){const e=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});if(!e)throw new Error("Could not create an image canvas");return e}filledImageCanvas(){const e=this.imageCanvas(),t=this.image();return e.canvas.width=t.naturalWidth,e.canvas.height=t.naturalHeight,e.imageSmoothingEnabled=this.smoothing(),e.drawImage(t,0,0),e}async draw(e){this.drawShape(e);const t=this.alpha();if(t>0){const s=pe.fromSizeCentered(this.computedSize());e.save(),e.clip(this.getPath()),t<1&&(e.globalAlpha*=t),e.imageSmoothingEnabled=this.smoothing(),Zc(e,this.image(),s),e.restore()}this.clip()&&e.clip(this.getPath()),await this.drawChildren(e)}applyFlex(){super.applyFlex();const e=this.image();this.element.style.aspectRatio=(this.ratio()??e.naturalWidth/e.naturalHeight).toString()}getColorAtPoint(e){const t=this.computedSize(),s=this.naturalSize(),n=new C(e).add(this.computedSize().scale(.5)).mul(s.div(t).safe);return this.getPixelColor(n)}naturalSize(){const e=this.image();return new C(e.naturalWidth,e.naturalHeight)}getPixelColor(e){const t=this.filledImageCanvas(),s=new C(e),n=t.getImageData(s.x,s.y,1,1).data;return new we({r:n[0],g:n[1],b:n[2],a:n[3]/255})}collectAsyncResources(){super.collectAsyncResources(),this.image()}};mt.pool={};Ai([N()],mt.prototype,"src",void 0);Ai([W(1),N()],mt.prototype,"alpha",void 0);Ai([W(!0),N()],mt.prototype,"smoothing",void 0);Ai([te()],mt.prototype,"image",null);Ai([te()],mt.prototype,"imageCanvas",null);Ai([te()],mt.prototype,"filledImageCanvas",null);Ai([te()],mt.prototype,"naturalSize",null);mt=Dn=Ai([ut("Img")],mt);var Io=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a};class Ir extends mt{constructor(e){super({...e,src:null})}svgUrl(){const e=this.icon().replace(":","/"),t=encodeURIComponent(this.color().hex());return`https://api.iconify.design/${e}.svg?color=${t}`}getSrc(){return this.svgUrl()}setSrc(e){e!==null&&Ue().warn("The Icon Component does not accept setting the `src`. If you need access to `src`, use '<Img/>` instead.")}}Io([N()],Ir.prototype,"icon",void 0);Io([W("white"),td()],Ir.prototype,"color",void 0);Io([te()],Ir.prototype,"svgUrl",null);var wr=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},kn;const id=Symbol("Txt");let At=kn=class extends Ye{constructor({children:e,...t}){super(t),e&&this.text(e)}parentTxt(){const e=this.parent();return!e||!(id in e)?null:e}async draw(e){var d;this.requestFontUpdate(),this.applyStyle(e),await((d=document.fonts)==null?void 0:d.ready),this.applyText(e),e.font=this.styles.font,e.textBaseline="bottom","letterSpacing"in e&&(e.letterSpacing=`${this.letterSpacing()}px`);const t=e.measureText("").fontBoundingBoxAscent,s=this.element.getBoundingClientRect(),{width:n,height:a}=this.size(),h=document.createRange();let l="";const u=new pe;for(const p of this.element.childNodes){if(!p.textContent)continue;h.selectNodeContents(p);const g=h.getBoundingClientRect(),y=n/-2+g.left-s.left,x=a/-2+g.top-s.top+t;u.y===x?(u.width+=g.width,l+=p.textContent):(await this.drawText(e,l,u),u.x=y,u.y=x,u.width=g.width,u.height=g.height,l=p.textContent)}await this.drawText(e,l,u)}async drawText(e,t,s){const n=s.y;t=t.replace(/\s+/g," "),this.lineWidth()<=0?e.fillText(t,s.x,n):this.strokeFirst()?(e.strokeText(t,s.x,n),e.fillText(t,s.x,n)):(e.fillText(t,s.x,n),e.strokeText(t,s.x,n))}getCacheBBox(){const e=this.computedSize(),t=document.createRange();t.selectNodeContents(this.element);const s=t.getBoundingClientRect(),n=this.lineWidth(),a=this.lineJoin()==="miter"?.5*10:.5;return new pe(-e.width/2,-e.height/2,s.width,s.height).expand([0,this.fontSize()*.5]).expand(n*a)}applyFlex(){super.applyFlex(),this.element.style.display="inline"}updateLayout(){if(this.applyFont(),this.applyFlex(),this.justifyContent.isInitial()&&(this.element.style.justifyContent=this.styles.getPropertyValue("text-align")),this.styles.whiteSpace!=="nowrap"&&this.styles.whiteSpace!=="pre")if(this.element.innerText="",kn.segmenter)for(const t of kn.segmenter.segment(this.text()))this.element.appendChild(document.createTextNode(t.segment));else for(const t of this.text().split(""))this.element.appendChild(document.createTextNode(t));else if(this.styles.whiteSpace==="pre"){this.element.innerText="";for(const t of this.text().split(`
|
|
104
104
|
`))this.element.appendChild(document.createTextNode(t+`
|
|
105
|
-
`))}else this.element.innerText=this.text()}};mr([V(""),ho(Vh),N()],yt.prototype,"text",void 0);mr([J()],yt.prototype,"parentTxt",null);mr([Zn(()=>{try{return new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{return null}})],yt,"segmenter",void 0);yt=Tn=mr([nt("TxtLeaf")],yt);["fill","stroke","lineWidth","strokeFirst","lineCap","lineJoin","lineDash","lineDashOffset"].forEach(r=>{yt.prototype[`get${Li(r)}`]=function(){var e;return((e=this.parentTxt())==null?void 0:e[r]())??this[r].context.getInitial()}});var Ws=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},$c,bi;let kt=bi=class extends ze{static b(e){return new bi({...e,fontWeight:700})}static i(e){return new bi({...e,fontStyle:"italic"})}getText(){return this.innerText()}setText(e){const t=this.children();let s=null;for(let n=0;n<t.length;n++){const a=t[n];s===null&&a instanceof yt?s=a:a.parent(null)}s===null?(s=new yt({text:e}),s.parent(this)):s.text(e),this.setParsedChildren([s])}setChildren(e){this.children.context.raw()!==e&&(typeof e=="string"?this.text(e):super.setChildren(e))}*tweenText(e,t,s,n){var p;yield(p=document.fonts)==null?void 0:p.ready;const a=this.children();(a.length!==1||!(a[0]instanceof yt))&&this.text.save();const h=this.childAs(0),l=h.text.context.raw(),u=this.size.context.raw();h.text(e);const d=this.size();h.text(l??ma),this.height()===0&&this.height(d.height),yield*_e(this.size(d,t,s),h.text(e,t,s,n)),this.children.context.setter(e),this.size(u)}getLayout(){return!0}constructor({children:e,text:t,...s}){super(s),this[$c]=!0,this.children(t??e)}innerText(){const e=this.childrenAs();let t="";for(const s of e)t+=s.text();return t}parentTxt(){const e=this.parent();return e instanceof bi?e:null}parseChildren(e){const t=[],s=Array.isArray(e)?e:[e];for(const n of s)n instanceof bi||n instanceof yt?t.push(n):typeof n=="string"&&t.push(new yt({text:n}));return t}applyFlex(){super.applyFlex(),this.element.style.display=this.findAncestor(Uc(bi))?"inline":"block"}async draw(e){var t;await((t=document.fonts)==null?void 0:t.ready),await this.drawChildren(e)}};$c=Nc;Ws([V(""),N()],kt.prototype,"text",void 0);Ws([et()],kt.prototype,"tweenText",null);Ws([J()],kt.prototype,"innerText",null);Ws([J()],kt.prototype,"parentTxt",null);kt=bi=Ws([nt("Txt")],kt);["fill","stroke","lineWidth","strokeFirst","lineCap","lineJoin","lineDash","lineDashOffset"].forEach(r=>{kt.prototype[`getDefault${Li(r)}`]=function(e){var t;return((t=this.parentTxt())==null?void 0:t[r]())??e}});const K=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},Zg=Number.isSafeInteger||function(r){return typeof r=="number"&&Math.abs(r)<=Jg},Jg=Number.MAX_SAFE_INTEGER||9007199254740991;let Q=function(r){return r.NETWORK_ERROR="networkError",r.MEDIA_ERROR="mediaError",r.KEY_SYSTEM_ERROR="keySystemError",r.MUX_ERROR="muxError",r.OTHER_ERROR="otherError",r}({}),P=function(r){return r.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",r.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",r.KEY_SYSTEM_NO_SESSION="keySystemNoSession",r.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",r.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",r.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",r.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",r.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",r.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",r.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",r.MANIFEST_LOAD_ERROR="manifestLoadError",r.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",r.MANIFEST_PARSING_ERROR="manifestParsingError",r.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",r.LEVEL_EMPTY_ERROR="levelEmptyError",r.LEVEL_LOAD_ERROR="levelLoadError",r.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",r.LEVEL_PARSING_ERROR="levelParsingError",r.LEVEL_SWITCH_ERROR="levelSwitchError",r.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",r.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",r.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",r.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",r.FRAG_LOAD_ERROR="fragLoadError",r.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",r.FRAG_DECRYPT_ERROR="fragDecryptError",r.FRAG_PARSING_ERROR="fragParsingError",r.FRAG_GAP="fragGap",r.REMUX_ALLOC_ERROR="remuxAllocError",r.KEY_LOAD_ERROR="keyLoadError",r.KEY_LOAD_TIMEOUT="keyLoadTimeOut",r.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",r.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",r.BUFFER_APPEND_ERROR="bufferAppendError",r.BUFFER_APPENDING_ERROR="bufferAppendingError",r.BUFFER_STALLED_ERROR="bufferStalledError",r.BUFFER_FULL_ERROR="bufferFullError",r.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",r.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",r.ASSET_LIST_LOAD_ERROR="assetListLoadError",r.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",r.ASSET_LIST_PARSING_ERROR="assetListParsingError",r.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",r.INTERNAL_EXCEPTION="internalException",r.INTERNAL_ABORTED="aborted",r.ATTACH_MEDIA_ERROR="attachMediaError",r.UNKNOWN="unknown",r}({}),_=function(r){return r.MEDIA_ATTACHING="hlsMediaAttaching",r.MEDIA_ATTACHED="hlsMediaAttached",r.MEDIA_DETACHING="hlsMediaDetaching",r.MEDIA_DETACHED="hlsMediaDetached",r.MEDIA_ENDED="hlsMediaEnded",r.STALL_RESOLVED="hlsStallResolved",r.BUFFER_RESET="hlsBufferReset",r.BUFFER_CODECS="hlsBufferCodecs",r.BUFFER_CREATED="hlsBufferCreated",r.BUFFER_APPENDING="hlsBufferAppending",r.BUFFER_APPENDED="hlsBufferAppended",r.BUFFER_EOS="hlsBufferEos",r.BUFFERED_TO_END="hlsBufferedToEnd",r.BUFFER_FLUSHING="hlsBufferFlushing",r.BUFFER_FLUSHED="hlsBufferFlushed",r.MANIFEST_LOADING="hlsManifestLoading",r.MANIFEST_LOADED="hlsManifestLoaded",r.MANIFEST_PARSED="hlsManifestParsed",r.LEVEL_SWITCHING="hlsLevelSwitching",r.LEVEL_SWITCHED="hlsLevelSwitched",r.LEVEL_LOADING="hlsLevelLoading",r.LEVEL_LOADED="hlsLevelLoaded",r.LEVEL_UPDATED="hlsLevelUpdated",r.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",r.LEVELS_UPDATED="hlsLevelsUpdated",r.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",r.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",r.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",r.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",r.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",r.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",r.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",r.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",r.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",r.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",r.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",r.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",r.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",r.CUES_PARSED="hlsCuesParsed",r.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",r.INIT_PTS_FOUND="hlsInitPtsFound",r.FRAG_LOADING="hlsFragLoading",r.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",r.FRAG_LOADED="hlsFragLoaded",r.FRAG_DECRYPTED="hlsFragDecrypted",r.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",r.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",r.FRAG_PARSING_METADATA="hlsFragParsingMetadata",r.FRAG_PARSED="hlsFragParsed",r.FRAG_BUFFERED="hlsFragBuffered",r.FRAG_CHANGED="hlsFragChanged",r.FPS_DROP="hlsFpsDrop",r.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",r.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",r.ERROR="hlsError",r.DESTROYING="hlsDestroying",r.KEY_LOADING="hlsKeyLoading",r.KEY_LOADED="hlsKeyLoaded",r.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",r.BACK_BUFFER_REACHED="hlsBackBufferReached",r.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",r.ASSET_LIST_LOADING="hlsAssetListLoading",r.ASSET_LIST_LOADED="hlsAssetListLoaded",r.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",r.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",r.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",r.INTERSTITIAL_STARTED="hlsInterstitialStarted",r.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",r.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",r.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",r.INTERSTITIAL_ENDED="hlsInterstitialEnded",r.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",r.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",r.EVENT_CUE_ENTER="hlsEventCueEnter",r}({});var ue={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},X={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Ni{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class e0{constructor(e,t,s,n=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ni(e),this.fast_=new Ni(t),this.defaultTTFB_=n,this.ttfb_=new Ni(e)}update(e,t){const{slow_:s,fast_:n,ttfb_:a}=this;s.halfLife!==e&&(this.slow_=new Ni(e,s.getEstimate(),s.getTotalWeight())),n.halfLife!==t&&(this.fast_=new Ni(t,n.getEstimate(),n.getTotalWeight())),a.halfLife!==e&&(this.ttfb_=new Ni(e,a.getEstimate(),a.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,n=e/1e3,a=s/n;this.fast_.sample(n,a),this.slow_.sample(n,a)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function t0(r,e,t){return(e=s0(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function Te(){return Te=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(r[s]=t[s])}return r},Te.apply(null,arguments)}function _l(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(r,n).enumerable})),t.push.apply(t,s)}return t}function xe(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?_l(Object(t),!0).forEach(function(s){t0(r,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):_l(Object(t)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(t,s))})}return r}function i0(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var s=t.call(r,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function s0(r){var e=i0(r,"string");return typeof e=="symbol"?e:e+""}class Jt{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=ni,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const ni=function(){},n0={trace:ni,debug:ni,log:ni,warn:ni,info:ni,error:ni};function Ra(){return Te({},n0)}function r0(r,e){const t=self.console[r];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${r}] >`):ni}function El(r,e,t){return e[r]?e[r].bind(e):r0(r,t)}const Ca=Ra();function a0(r,e,t){const s=Ra();if(typeof console=="object"&&r===!0||typeof r=="object"){const n=["debug","log","info","warn","error"];n.forEach(a=>{s[a]=El(a,r,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.2`)}catch{return Ra()}n.forEach(a=>{Ca[a]=El(a,r)})}else Te(Ca,s);return s}const pe=Ca;function pi(r=!0){return typeof self>"u"?void 0:(r||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function o0(r){return typeof self<"u"&&r===self.ManagedMediaSource}function Gc(r,e){const t=Object.keys(r),s=Object.keys(e),n=t.length,a=s.length;return!n||!a||n===a&&!t.some(h=>s.indexOf(h)===-1)}function st(r,e=!1){if(typeof TextDecoder<"u"){const d=new TextDecoder("utf-8").decode(r);if(e){const p=d.indexOf("\0");return p!==-1?d.substring(0,p):d}return d.replace(/\0/g,"")}const t=r.length;let s,n,a,h="",l=0;for(;l<t;){if(s=r[l++],s===0&&e)return h;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:h+=String.fromCharCode(s);break;case 12:case 13:n=r[l++],h+=String.fromCharCode((s&31)<<6|n&63);break;case 14:n=r[l++],a=r[l++],h+=String.fromCharCode((s&15)<<12|(n&63)<<6|(a&63)<<0);break}}return h}const Et={hexDump:function(r){let e="";for(let t=0;t<r.length;t++){let s=r[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}};function l0(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Vr={exports:{}},Tl;function h0(){return Tl||(Tl=1,function(r,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,n=/^(?=([^\/?#]*))\1([^]*)$/,a=/(?:\/|^)\.(?=\/)/g,h=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,l={buildAbsoluteURL:function(u,d,p){if(p=p||{},u=u.trim(),d=d.trim(),!d){if(!p.alwaysNormalize)return u;var g=l.parseURL(u);if(!g)throw new Error("Error trying to parse base URL.");return g.path=l.normalizePath(g.path),l.buildURLFromParts(g)}var y=l.parseURL(d);if(!y)throw new Error("Error trying to parse relative URL.");if(y.scheme)return p.alwaysNormalize?(y.path=l.normalizePath(y.path),l.buildURLFromParts(y)):d;var v=l.parseURL(u);if(!v)throw new Error("Error trying to parse base URL.");if(!v.netLoc&&v.path&&v.path[0]!=="/"){var x=n.exec(v.path);v.netLoc=x[1],v.path=x[2]}v.netLoc&&!v.path&&(v.path="/");var E={scheme:v.scheme,netLoc:y.netLoc,path:null,params:y.params,query:y.query,fragment:y.fragment};if(!y.netLoc&&(E.netLoc=v.netLoc,y.path[0]!=="/"))if(!y.path)E.path=v.path,y.params||(E.params=v.params,y.query||(E.query=v.query));else{var o=v.path,c=o.substring(0,o.lastIndexOf("/")+1)+y.path;E.path=l.normalizePath(c)}return E.path===null&&(E.path=p.alwaysNormalize?l.normalizePath(y.path):y.path),l.buildURLFromParts(E)},parseURL:function(u){var d=s.exec(u);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[6]||""}:null},normalizePath:function(u){for(u=u.split("").reverse().join("").replace(a,"");u.length!==(u=u.replace(h,"")).length;);return u.split("").reverse().join("")},buildURLFromParts:function(u){return u.scheme+u.netLoc+u.path+u.params+u.query+u.fragment}};r.exports=l})()}(Vr)),Vr.exports}var po=h0();class go{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var Ee={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class zc{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,d0(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let n;s.length===1?n=(t==null?void 0:t.byteRangeEndOffset)||0:n=parseInt(s[1]),this._byteRange=[n,parseInt(s[0])+n]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[Ee.AUDIO]:null,[Ee.VIDEO]:null,[Ee.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new go),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=po.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Ee.AUDIO]=null,e[Ee.VIDEO]=null,e[Ee.AUDIOVIDEO]=null}}function Ne(r){return r.sn!=="initSegment"}class Kr extends zc{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange){const e=this.byteRange[0],t=this.byteRange[1];if(K(e)&&K(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const s=Object.keys(this.levelkeys);if(s.length===1)return this._decryptdata=this.levelkeys[s[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=K(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),s=t.length;if(s>1||s===1&&this.levelkeys[t[0]].encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!K(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Ne(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,n,a,h=!1){const{elementaryStreams:l}=this,u=l[e];if(!u){l[e]={startPTS:t,endPTS:s,startDTS:n,endDTS:a,partial:h};return}u.startPTS=Math.min(u.startPTS,t),u.endPTS=Math.max(u.endPTS,s),u.startDTS=Math.min(u.startDTS,n),u.endDTS=Math.max(u.endDTS,a)}}class c0 extends zc{constructor(e,t,s,n,a){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=n;const h=e.enumeratedString("BYTERANGE");h&&this.setByteRange(h,a),a&&(this.fragOffset=a.fragOffset+a.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function Hc(r,e){const t=Object.getPrototypeOf(r);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||Hc(t,e)}}function d0(r,e){const t=Hc(r,e);t&&(t.enumerable=!0,Object.defineProperty(r,e,t))}const Nn=Math.pow(2,32)-1,u0=[].push,Vc={video:1,audio:2,id3:3,text:4};function Pe(r){return String.fromCharCode.apply(null,r)}function Kc(r,e){const t=r[e]<<8|r[e+1];return t<0?65536+t:t}function ie(r,e){const t=Yc(r,e);return t<0?4294967296+t:t}function bl(r,e){let t=ie(r,e);return t*=Math.pow(2,32),t+=ie(r,e+4),t}function Yc(r,e){return r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}function Yr(r,e,t){r[e]=t>>24,r[e+1]=t>>16&255,r[e+2]=t>>8&255,r[e+3]=t&255}function f0(r){const e=r.byteLength;for(let t=0;t<e;){const s=ie(r,t);if(s>8&&r[t+4]===109&&r[t+5]===111&&r[t+6]===111&&r[t+7]===102)return!0;t=s>1?t+s:e}return!1}function oe(r,e){const t=[];if(!e.length)return t;const s=r.byteLength;for(let n=0;n<s;){const a=ie(r,n),h=Pe(r.subarray(n+4,n+8)),l=a>1?n+a:s;if(h===e[0])if(e.length===1)t.push(r.subarray(n+8,l));else{const u=oe(r.subarray(n+8,l),e.slice(1));u.length&&u0.apply(t,u)}n=l}return t}function p0(r){const e=[],t=r[0];let s=8;const n=ie(r,s);s+=4;let a=0,h=0;t===0?(a=ie(r,s),h=ie(r,s+4),s+=8):(a=bl(r,s),h=bl(r,s+8),s+=16),s+=2;let l=r.length+h;const u=Kc(r,s);s+=2;for(let d=0;d<u;d++){let p=s;const g=ie(r,p);p+=4;const y=g&2147483647;if((g&2147483648)>>>31===1)return pe.warn("SIDX has hierarchical references (not supported)"),null;const x=ie(r,p);p+=4,e.push({referenceSize:y,subsegmentDuration:x,info:{duration:x/n,start:l,end:l+y-1}}),l+=y,p+=4,s=p}return{earliestPresentationTime:a,timescale:n,version:t,referencesCount:u,references:e}}function Wc(r){const e=[],t=oe(r,["moov","trak"]);for(let n=0;n<t.length;n++){const a=t[n],h=oe(a,["tkhd"])[0];if(h){let l=h[0];const u=ie(h,l===0?12:20),d=oe(a,["mdia","mdhd"])[0];if(d){l=d[0];const p=ie(d,l===0?12:20),g=oe(a,["mdia","hdlr"])[0];if(g){const y=Pe(g.subarray(8,12)),v={soun:Ee.AUDIO,vide:Ee.VIDEO}[y],x=oe(a,["mdia","minf","stbl","stsd"])[0],E=g0(x);v?(e[u]={timescale:p,type:v,stsd:E},e[v]=xe({timescale:p,id:u},E)):e[u]={timescale:p,type:y,stsd:E}}}}}return oe(r,["moov","mvex","trex"]).forEach(n=>{const a=ie(n,4),h=e[a];h&&(h.default={duration:ie(n,12),flags:ie(n,20)})}),e}function g0(r){const e=r.subarray(8),t=e.subarray(86),s=Pe(e.subarray(4,8));let n=s,a;const h=s==="enca"||s==="encv";if(h){const d=oe(e,[s])[0].subarray(s==="enca"?28:78);oe(d,["sinf"]).forEach(g=>{const y=oe(g,["schm"])[0];if(y){const v=Pe(y.subarray(4,8));if(v==="cbcs"||v==="cenc"){const x=oe(g,["frma"])[0];x&&(n=Pe(x))}}})}const l=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const u=oe(t,["avcC"])[0];u&&u.length>3&&(n+="."+nn(u[1])+nn(u[2])+nn(u[3]),a=sn(l==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const u=oe(e,[s])[0],d=oe(u.subarray(28),["esds"])[0];if(d&&d.length>7){let p=4;if(d[p++]!==3)break;p=Wr(d,p),p+=2;const g=d[p++];if(g&128&&(p+=2),g&64&&(p+=d[p++]),d[p++]!==4)break;p=Wr(d,p);const y=d[p++];if(y===64)n+="."+nn(y);else break;if(p+=12,d[p++]!==5)break;p=Wr(d,p);const v=d[p++];let x=(v&248)>>3;x===31&&(x+=1+((v&7)<<3)+((d[p]&224)>>5)),n+="."+x}break}case"hvc1":case"hev1":{const u=oe(t,["hvcC"])[0];if(u&&u.length>12){const d=u[1],p=["","A","B","C"][d>>6],g=d&31,y=ie(u,2),v=(d&32)>>5?"H":"L",x=u[12],E=u.subarray(6,12);n+="."+p+g,n+="."+y.toString(16).toUpperCase(),n+="."+v+x;let o="";for(let c=E.length;c--;){const f=E[c];(f||o)&&(o="."+f.toString(16).toUpperCase()+o)}n+=o}a=sn(l=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{n=sn(n,t)||n;break}case"vp09":{const u=oe(t,["vpcC"])[0];if(u&&u.length>6){const d=u[4],p=u[5],g=u[6]>>4&15;n+="."+_t(d)+"."+_t(p)+"."+_t(g)}break}case"av01":{const u=oe(t,["av1C"])[0];if(u&&u.length>2){const d=u[1]>>>5,p=u[1]&31,g=u[2]>>>7?"H":"M",y=(u[2]&64)>>6,v=(u[2]&32)>>5,x=d===2&&y?v?12:10:y?10:8,E=(u[2]&16)>>4,o=(u[2]&8)>>3,c=(u[2]&4)>>2,f=u[2]&3;n+="."+d+"."+_t(p)+g+"."+_t(x)+"."+E+"."+o+c+f+"."+_t(1)+"."+_t(1)+"."+_t(1)+"."+0,a=sn("dav1",t)}break}}return{codec:n,encrypted:h,supplemental:a}}function sn(r,e){const t=oe(e,["dvvC"]),s=t.length?t[0]:oe(e,["dvcC"])[0];if(s){const n=s[2]>>1&127,a=s[2]<<5&32|s[3]>>3&31;return r+"."+_t(n)+"."+_t(a)}}function Wr(r,e){const t=e+5;for(;r[e++]&128&&e<t;);return e}function nn(r){return("0"+r.toString(16).toUpperCase()).slice(-2)}function _t(r){return(r<10?"0":"")+r}function m0(r,e){if(!r||!e)return r;const t=e.keyId;return t&&e.isCommonEncryption&&oe(r,["moov","trak"]).forEach(n=>{const h=oe(n,["mdia","minf","stbl","stsd"])[0].subarray(8);let l=oe(h,["enca"]);const u=l.length>0;u||(l=oe(h,["encv"])),l.forEach(d=>{const p=u?d.subarray(28):d.subarray(78);oe(p,["sinf"]).forEach(y=>{const v=jc(y);if(v){const x=v.subarray(8,24);x.some(E=>E!==0)||(pe.log(`[eme] Patching keyId in 'enc${u?"a":"v"}>sinf>>tenc' box: ${Et.hexDump(x)} -> ${Et.hexDump(t)}`),v.set(t,8))}})})}),r}function jc(r){const e=oe(r,["schm"])[0];if(e){const t=Pe(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return oe(r,["schi","tenc"])[0]}return null}function y0(r,e){return oe(e,["moof","traf"]).reduce((t,s)=>{const n=oe(s,["tfdt"])[0],a=n[0],h=oe(s,["tfhd"]).reduce((l,u)=>{const d=ie(u,4),p=r[d];if(p){let g=ie(n,4);if(a===1){if(g===Nn)return pe.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),l;g*=Nn+1,g+=ie(n,8)}const y=p.timescale||9e4,v=g/y;if(K(v)&&(l===null||v<l))return v}return l},null);return h!==null&&K(h)&&(t===null||h<t)?h:t},null)}function x0(r,e){let t=0,s=0,n=0;const a=oe(r,["moof","traf"]);for(let h=0;h<a.length;h++){const l=a[h],u=oe(l,["tfhd"])[0],d=ie(u,4),p=e[d];if(!p)continue;const g=p.default,y=ie(u,0)|(g==null?void 0:g.flags);let v=g==null?void 0:g.duration;y&8&&(y&2?v=ie(u,12):v=ie(u,8));const x=p.timescale||9e4,E=oe(l,["trun"]);for(let o=0;o<E.length;o++){if(t=v0(E[o]),!t&&v){const c=ie(E[o],4);t=v*c}p.type===Ee.VIDEO?s+=t/x:p.type===Ee.AUDIO&&(n+=t/x)}}if(s===0&&n===0){let h=1/0,l=0,u=0;const d=oe(r,["sidx"]);for(let p=0;p<d.length;p++){const g=p0(d[p]);if(g!=null&&g.references){h=Math.min(h,g.earliestPresentationTime/g.timescale);const y=g.references.reduce((v,x)=>v+x.info.duration||0,0);l=Math.max(l,y+g.earliestPresentationTime/g.timescale),u=l-h}}if(u&&K(u))return u}return s||n}function v0(r){const e=ie(r,0);let t=8;e&1&&(t+=4),e&4&&(t+=4);let s=0;const n=ie(r,4);for(let a=0;a<n;a++){if(e&256){const h=ie(r,t);s+=h,t+=4}e&512&&(t+=4),e&1024&&(t+=4),e&2048&&(t+=4)}return s}function S0(r,e,t){oe(e,["moof","traf"]).forEach(s=>{oe(s,["tfhd"]).forEach(n=>{const a=ie(n,4),h=r[a];if(!h)return;const l=h.timescale||9e4;oe(s,["tfdt"]).forEach(u=>{const d=u[0],p=t*l;if(p){let g=ie(u,4);if(d===0)g-=p,g=Math.max(g,0),Yr(u,4,g);else{g*=Math.pow(2,32),g+=ie(u,8),g-=p,g=Math.max(g,0);const y=Math.floor(g/(Nn+1)),v=Math.floor(g%(Nn+1));Yr(u,4,y),Yr(u,8,v)}}})})})}function _0(r){const e={valid:null,remainder:null},t=oe(r,["moof"]);if(t.length<2)return e.remainder=r,e;const s=t[t.length-1];return e.valid=r.slice(0,s.byteOffset-8),e.remainder=r.slice(s.byteOffset-8),e}function ct(r,e){const t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function Al(r,e){const t=[],s=e.samples,n=e.timescale,a=e.id;let h=!1;return oe(s,["moof"]).map(u=>{const d=u.byteOffset-8;oe(u,["traf"]).map(g=>{const y=oe(g,["tfdt"]).map(v=>{const x=v[0];let E=ie(v,4);return x===1&&(E*=Math.pow(2,32),E+=ie(v,8)),E/n})[0];return y!==void 0&&(r=y),oe(g,["tfhd"]).map(v=>{const x=ie(v,4),E=ie(v,0)&16777215,o=(E&1)!==0,c=(E&2)!==0,f=(E&8)!==0;let m=0;const S=(E&16)!==0;let T=0;const b=(E&32)!==0;let A=8;x===a&&(o&&(A+=8),c&&(A+=4),f&&(m=ie(v,A),A+=4),S&&(T=ie(v,A),A+=4),b&&(A+=4),e.type==="video"&&(h=yr(e.codec)),oe(g,["trun"]).map(I=>{const L=I[0],w=ie(I,0)&16777215,C=(w&1)!==0;let k=0;const U=(w&4)!==0,G=(w&256)!==0;let $=0;const z=(w&512)!==0;let j=0;const Y=(w&1024)!==0,F=(w&2048)!==0;let O=0;const te=ie(I,4);let ee=8;C&&(k=ie(I,ee),ee+=4),U&&(ee+=4);let se=k+d;for(let he=0;he<te;he++){if(G?($=ie(I,ee),ee+=4):$=m,z?(j=ie(I,ee),ee+=4):j=T,Y&&(ee+=4),F&&(L===0?O=ie(I,ee):O=Yc(I,ee),ee+=4),e.type===Ee.VIDEO){let W=0;for(;W<j;){const me=ie(s,se);if(se+=4,E0(h,s[se])){const De=s.subarray(se,se+me);mo(De,h?2:1,r+O/n,t)}se+=me,W+=me+4}}r+=$/n}}))})})}),t}function yr(r){if(!r)return!1;const e=r.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function E0(r,e){if(r){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function mo(r,e,t,s){const n=qc(r);let a=0;a+=e;let h=0,l=0,u=0;for(;a<n.length;){h=0;do{if(a>=n.length)break;u=n[a++],h+=u}while(u===255);l=0;do{if(a>=n.length)break;u=n[a++],l+=u}while(u===255);const d=n.length-a;let p=a;if(l<d)a+=l;else if(l>d){pe.error(`Malformed SEI payload. ${l} is too small, only ${d} bytes left to parse.`);break}if(h===4){if(n[p++]===181){const y=Kc(n,p);if(p+=2,y===49){const v=ie(n,p);if(p+=4,v===1195456820){const x=n[p++];if(x===3){const E=n[p++],o=31&E,c=64&E,f=c?2+o*3:0,m=new Uint8Array(f);if(c){m[0]=E;for(let S=1;S<f;S++)m[S]=n[p++]}s.push({type:x,payloadType:h,pts:t,bytes:m})}}}}}else if(h===5&&l>16){const g=[];for(let x=0;x<16;x++){const E=n[p++].toString(16);g.push(E.length==1?"0"+E:E),(x===3||x===5||x===7||x===9)&&g.push("-")}const y=l-16,v=new Uint8Array(y);for(let x=0;x<y;x++)v[x]=n[p++];s.push({payloadType:h,pts:t,uuid:g.join(""),userData:st(v),userDataBytes:v})}}}function qc(r){const e=r.byteLength,t=[];let s=1;for(;s<e-2;)r[s]===0&&r[s+1]===0&&r[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return r;const n=e-t.length,a=new Uint8Array(n);let h=0;for(s=0;s<n;h++,s++)h===t[0]&&(h++,t.shift()),a[s]=r[h];return a}function T0(r){const e=r[0];let t="",s="",n=0,a=0,h=0,l=0,u=0,d=0;if(e===0){for(;Pe(r.subarray(d,d+1))!=="\0";)t+=Pe(r.subarray(d,d+1)),d+=1;for(t+=Pe(r.subarray(d,d+1)),d+=1;Pe(r.subarray(d,d+1))!=="\0";)s+=Pe(r.subarray(d,d+1)),d+=1;s+=Pe(r.subarray(d,d+1)),d+=1,n=ie(r,12),a=ie(r,16),l=ie(r,20),u=ie(r,24),d=28}else if(e===1){d+=4,n=ie(r,d),d+=4;const g=ie(r,d);d+=4;const y=ie(r,d);for(d+=4,h=2**32*g+y,Zg(h)||(h=Number.MAX_SAFE_INTEGER,pe.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=ie(r,d),d+=4,u=ie(r,d),d+=4;Pe(r.subarray(d,d+1))!=="\0";)t+=Pe(r.subarray(d,d+1)),d+=1;for(t+=Pe(r.subarray(d,d+1)),d+=1;Pe(r.subarray(d,d+1))!=="\0";)s+=Pe(r.subarray(d,d+1)),d+=1;s+=Pe(r.subarray(d,d+1)),d+=1}const p=r.subarray(d,r.byteLength);return{schemeIdUri:t,value:s,timeScale:n,presentationTime:h,presentationTimeDelta:a,eventDuration:l,id:u,payload:p}}function b0(r,...e){const t=e.length;let s=8,n=t;for(;n--;)s+=e[n].byteLength;const a=new Uint8Array(s);for(a[0]=s>>24&255,a[1]=s>>16&255,a[2]=s>>8&255,a[3]=s&255,a.set(r,4),n=0,s=8;n<t;n++)a.set(e[n],s),s+=e[n].byteLength;return a}function A0(r,e,t){if(r.byteLength!==16)throw new RangeError("Invalid system id");let s,n;s=0,n=new Uint8Array;let a;s>0?(a=new Uint8Array(4),e.length>0&&new DataView(a.buffer).setUint32(0,e.length,!1)):a=new Uint8Array;const h=new Uint8Array(4);return t&&t.byteLength>0&&new DataView(h.buffer).setUint32(0,t.byteLength,!1),b0([112,115,115,104],new Uint8Array([s,0,0,0]),r,a,n,h,t||new Uint8Array)}function I0(r){const e=[];if(r instanceof ArrayBuffer){const t=r.byteLength;let s=0;for(;s+32<t;){const n=new DataView(r,s),a=w0(n);e.push(a),s+=a.size}}return e}function w0(r){const e=r.getUint32(0),t=r.byteOffset,s=r.byteLength;if(s<e)return{offset:t,size:s};if(r.getUint32(4)!==1886614376)return{offset:t,size:e};const a=r.getUint32(8)>>>24;if(a!==0&&a!==1)return{offset:t,size:e};const h=r.buffer,l=Et.hexDump(new Uint8Array(h,t+12,16)),u=r.getUint32(28);let d=null,p=null;if(a===0){if(e-32<u||u<22)return{offset:t,size:e};p=new Uint8Array(h,t+32,u)}else if(a===1){if(!u||s<t+32+u*16+16)return{offset:t,size:e};d=[];for(let g=0;g<u;g++)d.push(new Uint8Array(h,t+32+g*16,16))}return{version:a,systemId:l,kids:d,data:p,offset:t,size:e}}const Xc=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),rs={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Qc(r,e){const t=rs[e];return!!t&&!!t[r.slice(0,4)]}function Da(r,e,t=!0){return!r.split(",").some(s=>!Zc(s,e,t))}function Zc(r,e,t=!0){var s;const n=pi(t);return(s=n==null?void 0:n.isTypeSupported(Ds(r,e)))!=null?s:!1}function Ds(r,e){return`${e}/mp4;codecs=${r}`}function Il(r){if(r){const e=r.substring(0,4);return rs.video[e]}return 2}function $n(r){const e=Xc();return r.split(",").reduce((t,s)=>{const a=e&&yr(s)?9:rs.video[s];return a?(a*2+t)/(t?3:2):(rs.audio[s]+t)/(t?2:1)},0)}const jr={};function L0(r,e=!0){if(jr[r])return jr[r];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[r];for(let n=0;n<t.length;n++){var s;if(Zc(t[n],"audio",e))return jr[r]=t[n],t[n];if(t[n]==="mp3"&&(s=pi(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return r}const R0=/flac|opus|mp4a\.40\.34/i;function Gn(r,e=!0){return r.replace(R0,t=>L0(t.toLowerCase(),e))}function C0(r,e){const t=[];if(r){const s=r.split(",");for(let n=0;n<s.length;n++)Qc(s[n],"video")||t.push(s[n])}return e&&t.push(e),t.join(",")}function bn(r,e){if(r&&(r.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(r)!==-1))return r;if(e){const t=e.split(",");if(t.length>1){if(r){for(let s=t.length;s--;)if(t[s].substring(0,4)===r.substring(0,4))return t[s]}return t[0]}}return e||r}function D0(r){const e=r.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");if(s.length>2){let n=s.shift()+".";n+=parseInt(s.shift()).toString(16),n+=("000"+parseInt(s.shift()).toString(16)).slice(-4),e[t]=n}}return e.join(",")}function P0(r){if(r.startsWith("av01.")){const e=r.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return r}function wl(r){const e=pi(r)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Jc(r){return r.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const ed={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function td(r,e){return{supported:!1,configurations:e,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:r}}const Ll={};function k0(r,e,t,s,n,a){const h=r.audioCodec?r.audioGroups:null,l=a==null?void 0:a.audioCodec,u=a==null?void 0:a.channels,d=u?parseInt(u):l?1/0:2;let p=null;if(h!=null&&h.length)try{h.length===1&&h[0]?p=e.groups[h[0]].channels:p=h.reduce((g,y)=>{if(y){const v=e.groups[y];if(!v)throw new Error(`Audio track group ${y} not found`);Object.keys(v.channels).forEach(x=>{g[x]=(g[x]||0)+v.channels[x]})}return g},{2:0})}catch{return!0}return r.videoCodec!==void 0&&(r.width>1920&&r.height>1088||r.height>1920&&r.width>1088||r.frameRate>Math.max(s,30)||r.videoRange!=="SDR"&&r.videoRange!==t||r.bitrate>Math.max(n,8e6))||!!p&&K(d)&&Object.keys(p).some(g=>parseInt(g)>d)}function id(r,e,t){const s=r.videoCodec,n=r.audioCodec;if(!s&&!n||!t)return Promise.resolve(ed);const a=[];if(s){const h={width:r.width,height:r.height,bitrate:Math.ceil(Math.max(r.bitrate*.9,r.averageBitrate)),framerate:r.frameRate||30},l=r.videoRange;l!=="SDR"&&(h.transferFunction=l.toLowerCase());const u=s.split(","),d=navigator.userAgent;if(u.some(p=>yr(p))&&Xc())return Promise.resolve(td(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: (${d})`),a));a.push.apply(a,u.map(p=>({type:"media-source",video:xe(xe({},h),{},{contentType:Ds(P0(p),"video")})})))}return n&&r.audioGroups&&r.audioGroups.forEach(h=>{var l;h&&((l=e.groups[h])==null||l.tracks.forEach(u=>{if(u.groupId===h){const d=u.channels||"",p=parseFloat(d);K(p)&&p>2&&a.push.apply(a,n.split(",").map(g=>({type:"media-source",audio:{contentType:Ds(g,"audio"),channels:""+p}})))}}))}),Promise.all(a.map(h=>{const l=M0(h);return Ll[l]||(Ll[l]=t.decodingInfo(h))})).then(h=>({supported:!h.some(l=>!l.supported),configurations:a,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:a,decodingInfoResults:[],error:h}))}function M0(r){const{audio:e,video:t}=r,s=t||e;if(s){const n=Jc(s.contentType);if(t)return`r${t.height}x${t.width}f${Math.ceil(t.framerate)}${t.transferFunction||"sd"}_${n}_${Math.ceil(t.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${n}`}return""}const Pa=["NONE","TYPE-0","TYPE-1",null];function F0(r){return Pa.indexOf(r)>-1}const zn=["SDR","PQ","HLG"];function U0(r){return!!r&&zn.indexOf(r)>-1}var An={No:"",Yes:"YES",v2:"v2"};function Rl(r){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=r,n=s<e/2;return e&&n?t?An.v2:An.Yes:An.No}class Cl{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Ps{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Dl(this._audioGroups,e)}hasSubtitleGroup(e){return Dl(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Dl(r,e){return!e||!r?!1:r.indexOf(e)!==-1}function O0(){if(typeof matchMedia=="function"){const r=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(r.media!==e.media)return r.matches===!0}return!1}function B0(r,e){let t=!1,s=[];if(r&&(t=r!=="SDR",s=[r]),e){s=e.allowedVideoRanges||zn.slice(0);const n=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:n&&O0(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const N0=r=>{const e=new WeakSet;return(t,s)=>{if(r&&(s=r(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},Ae=(r,e)=>JSON.stringify(r,N0(e));function $0(r,e,t,s,n){const a=Object.keys(r),h=s==null?void 0:s.channels,l=s==null?void 0:s.audioCodec,u=n==null?void 0:n.videoCodec,d=h&&parseInt(h)===2;let p=!1,g=!1,y=1/0,v=1/0,x=1/0,E=1/0,o=0,c=[];const{preferHDR:f,allowedVideoRanges:m}=B0(e,n);for(let I=a.length;I--;){const L=r[a[I]];p||(p=L.channels[2]>0),y=Math.min(y,L.minHeight),v=Math.min(v,L.minFramerate),x=Math.min(x,L.minBitrate),m.filter(C=>L.videoRanges[C]>0).length>0&&(g=!0)}y=K(y)?y:0,v=K(v)?v:0;const S=Math.max(1080,y),T=Math.max(30,v);x=K(x)?x:t,t=Math.max(x,t),g||(e=void 0);const b=a.length>1;return{codecSet:a.reduce((I,L)=>{const w=r[L];if(L===I)return I;if(c=g?m.filter(C=>w.videoRanges[C]>0):[],b){if(w.minBitrate>t)return St(L,`min bitrate of ${w.minBitrate} > current estimate of ${t}`),I;if(!w.hasDefaultAudio)return St(L,"no renditions with default or auto-select sound found"),I;if(l&&L.indexOf(l.substring(0,4))%5!==0)return St(L,`audio codec preference "${l}" not found`),I;if(h&&!d){if(!w.channels[h])return St(L,`no renditions with ${h} channel sound found (channels options: ${Object.keys(w.channels)})`),I}else if((!l||d)&&p&&w.channels[2]===0)return St(L,"no renditions with stereo sound found"),I;if(w.minHeight>S)return St(L,`min resolution of ${w.minHeight} > maximum of ${S}`),I;if(w.minFramerate>T)return St(L,`min framerate of ${w.minFramerate} > maximum of ${T}`),I;if(!c.some(C=>w.videoRanges[C]>0))return St(L,`no variants with VIDEO-RANGE of ${Ae(c)} found`),I;if(u&&L.indexOf(u.substring(0,4))%5!==0)return St(L,`video codec preference "${u}" not found`),I;if(w.maxScore<o)return St(L,`max score of ${w.maxScore} < selected max of ${o}`),I}return I&&($n(L)>=$n(I)||w.fragmentError>r[I].fragmentError)?I:(E=w.minIndex,o=w.maxScore,L)},void 0),videoRanges:c,preferHDR:f,minFramerate:v,minBitrate:x,minIndex:E}}function St(r,e){pe.log(`[abr] start candidates with "${r}" ignored because ${e}`)}function sd(r){return r.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const n=t.channels||"2";return s.channels[n]=(s.channels[n]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function G0(r,e,t,s){return r.slice(t,s+1).reduce((n,a,h)=>{if(!a.codecSet)return n;const l=a.audioGroups;let u=n[a.codecSet];u||(n[a.codecSet]=u={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:h,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!l,fragmentError:0}),u.minBitrate=Math.min(u.minBitrate,a.bitrate);const d=Math.min(a.height,a.width);return u.minHeight=Math.min(u.minHeight,d),u.minFramerate=Math.min(u.minFramerate,a.frameRate),u.minIndex=Math.min(u.minIndex,h),u.maxScore=Math.max(u.maxScore,a.score),u.fragmentError+=a.fragmentError,u.videoRanges[a.videoRange]=(u.videoRanges[a.videoRange]||0)+1,l&&l.forEach(p=>{if(!p)return;const g=e.groups[p];g&&(u.hasDefaultAudio=u.hasDefaultAudio||e.hasDefaultAudio?g.hasDefault:g.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(g.channels).forEach(y=>{u.channels[y]=(u.channels[y]||0)+g.channels[y]}))}),n},{})}function Pl(r){if(!r)return r;const{lang:e,assocLang:t,characteristics:s,channels:n,audioCodec:a}=r;return{lang:e,assocLang:t,characteristics:s,channels:n,audioCodec:a}}function wt(r,e,t){if("attrs"in r){const s=e.indexOf(r);if(s!==-1)return s}for(let s=0;s<e.length;s++){const n=e[s];if(Ci(r,n,t))return s}return-1}function Ci(r,e,t){const{groupId:s,name:n,lang:a,assocLang:h,default:l}=r,u=r.forced;return(s===void 0||e.groupId===s)&&(n===void 0||e.name===n)&&(a===void 0||z0(a,e.lang))&&(a===void 0||e.assocLang===h)&&(l===void 0||e.default===l)&&(u===void 0||e.forced===u)&&(!("characteristics"in r)||H0(r.characteristics||"",e.characteristics))&&(t===void 0||t(r,e))}function z0(r,e="--"){return r.length===e.length?r===e:r.startsWith(e)||e.startsWith(r)}function H0(r,e=""){const t=r.split(","),s=e.split(",");return t.length===s.length&&!t.some(n=>s.indexOf(n)===-1)}function Ai(r,e){const{audioCodec:t,channels:s}=r;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function V0(r,e,t,s,n){const a=e[s],l=e.reduce((y,v,x)=>{const E=v.uri;return(y[E]||(y[E]=[])).push(x),y},{})[a.uri];l.length>1&&(s=Math.max.apply(Math,l));const u=a.videoRange,d=a.frameRate,p=a.codecSet.substring(0,4),g=kl(e,s,y=>{if(y.videoRange!==u||y.frameRate!==d||y.codecSet.substring(0,4)!==p)return!1;const v=y.audioGroups,x=t.filter(E=>!v||v.indexOf(E.groupId)!==-1);return wt(r,x,n)>-1});return g>-1?g:kl(e,s,y=>{const v=y.audioGroups,x=t.filter(E=>!v||v.indexOf(E.groupId)!==-1);return wt(r,x,n)>-1})}function kl(r,e,t){for(let s=e;s>-1;s--)if(t(r[s]))return s;for(let s=e+1;s<r.length;s++)if(t(r[s]))return s;return-1}function Hn(r,e){var t;return!!r&&r!==((t=e.loadLevelObj)==null?void 0:t.uri)}class K0 extends Jt{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:n,partCurrent:a,hls:h}=this,{autoLevelEnabled:l,media:u}=h;if(!n||!u)return;const d=performance.now(),p=a?a.stats:n.stats,g=a?a.duration:n.duration,y=d-p.loading.start,v=h.minAutoLevel,x=n.level,E=this._nextAutoLevel;if(p.aborted||p.loaded&&p.loaded===p.total||x<=v){this.clearTimer(),this._nextAutoLevel=-1;return}if(!l)return;const o=E>-1&&E!==x,c=!!t||o;if(!c&&(u.paused||!u.playbackRate||!u.readyState))return;const f=h.mainForwardBufferInfo;if(!c&&f===null)return;const m=this.bwEstimator.getEstimateTTFB(),S=Math.abs(u.playbackRate);if(y<=Math.max(m,1e3*(g/(S*2))))return;const T=f?f.len/S:0,b=p.loading.first?p.loading.first-p.loading.start:-1,A=p.loaded&&b>-1,I=this.getBwEstimate(),L=h.levels,w=L[x],C=Math.max(p.loaded,Math.round(g*(n.bitrate||w.averageBitrate)/8));let k=A?y-b:y;k<1&&A&&(k=Math.min(y,p.loaded*8/I));const U=A?p.loaded*1e3/k:0,G=m/1e3,$=U?(C-p.loaded)/U:C*8/I+G;if($<=T)return;const z=U?U*8:I,j=((s=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,Y=this.hls.config.abrBandWidthUpFactor;let F=Number.POSITIVE_INFINITY,O;for(O=x-1;O>v;O--){const he=L[O].maxBitrate,W=!L[O].details||j;if(F=this.getTimeToLoadFrag(G,z,g*he,W),F<Math.min(T,g+G))break}if(F>=$||F>g*10)return;A?this.bwEstimator.sample(y-Math.min(m,b),p.loaded):this.bwEstimator.sampleTTFB(y);const te=L[O].maxBitrate;this.getBwEstimate()*Y>te&&this.resetEstimator(te);const ee=this.findBestLevel(te,v,O,0,T,1,1);ee>-1&&(O=ee),this.warn(`Fragment ${n.sn}${a?" part "+a.index:""} of level ${x} is loading too slowly;
|
|
105
|
+
`))}else this.element.innerText=this.text()}};wr([W(""),To(oc),N()],At.prototype,"text",void 0);wr([te()],At.prototype,"parentTxt",null);wr([hr(()=>{try{return new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{return null}})],At,"segmenter",void 0);At=kn=wr([ut("TxtLeaf")],At);["fill","stroke","lineWidth","strokeFirst","lineCap","lineJoin","lineDash","lineDashOffset"].forEach(r=>{At.prototype[`get${Ui(r)}`]=function(){var e;return((e=this.parentTxt())==null?void 0:e[r]())??this[r].context.getInitial()}});var sn=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},sd,Di;let $t=Di=class extends Ye{static b(e){return new Di({...e,fontWeight:700})}static i(e){return new Di({...e,fontStyle:"italic"})}getText(){return this.innerText()}setText(e){const t=this.children();let s=null;for(let n=0;n<t.length;n++){const a=t[n];s===null&&a instanceof At?s=a:a.parent(null)}s===null?(s=new At({text:e}),s.parent(this)):s.text(e),this.setParsedChildren([s])}setChildren(e){this.children.context.raw()!==e&&(typeof e=="string"?this.text(e):super.setChildren(e))}*tweenText(e,t,s,n){var p;yield(p=document.fonts)==null?void 0:p.ready;const a=this.children();(a.length!==1||!(a[0]instanceof At))&&this.text.save();const h=this.childAs(0),l=h.text.context.raw(),u=this.size.context.raw();h.text(e);const d=this.size();h.text(l??La),this.height()===0&&this.height(d.height),yield*Se(this.size(d,t,s),h.text(e,t,s,n)),this.children.context.setter(e),this.size(u)}getLayout(){return!0}constructor({children:e,text:t,...s}){super(s),this[sd]=!0,this.children(t??e)}innerText(){const e=this.childrenAs();let t="";for(const s of e)t+=s.text();return t}parentTxt(){const e=this.parent();return e instanceof Di?e:null}parseChildren(e){const t=[],s=Array.isArray(e)?e:[e];for(const n of s)n instanceof Di||n instanceof At?t.push(n):typeof n=="string"&&t.push(new At({text:n}));return t}applyFlex(){super.applyFlex(),this.element.style.display=this.findAncestor(Jc(Di))?"inline":"block"}async draw(e){var t;await((t=document.fonts)==null?void 0:t.ready),await this.drawChildren(e)}};sd=id;sn([W(""),N()],$t.prototype,"text",void 0);sn([rt()],$t.prototype,"tweenText",null);sn([te()],$t.prototype,"innerText",null);sn([te()],$t.prototype,"parentTxt",null);$t=Di=sn([ut("Txt")],$t);["fill","stroke","lineWidth","strokeFirst","lineCap","lineJoin","lineDash","lineDashOffset"].forEach(r=>{$t.prototype[`getDefault${Ui(r)}`]=function(e){var t;return((t=this.parentTxt())==null?void 0:t[r]())??e}});const q=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},b0=Number.isSafeInteger||function(r){return typeof r=="number"&&Math.abs(r)<=A0},A0=Number.MAX_SAFE_INTEGER||9007199254740991;let Z=function(r){return r.NETWORK_ERROR="networkError",r.MEDIA_ERROR="mediaError",r.KEY_SYSTEM_ERROR="keySystemError",r.MUX_ERROR="muxError",r.OTHER_ERROR="otherError",r}({}),D=function(r){return r.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",r.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",r.KEY_SYSTEM_NO_SESSION="keySystemNoSession",r.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",r.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",r.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",r.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",r.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",r.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",r.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",r.MANIFEST_LOAD_ERROR="manifestLoadError",r.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",r.MANIFEST_PARSING_ERROR="manifestParsingError",r.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",r.LEVEL_EMPTY_ERROR="levelEmptyError",r.LEVEL_LOAD_ERROR="levelLoadError",r.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",r.LEVEL_PARSING_ERROR="levelParsingError",r.LEVEL_SWITCH_ERROR="levelSwitchError",r.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",r.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",r.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",r.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",r.FRAG_LOAD_ERROR="fragLoadError",r.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",r.FRAG_DECRYPT_ERROR="fragDecryptError",r.FRAG_PARSING_ERROR="fragParsingError",r.FRAG_GAP="fragGap",r.REMUX_ALLOC_ERROR="remuxAllocError",r.KEY_LOAD_ERROR="keyLoadError",r.KEY_LOAD_TIMEOUT="keyLoadTimeOut",r.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",r.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",r.BUFFER_APPEND_ERROR="bufferAppendError",r.BUFFER_APPENDING_ERROR="bufferAppendingError",r.BUFFER_STALLED_ERROR="bufferStalledError",r.BUFFER_FULL_ERROR="bufferFullError",r.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",r.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",r.ASSET_LIST_LOAD_ERROR="assetListLoadError",r.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",r.ASSET_LIST_PARSING_ERROR="assetListParsingError",r.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",r.INTERNAL_EXCEPTION="internalException",r.INTERNAL_ABORTED="aborted",r.ATTACH_MEDIA_ERROR="attachMediaError",r.UNKNOWN="unknown",r}({}),E=function(r){return r.MEDIA_ATTACHING="hlsMediaAttaching",r.MEDIA_ATTACHED="hlsMediaAttached",r.MEDIA_DETACHING="hlsMediaDetaching",r.MEDIA_DETACHED="hlsMediaDetached",r.MEDIA_ENDED="hlsMediaEnded",r.STALL_RESOLVED="hlsStallResolved",r.BUFFER_RESET="hlsBufferReset",r.BUFFER_CODECS="hlsBufferCodecs",r.BUFFER_CREATED="hlsBufferCreated",r.BUFFER_APPENDING="hlsBufferAppending",r.BUFFER_APPENDED="hlsBufferAppended",r.BUFFER_EOS="hlsBufferEos",r.BUFFERED_TO_END="hlsBufferedToEnd",r.BUFFER_FLUSHING="hlsBufferFlushing",r.BUFFER_FLUSHED="hlsBufferFlushed",r.MANIFEST_LOADING="hlsManifestLoading",r.MANIFEST_LOADED="hlsManifestLoaded",r.MANIFEST_PARSED="hlsManifestParsed",r.LEVEL_SWITCHING="hlsLevelSwitching",r.LEVEL_SWITCHED="hlsLevelSwitched",r.LEVEL_LOADING="hlsLevelLoading",r.LEVEL_LOADED="hlsLevelLoaded",r.LEVEL_UPDATED="hlsLevelUpdated",r.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",r.LEVELS_UPDATED="hlsLevelsUpdated",r.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",r.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",r.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",r.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",r.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",r.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",r.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",r.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",r.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",r.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",r.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",r.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",r.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",r.CUES_PARSED="hlsCuesParsed",r.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",r.INIT_PTS_FOUND="hlsInitPtsFound",r.FRAG_LOADING="hlsFragLoading",r.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",r.FRAG_LOADED="hlsFragLoaded",r.FRAG_DECRYPTED="hlsFragDecrypted",r.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",r.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",r.FRAG_PARSING_METADATA="hlsFragParsingMetadata",r.FRAG_PARSED="hlsFragParsed",r.FRAG_BUFFERED="hlsFragBuffered",r.FRAG_CHANGED="hlsFragChanged",r.FPS_DROP="hlsFpsDrop",r.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",r.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",r.ERROR="hlsError",r.DESTROYING="hlsDestroying",r.KEY_LOADING="hlsKeyLoading",r.KEY_LOADED="hlsKeyLoaded",r.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",r.BACK_BUFFER_REACHED="hlsBackBufferReached",r.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",r.ASSET_LIST_LOADING="hlsAssetListLoading",r.ASSET_LIST_LOADED="hlsAssetListLoaded",r.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",r.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",r.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",r.INTERSTITIAL_STARTED="hlsInterstitialStarted",r.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",r.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",r.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",r.INTERSTITIAL_ENDED="hlsInterstitialEnded",r.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",r.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",r.EVENT_CUE_ENTER="hlsEventCueEnter",r}({});var fe={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},X={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class ji{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class I0{constructor(e,t,s,n=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new ji(e),this.fast_=new ji(t),this.defaultTTFB_=n,this.ttfb_=new ji(e)}update(e,t){const{slow_:s,fast_:n,ttfb_:a}=this;s.halfLife!==e&&(this.slow_=new ji(e,s.getEstimate(),s.getTotalWeight())),n.halfLife!==t&&(this.fast_=new ji(t,n.getEstimate(),n.getTotalWeight())),a.halfLife!==e&&(this.ttfb_=new ji(e,a.getEstimate(),a.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,n=e/1e3,a=s/n;this.fast_.sample(n,a),this.slow_.sample(n,a)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function w0(r,e,t){return(e=R0(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function Ee(){return Ee=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(r[s]=t[s])}return r},Ee.apply(null,arguments)}function Fl(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(r,n).enumerable})),t.push.apply(t,s)}return t}function xe(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Fl(Object(t),!0).forEach(function(s){w0(r,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Fl(Object(t)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(t,s))})}return r}function L0(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var s=t.call(r,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function R0(r){var e=L0(r,"string");return typeof e=="symbol"?e:e+""}class xt{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=di,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const di=function(){},C0={trace:di,debug:di,log:di,warn:di,info:di,error:di};function Ga(){return Ee({},C0)}function P0(r,e){const t=self.console[r];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${r}] >`):di}function Ul(r,e,t){return e[r]?e[r].bind(e):P0(r,t)}const za=Ga();function D0(r,e,t){const s=Ga();if(typeof console=="object"&&r===!0||typeof r=="object"){const n=["debug","log","info","warn","error"];n.forEach(a=>{s[a]=Ul(a,r,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.13`)}catch{return Ga()}n.forEach(a=>{za[a]=Ul(a,r)})}else Ee(za,s);return s}const _e=za;function Si(r=!0){return typeof self>"u"?void 0:(r||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function k0(r){return typeof self<"u"&&r===self.ManagedMediaSource}function nd(r,e){const t=Object.keys(r),s=Object.keys(e),n=t.length,a=s.length;return!n||!a||n===a&&!t.some(h=>s.indexOf(h)===-1)}function dt(r,e=!1){if(typeof TextDecoder<"u"){const d=new TextDecoder("utf-8").decode(r);if(e){const p=d.indexOf("\0");return p!==-1?d.substring(0,p):d}return d.replace(/\0/g,"")}const t=r.length;let s,n,a,h="",l=0;for(;l<t;){if(s=r[l++],s===0&&e)return h;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:h+=String.fromCharCode(s);break;case 12:case 13:n=r[l++],h+=String.fromCharCode((s&31)<<6|n&63);break;case 14:n=r[l++],a=r[l++],h+=String.fromCharCode((s&15)<<12|(n&63)<<6|(a&63)<<0);break}}return h}function Ze(r){let e="";for(let t=0;t<r.length;t++){let s=r[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function rd(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function M0(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var ia={exports:{}},Ol;function F0(){return Ol||(Ol=1,function(r,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,n=/^(?=([^\/?#]*))\1([^]*)$/,a=/(?:\/|^)\.(?=\/)/g,h=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,l={buildAbsoluteURL:function(u,d,p){if(p=p||{},u=u.trim(),d=d.trim(),!d){if(!p.alwaysNormalize)return u;var g=l.parseURL(u);if(!g)throw new Error("Error trying to parse base URL.");return g.path=l.normalizePath(g.path),l.buildURLFromParts(g)}var y=l.parseURL(d);if(!y)throw new Error("Error trying to parse relative URL.");if(y.scheme)return p.alwaysNormalize?(y.path=l.normalizePath(y.path),l.buildURLFromParts(y)):d;var x=l.parseURL(u);if(!x)throw new Error("Error trying to parse base URL.");if(!x.netLoc&&x.path&&x.path[0]!=="/"){var v=n.exec(x.path);x.netLoc=v[1],x.path=v[2]}x.netLoc&&!x.path&&(x.path="/");var _={scheme:x.scheme,netLoc:y.netLoc,path:null,params:y.params,query:y.query,fragment:y.fragment};if(!y.netLoc&&(_.netLoc=x.netLoc,y.path[0]!=="/"))if(!y.path)_.path=x.path,y.params||(_.params=x.params,y.query||(_.query=x.query));else{var o=x.path,c=o.substring(0,o.lastIndexOf("/")+1)+y.path;_.path=l.normalizePath(c)}return _.path===null&&(_.path=p.alwaysNormalize?l.normalizePath(y.path):y.path),l.buildURLFromParts(_)},parseURL:function(u){var d=s.exec(u);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[6]||""}:null},normalizePath:function(u){for(u=u.split("").reverse().join("").replace(a,"");u.length!==(u=u.replace(h,"")).length;);return u.split("").reverse().join("")},buildURLFromParts:function(u){return u.scheme+u.netLoc+u.path+u.params+u.query+u.fragment}};r.exports=l})()}(ia)),ia.exports}var wo=F0();class Lo{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var Te={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class ad{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,O0(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let n;s.length===1?n=(t==null?void 0:t.byteRangeEndOffset)||0:n=parseInt(s[1]),this._byteRange=[n,parseInt(s[0])+n]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[Te.AUDIO]:null,[Te.VIDEO]:null,[Te.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Lo),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=wo.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Te.AUDIO]=null,e[Te.VIDEO]=null,e[Te.AUDIOVIDEO]=null}}function Pe(r){return r.sn!=="initSegment"}class sa extends ad{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(q(e)&&q(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const s=Object.keys(t);if(s.length===1){const n=this._decryptdata=t[s[0]]||null;n&&(this._decryptdata=n.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=q(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),n=s.length;if(n>1||n===1&&(t=this.levelkeys[s[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!q(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Pe(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const n=t[e];n&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=n.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,n,a,h=!1){const{elementaryStreams:l}=this,u=l[e];if(!u){l[e]={startPTS:t,endPTS:s,startDTS:n,endDTS:a,partial:h};return}u.startPTS=Math.min(u.startPTS,t),u.endPTS=Math.max(u.endPTS,s),u.startDTS=Math.min(u.startDTS,n),u.endDTS=Math.max(u.endDTS,a)}}class U0 extends ad{constructor(e,t,s,n,a){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=n;const h=e.enumeratedString("BYTERANGE");h&&this.setByteRange(h,a),a&&(this.fragOffset=a.fragOffset+a.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function od(r,e){const t=Object.getPrototypeOf(r);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||od(t,e)}}function O0(r,e){const t=od(r,e);t&&(t.enumerable=!0,Object.defineProperty(r,e,t))}const Bl=Math.pow(2,32)-1,B0=[].push,ld={video:1,audio:2,id3:3,text:4};function Me(r){return String.fromCharCode.apply(null,r)}function hd(r,e){const t=r[e]<<8|r[e+1];return t<0?65536+t:t}function re(r,e){const t=cd(r,e);return t<0?4294967296+t:t}function Nl(r,e){let t=re(r,e);return t*=Math.pow(2,32),t+=re(r,e+4),t}function cd(r,e){return r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}function N0(r){const e=r.byteLength;for(let t=0;t<e;){const s=re(r,t);if(s>8&&r[t+4]===109&&r[t+5]===111&&r[t+6]===111&&r[t+7]===102)return!0;t=s>1?t+s:e}return!1}function de(r,e){const t=[];if(!e.length)return t;const s=r.byteLength;for(let n=0;n<s;){const a=re(r,n),h=Me(r.subarray(n+4,n+8)),l=a>1?n+a:s;if(h===e[0])if(e.length===1)t.push(r.subarray(n+8,l));else{const u=de(r.subarray(n+8,l),e.slice(1));u.length&&B0.apply(t,u)}n=l}return t}function $0(r){const e=[],t=r[0];let s=8;const n=re(r,s);s+=4;let a=0,h=0;t===0?(a=re(r,s),h=re(r,s+4),s+=8):(a=Nl(r,s),h=Nl(r,s+8),s+=16),s+=2;let l=r.length+h;const u=hd(r,s);s+=2;for(let d=0;d<u;d++){let p=s;const g=re(r,p);p+=4;const y=g&2147483647;if((g&2147483648)>>>31===1)return _e.warn("SIDX has hierarchical references (not supported)"),null;const v=re(r,p);p+=4,e.push({referenceSize:y,subsegmentDuration:v,info:{duration:v/n,start:l,end:l+y-1}}),l+=y,p+=4,s=p}return{earliestPresentationTime:a,timescale:n,version:t,referencesCount:u,references:e}}function dd(r){const e=[],t=de(r,["moov","trak"]);for(let n=0;n<t.length;n++){const a=t[n],h=de(a,["tkhd"])[0];if(h){let l=h[0];const u=re(h,l===0?12:20),d=de(a,["mdia","mdhd"])[0];if(d){l=d[0];const p=re(d,l===0?12:20),g=de(a,["mdia","hdlr"])[0];if(g){const y=Me(g.subarray(8,12)),x={soun:Te.AUDIO,vide:Te.VIDEO}[y],v=de(a,["mdia","minf","stbl","stsd"])[0],_=G0(v);x?(e[u]={timescale:p,type:x,stsd:_},e[x]=xe({timescale:p,id:u},_)):e[u]={timescale:p,type:y,stsd:_}}}}}return de(r,["moov","mvex","trex"]).forEach(n=>{const a=re(n,4),h=e[a];h&&(h.default={duration:re(n,12),flags:re(n,20)})}),e}function G0(r){const e=r.subarray(8),t=e.subarray(86),s=Me(e.subarray(4,8));let n=s,a;const h=s==="enca"||s==="encv";if(h){const d=de(e,[s])[0].subarray(s==="enca"?28:78);de(d,["sinf"]).forEach(g=>{const y=de(g,["schm"])[0];if(y){const x=Me(y.subarray(4,8));if(x==="cbcs"||x==="cenc"){const v=de(g,["frma"])[0];v&&(n=Me(v))}}})}const l=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const u=de(t,["avcC"])[0];u&&u.length>3&&(n+="."+fn(u[1])+fn(u[2])+fn(u[3]),a=un(l==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const u=de(e,[s])[0],d=de(u.subarray(28),["esds"])[0];if(d&&d.length>7){let p=4;if(d[p++]!==3)break;p=na(d,p),p+=2;const g=d[p++];if(g&128&&(p+=2),g&64&&(p+=d[p++]),d[p++]!==4)break;p=na(d,p);const y=d[p++];if(y===64)n+="."+fn(y);else break;if(p+=12,d[p++]!==5)break;p=na(d,p);const x=d[p++];let v=(x&248)>>3;v===31&&(v+=1+((x&7)<<3)+((d[p]&224)>>5)),n+="."+v}break}case"hvc1":case"hev1":{const u=de(t,["hvcC"])[0];if(u&&u.length>12){const d=u[1],p=["","A","B","C"][d>>6],g=d&31,y=re(u,2),x=(d&32)>>5?"H":"L",v=u[12],_=u.subarray(6,12);n+="."+p+g,n+="."+z0(y).toString(16).toUpperCase(),n+="."+x+v;let o="";for(let c=_.length;c--;){const f=_[c];(f||o)&&(o="."+f.toString(16).toUpperCase()+o)}n+=o}a=un(l=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{n=un(n,t)||n;break}case"vp09":{const u=de(t,["vpcC"])[0];if(u&&u.length>6){const d=u[4],p=u[5],g=u[6]>>4&15;n+="."+Ct(d)+"."+Ct(p)+"."+Ct(g)}break}case"av01":{const u=de(t,["av1C"])[0];if(u&&u.length>2){const d=u[1]>>>5,p=u[1]&31,g=u[2]>>>7?"H":"M",y=(u[2]&64)>>6,x=(u[2]&32)>>5,v=d===2&&y?x?12:10:y?10:8,_=(u[2]&16)>>4,o=(u[2]&8)>>3,c=(u[2]&4)>>2,f=u[2]&3;n+="."+d+"."+Ct(p)+g+"."+Ct(v)+"."+_+"."+o+c+f+"."+Ct(1)+"."+Ct(1)+"."+Ct(1)+"."+0,a=un("dav1",t)}break}}return{codec:n,encrypted:h,supplemental:a}}function un(r,e){const t=de(e,["dvvC"]),s=t.length?t[0]:de(e,["dvcC"])[0];if(s){const n=s[2]>>1&127,a=s[2]<<5&32|s[3]>>3&31;return r+"."+Ct(n)+"."+Ct(a)}}function z0(r){let e=0;for(let t=0;t<32;t++)e|=(r>>t&1)<<31-t;return e>>>0}function na(r,e){const t=e+5;for(;r[e++]&128&&e<t;);return e}function fn(r){return("0"+r.toString(16).toUpperCase()).slice(-2)}function Ct(r){return(r<10?"0":"")+r}function H0(r,e){if(!r||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&ud(r,(s,n)=>{const a=s.subarray(8,24);a.some(h=>h!==0)||(_e.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${Ze(a)} -> ${Ze(t)}`),s.set(t,8))})}function V0(r){const e=[];return ud(r,t=>e.push(t.subarray(8,24))),e}function ud(r,e){de(r,["moov","trak"]).forEach(s=>{const n=de(s,["mdia","minf","stbl","stsd"])[0];if(!n)return;const a=n.subarray(8);let h=de(a,["enca"]);const l=h.length>0;l||(h=de(a,["encv"])),h.forEach(u=>{const d=l?u.subarray(28):u.subarray(78);de(d,["sinf"]).forEach(g=>{const y=fd(g);y&&e(y,l)})})})}function fd(r){const e=de(r,["schm"])[0];if(e){const t=Me(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=de(r,["schi","tenc"])[0];if(s)return s}}}function K0(r,e,t){const s={},n=de(r,["moof","traf"]);for(let a=0;a<n.length;a++){const h=n[a],l=de(h,["tfhd"])[0],u=re(l,4),d=e[u];if(!d)continue;s[u]||(s[u]={start:NaN,duration:0,sampleCount:0,timescale:d.timescale,type:d.type});const p=s[u],g=de(h,["tfdt"])[0];if(g){const m=g[0];let S=re(g,4);m===1&&(S===Bl?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=Bl+1,S+=re(g,8))),q(S)&&(!q(p.start)||S<p.start)&&(p.start=S)}const y=d.default,x=re(l,0)|(y==null?void 0:y.flags);let v=(y==null?void 0:y.duration)||0;x&8&&(x&2?v=re(l,12):v=re(l,8));const _=de(h,["trun"]);let o=p.start||0,c=0,f=v;for(let m=0;m<_.length;m++){const S=_[m],T=re(S,4),b=p.sampleCount;p.sampleCount+=T;const A=S[3]&1,I=S[3]&4,L=S[2]&1,w=S[2]&2,R=S[2]&4,M=S[2]&8;let k=8,z=T;for(A&&(k+=4),I&&T&&(!(S[k+1]&1)&&p.keyFrameIndex===void 0&&(p.keyFrameIndex=b),k+=4,L?(f=re(S,k),k+=4):f=v,w&&(k+=4),M&&(k+=4),o+=f,c+=f,z--);z--;)L?(f=re(S,k),k+=4):f=v,w&&(k+=4),R&&(S[k+1]&1||p.keyFrameIndex===void 0&&(p.keyFrameIndex=p.sampleCount-(z+1),p.keyFrameStart=o),k+=4),M&&(k+=4),o+=f,c+=f;!c&&v&&(c+=v*T)}p.duration+=c}if(!Object.keys(s).some(a=>s[a].duration)){let a=1/0,h=0;const l=de(r,["sidx"]);for(let u=0;u<l.length;u++){const d=$0(l[u]);if(d!=null&&d.references){a=Math.min(a,d.earliestPresentationTime/d.timescale);const p=d.references.reduce((g,y)=>g+y.info.duration||0,0);h=Math.max(h,p+d.earliestPresentationTime/d.timescale)}}h&&q(h)&&Object.keys(s).forEach(u=>{s[u].duration||(s[u].duration=h*s[u].timescale-s[u].start)})}return s}function Y0(r){const e={valid:null,remainder:null},t=de(r,["moof"]);if(t.length<2)return e.remainder=r,e;const s=t[t.length-1];return e.valid=r.slice(0,s.byteOffset-8),e.remainder=r.slice(s.byteOffset-8),e}function yt(r,e){const t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function $l(r,e){const t=[],s=e.samples,n=e.timescale,a=e.id;let h=!1;return de(s,["moof"]).map(u=>{const d=u.byteOffset-8;de(u,["traf"]).map(g=>{const y=de(g,["tfdt"]).map(x=>{const v=x[0];let _=re(x,4);return v===1&&(_*=Math.pow(2,32),_+=re(x,8)),_/n})[0];return y!==void 0&&(r=y),de(g,["tfhd"]).map(x=>{const v=re(x,4),_=re(x,0)&16777215,o=(_&1)!==0,c=(_&2)!==0,f=(_&8)!==0;let m=0;const S=(_&16)!==0;let T=0;const b=(_&32)!==0;let A=8;v===a&&(o&&(A+=8),c&&(A+=4),f&&(m=re(x,A),A+=4),S&&(T=re(x,A),A+=4),b&&(A+=4),e.type==="video"&&(h=Lr(e.codec)),de(g,["trun"]).map(I=>{const L=I[0],w=re(I,0)&16777215,R=(w&1)!==0;let M=0;const k=(w&4)!==0,z=(w&256)!==0;let O=0;const U=(w&512)!==0;let j=0;const H=(w&1024)!==0,V=(w&2048)!==0;let J=0;const $=re(I,4);let G=8;R&&(M=re(I,G),G+=4),k&&(G+=4);let ie=M+d;for(let ce=0;ce<$;ce++){if(z?(O=re(I,G),G+=4):O=m,U?(j=re(I,G),G+=4):j=T,H&&(G+=4),V&&(L===0?J=re(I,G):J=cd(I,G),G+=4),e.type===Te.VIDEO){let K=0;for(;K<j;){const ue=re(s,ie);if(ie+=4,W0(h,s[ie])){const Ce=s.subarray(ie,ie+ue);Ro(Ce,h?2:1,r+J/n,t)}ie+=ue,K+=ue+4}}r+=O/n}}))})})}),t}function Lr(r){if(!r)return!1;const e=r.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function W0(r,e){if(r){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Ro(r,e,t,s){const n=pd(r);let a=0;a+=e;let h=0,l=0,u=0;for(;a<n.length;){h=0;do{if(a>=n.length)break;u=n[a++],h+=u}while(u===255);l=0;do{if(a>=n.length)break;u=n[a++],l+=u}while(u===255);const d=n.length-a;let p=a;if(l<d)a+=l;else if(l>d){_e.error(`Malformed SEI payload. ${l} is too small, only ${d} bytes left to parse.`);break}if(h===4){if(n[p++]===181){const y=hd(n,p);if(p+=2,y===49){const x=re(n,p);if(p+=4,x===1195456820){const v=n[p++];if(v===3){const _=n[p++],o=31&_,c=64&_,f=c?2+o*3:0,m=new Uint8Array(f);if(c){m[0]=_;for(let S=1;S<f;S++)m[S]=n[p++]}s.push({type:v,payloadType:h,pts:t,bytes:m})}}}}}else if(h===5&&l>16){const g=[];for(let v=0;v<16;v++){const _=n[p++].toString(16);g.push(_.length==1?"0"+_:_),(v===3||v===5||v===7||v===9)&&g.push("-")}const y=l-16,x=new Uint8Array(y);for(let v=0;v<y;v++)x[v]=n[p++];s.push({payloadType:h,pts:t,uuid:g.join(""),userData:dt(x),userDataBytes:x})}}}function pd(r){const e=r.byteLength,t=[];let s=1;for(;s<e-2;)r[s]===0&&r[s+1]===0&&r[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return r;const n=e-t.length,a=new Uint8Array(n);let h=0;for(s=0;s<n;h++,s++)h===t[0]&&(h++,t.shift()),a[s]=r[h];return a}function j0(r){const e=r[0];let t="",s="",n=0,a=0,h=0,l=0,u=0,d=0;if(e===0){for(;Me(r.subarray(d,d+1))!=="\0";)t+=Me(r.subarray(d,d+1)),d+=1;for(t+=Me(r.subarray(d,d+1)),d+=1;Me(r.subarray(d,d+1))!=="\0";)s+=Me(r.subarray(d,d+1)),d+=1;s+=Me(r.subarray(d,d+1)),d+=1,n=re(r,12),a=re(r,16),l=re(r,20),u=re(r,24),d=28}else if(e===1){d+=4,n=re(r,d),d+=4;const g=re(r,d);d+=4;const y=re(r,d);for(d+=4,h=2**32*g+y,b0(h)||(h=Number.MAX_SAFE_INTEGER,_e.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=re(r,d),d+=4,u=re(r,d),d+=4;Me(r.subarray(d,d+1))!=="\0";)t+=Me(r.subarray(d,d+1)),d+=1;for(t+=Me(r.subarray(d,d+1)),d+=1;Me(r.subarray(d,d+1))!=="\0";)s+=Me(r.subarray(d,d+1)),d+=1;s+=Me(r.subarray(d,d+1)),d+=1}const p=r.subarray(d,r.byteLength);return{schemeIdUri:t,value:s,timeScale:n,presentationTime:h,presentationTimeDelta:a,eventDuration:l,id:u,payload:p}}function q0(r,...e){const t=e.length;let s=8,n=t;for(;n--;)s+=e[n].byteLength;const a=new Uint8Array(s);for(a[0]=s>>24&255,a[1]=s>>16&255,a[2]=s>>8&255,a[3]=s&255,a.set(r,4),n=0,s=8;n<t;n++)a.set(e[n],s),s+=e[n].byteLength;return a}function X0(r,e,t){if(r.byteLength!==16)throw new RangeError("Invalid system id");let s,n;s=0,n=new Uint8Array;let a;s>0?(a=new Uint8Array(4),e.length>0&&new DataView(a.buffer).setUint32(0,e.length,!1)):a=new Uint8Array;const h=new Uint8Array(4);return t.byteLength>0&&new DataView(h.buffer).setUint32(0,t.byteLength,!1),q0([112,115,115,104],new Uint8Array([s,0,0,0]),r,a,n,h,t)}function Q0(r){const e=[];if(r instanceof ArrayBuffer){const t=r.byteLength;let s=0;for(;s+32<t;){const n=new DataView(r,s),a=Z0(n);e.push(a),s+=a.size}}return e}function Z0(r){const e=r.getUint32(0),t=r.byteOffset,s=r.byteLength;if(s<e)return{offset:t,size:s};if(r.getUint32(4)!==1886614376)return{offset:t,size:e};const a=r.getUint32(8)>>>24;if(a!==0&&a!==1)return{offset:t,size:e};const h=r.buffer,l=Ze(new Uint8Array(h,t+12,16));let u=null,d=null,p=0;if(a===0)p=28;else{const y=r.getUint32(28);if(!y||s<32+y*16)return{offset:t,size:e};u=[];for(let x=0;x<y;x++)u.push(new Uint8Array(h,t+32+x*16,16));p=32+y*16}if(!p)return{offset:t,size:e};const g=r.getUint32(p);return e-32<g?{offset:t,size:e}:(d=new Uint8Array(h,t+p+4,g),{version:a,systemId:l,kids:u,data:d,offset:t,size:e})}const gd=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),ms={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Co(r,e){const t=ms[e];return!!t&&!!t[r.slice(0,4)]}function Gs(r,e,t=!0){return!r.split(",").some(s=>!Po(s,e,t))}function Po(r,e,t=!0){var s;const n=Si(t);return(s=n==null?void 0:n.isTypeSupported(zs(r,e)))!=null?s:!1}function zs(r,e){return`${e}/mp4;codecs=${r}`}function Gl(r){if(r){const e=r.substring(0,4);return ms.video[e]}return 2}function Xn(r){const e=gd();return r.split(",").reduce((t,s)=>{const a=e&&Lr(s)?9:ms.video[s];return a?(a*2+t)/(t?3:2):(ms.audio[s]+t)/(t?2:1)},0)}const ra={};function J0(r,e=!0){if(ra[r])return ra[r];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[r];for(let n=0;n<t.length;n++){var s;if(Po(t[n],"audio",e))return ra[r]=t[n],t[n];if(t[n]==="mp3"&&(s=Si(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return r}const em=/flac|opus|mp4a\.40\.34/i;function Qn(r,e=!0){return r.replace(em,t=>J0(t.toLowerCase(),e))}function tm(r,e){const t=[];if(r){const s=r.split(",");for(let n=0;n<s.length;n++)Co(s[n],"video")||t.push(s[n])}return e&&t.push(e),t.join(",")}function Mn(r,e){if(r&&(r.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(r)!==-1)&&(zl(r,"audio")||zl(r,"video")))return r;if(e){const t=e.split(",");if(t.length>1){if(r){for(let s=t.length;s--;)if(t[s].substring(0,4)===r.substring(0,4))return t[s]}return t[0]}}return e||r}function zl(r,e){return Co(r,e)&&Po(r,e)}function im(r){const e=r.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function sm(r){if(r.startsWith("av01.")){const e=r.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return r}function Hl(r){const e=Si(r)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ha(r){return r.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const nm={supported:!0,powerEfficient:!0,smooth:!0},rm={supported:!1,smooth:!1,powerEfficient:!1},md={supported:!0,configurations:[],decodingInfoResults:[nm]};function yd(r,e){return{supported:!1,configurations:e,decodingInfoResults:[rm],error:r}}function am(r,e,t,s,n,a){const h=r.videoCodec,l=r.audioCodec?r.audioGroups:null,u=a==null?void 0:a.audioCodec,d=a==null?void 0:a.channels,p=d?parseInt(d):u?1/0:2;let g=null;if(l!=null&&l.length)try{l.length===1&&l[0]?g=e.groups[l[0]].channels:g=l.reduce((y,x)=>{if(x){const v=e.groups[x];if(!v)throw new Error(`Audio track group ${x} not found`);Object.keys(v.channels).forEach(_=>{y[_]=(y[_]||0)+v.channels[_]})}return y},{2:0})}catch{return!0}return h!==void 0&&(h.split(",").some(y=>Lr(y))||r.width>1920&&r.height>1088||r.height>1920&&r.width>1088||r.frameRate>Math.max(s,30)||r.videoRange!=="SDR"&&r.videoRange!==t||r.bitrate>Math.max(n,8e6))||!!g&&q(p)&&Object.keys(g).some(y=>parseInt(y)>p)}function vd(r,e,t,s={}){const n=r.videoCodec;if(!n&&!r.audioCodec||!t)return Promise.resolve(md);const a=[],h=om(r),l=h.length,u=lm(r,e,l>0),d=u.length;for(let p=l||1*d||1;p--;){const g={type:"media-source"};if(l&&(g.video=h[p%l]),d){g.audio=u[p%d];const y=g.audio.bitrate;g.video&&y&&(g.video.bitrate-=y)}a.push(g)}if(n){const p=navigator.userAgent;if(n.split(",").some(g=>Lr(g))&&gd())return Promise.resolve(yd(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${p})`),a))}return Promise.all(a.map(p=>{const g=cm(p);return s[g]||(s[g]=t.decodingInfo(p))})).then(p=>({supported:!p.some(g=>!g.supported),configurations:a,decodingInfoResults:p})).catch(p=>({supported:!1,configurations:a,decodingInfoResults:[],error:p}))}function om(r){var e;const t=(e=r.videoCodec)==null?void 0:e.split(","),s=xd(r),n=r.width||640,a=r.height||480,h=r.frameRate||30,l=r.videoRange.toLowerCase();return t?t.map(u=>{const d={contentType:zs(sm(u),"video"),width:n,height:a,bitrate:s,framerate:h};return l!=="sdr"&&(d.transferFunction=l),d}):[]}function lm(r,e,t){var s;const n=(s=r.audioCodec)==null?void 0:s.split(","),a=xd(r);return n&&r.audioGroups?r.audioGroups.reduce((h,l)=>{var u;const d=l?(u=e.groups[l])==null?void 0:u.tracks:null;return d?d.reduce((p,g)=>{if(g.groupId===l){const y=parseFloat(g.channels||"");n.forEach(x=>{const v={contentType:zs(x,"audio"),bitrate:t?hm(x,a):a};y&&(v.channels=""+y),p.push(v)})}return p},h):h},[]):[]}function hm(r,e){if(e<=1)return 1;let t=128e3;return r==="ec-3"?t=768e3:r==="ac-3"&&(t=64e4),Math.min(e/2,t)}function xd(r){return Math.ceil(Math.max(r.bitrate*.9,r.averageBitrate)/1e3)*1e3||1}function cm(r){let e="";const{audio:t,video:s}=r;if(s){const n=Ha(s.contentType);e+=`${n}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){const n=Ha(t.contentType);e+=`${s?"_":""}${n}_c${t.channels}`}return e}const Va=["NONE","TYPE-0","TYPE-1",null];function dm(r){return Va.indexOf(r)>-1}const Zn=["SDR","PQ","HLG"];function um(r){return!!r&&Zn.indexOf(r)>-1}var Fn={No:"",Yes:"YES",v2:"v2"};function Vl(r){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=r,n=s<e/2;return e&&n?t?Fn.v2:Fn.Yes:Fn.No}class Kl{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Hs{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Yl(this._audioGroups,e)}hasSubtitleGroup(e){return Yl(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Yl(r,e){return!e||!r?!1:r.indexOf(e)!==-1}function fm(){if(typeof matchMedia=="function"){const r=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(r.media!==e.media)return r.matches===!0}return!1}function pm(r,e){let t=!1,s=[];if(r&&(t=r!=="SDR",s=[r]),e){s=e.allowedVideoRanges||Zn.slice(0);const n=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:n&&fm(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const gm=r=>{const e=new WeakSet;return(t,s)=>{if(r&&(s=r(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},be=(r,e)=>JSON.stringify(r,gm(e));function mm(r,e,t,s,n){const a=Object.keys(r),h=s==null?void 0:s.channels,l=s==null?void 0:s.audioCodec,u=n==null?void 0:n.videoCodec,d=h&&parseInt(h)===2;let p=!1,g=!1,y=1/0,x=1/0,v=1/0,_=1/0,o=0,c=[];const{preferHDR:f,allowedVideoRanges:m}=pm(e,n);for(let I=a.length;I--;){const L=r[a[I]];p||(p=L.channels[2]>0),y=Math.min(y,L.minHeight),x=Math.min(x,L.minFramerate),v=Math.min(v,L.minBitrate),m.filter(R=>L.videoRanges[R]>0).length>0&&(g=!0)}y=q(y)?y:0,x=q(x)?x:0;const S=Math.max(1080,y),T=Math.max(30,x);v=q(v)?v:t,t=Math.max(v,t),g||(e=void 0);const b=a.length>1;return{codecSet:a.reduce((I,L)=>{const w=r[L];if(L===I)return I;if(c=g?m.filter(R=>w.videoRanges[R]>0):[],b){if(w.minBitrate>t)return Lt(L,`min bitrate of ${w.minBitrate} > current estimate of ${t}`),I;if(!w.hasDefaultAudio)return Lt(L,"no renditions with default or auto-select sound found"),I;if(l&&L.indexOf(l.substring(0,4))%5!==0)return Lt(L,`audio codec preference "${l}" not found`),I;if(h&&!d){if(!w.channels[h])return Lt(L,`no renditions with ${h} channel sound found (channels options: ${Object.keys(w.channels)})`),I}else if((!l||d)&&p&&w.channels[2]===0)return Lt(L,"no renditions with stereo sound found"),I;if(w.minHeight>S)return Lt(L,`min resolution of ${w.minHeight} > maximum of ${S}`),I;if(w.minFramerate>T)return Lt(L,`min framerate of ${w.minFramerate} > maximum of ${T}`),I;if(!c.some(R=>w.videoRanges[R]>0))return Lt(L,`no variants with VIDEO-RANGE of ${be(c)} found`),I;if(u&&L.indexOf(u.substring(0,4))%5!==0)return Lt(L,`video codec preference "${u}" not found`),I;if(w.maxScore<o)return Lt(L,`max score of ${w.maxScore} < selected max of ${o}`),I}return I&&(Xn(L)>=Xn(I)||w.fragmentError>r[I].fragmentError)?I:(_=w.minIndex,o=w.maxScore,L)},void 0),videoRanges:c,preferHDR:f,minFramerate:x,minBitrate:v,minIndex:_}}function Lt(r,e){_e.log(`[abr] start candidates with "${r}" ignored because ${e}`)}function Sd(r){return r.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const n=t.channels||"2";return s.channels[n]=(s.channels[n]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function ym(r,e,t,s){return r.slice(t,s+1).reduce((n,a,h)=>{if(!a.codecSet)return n;const l=a.audioGroups;let u=n[a.codecSet];u||(n[a.codecSet]=u={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:h,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!l,fragmentError:0}),u.minBitrate=Math.min(u.minBitrate,a.bitrate);const d=Math.min(a.height,a.width);return u.minHeight=Math.min(u.minHeight,d),u.minFramerate=Math.min(u.minFramerate,a.frameRate),u.minIndex=Math.min(u.minIndex,h),u.maxScore=Math.max(u.maxScore,a.score),u.fragmentError+=a.fragmentError,u.videoRanges[a.videoRange]=(u.videoRanges[a.videoRange]||0)+1,l&&l.forEach(p=>{if(!p)return;const g=e.groups[p];g&&(u.hasDefaultAudio=u.hasDefaultAudio||e.hasDefaultAudio?g.hasDefault:g.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(g.channels).forEach(y=>{u.channels[y]=(u.channels[y]||0)+g.channels[y]}))}),n},{})}function Wl(r){if(!r)return r;const{lang:e,assocLang:t,characteristics:s,channels:n,audioCodec:a}=r;return{lang:e,assocLang:t,characteristics:s,channels:n,audioCodec:a}}function Ft(r,e,t){if("attrs"in r){const s=e.indexOf(r);if(s!==-1)return s}for(let s=0;s<e.length;s++){const n=e[s];if(Bi(r,n,t))return s}return-1}function Bi(r,e,t){const{groupId:s,name:n,lang:a,assocLang:h,default:l}=r,u=r.forced;return(s===void 0||e.groupId===s)&&(n===void 0||e.name===n)&&(a===void 0||vm(a,e.lang))&&(a===void 0||e.assocLang===h)&&(l===void 0||e.default===l)&&(u===void 0||e.forced===u)&&(!("characteristics"in r)||xm(r.characteristics||"",e.characteristics))&&(t===void 0||t(r,e))}function vm(r,e="--"){return r.length===e.length?r===e:r.startsWith(e)||e.startsWith(r)}function xm(r,e=""){const t=r.split(","),s=e.split(",");return t.length===s.length&&!t.some(n=>s.indexOf(n)===-1)}function ki(r,e){const{audioCodec:t,channels:s}=r;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function Sm(r,e,t,s,n){const a=e[s],l=e.reduce((y,x,v)=>{const _=x.uri;return(y[_]||(y[_]=[])).push(v),y},{})[a.uri];l.length>1&&(s=Math.max.apply(Math,l));const u=a.videoRange,d=a.frameRate,p=a.codecSet.substring(0,4),g=jl(e,s,y=>{if(y.videoRange!==u||y.frameRate!==d||y.codecSet.substring(0,4)!==p)return!1;const x=y.audioGroups,v=t.filter(_=>!x||x.indexOf(_.groupId)!==-1);return Ft(r,v,n)>-1});return g>-1?g:jl(e,s,y=>{const x=y.audioGroups,v=t.filter(_=>!x||x.indexOf(_.groupId)!==-1);return Ft(r,v,n)>-1})}function jl(r,e,t){for(let s=e;s>-1;s--)if(t(r[s]))return s;for(let s=e+1;s<r.length;s++)if(t(r[s]))return s;return-1}function Jn(r,e){var t;return!!r&&r!==((t=e.loadLevelObj)==null?void 0:t.uri)}class _m extends xt{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:n,partCurrent:a,hls:h}=this,{autoLevelEnabled:l,media:u}=h;if(!n||!u)return;const d=performance.now(),p=a?a.stats:n.stats,g=a?a.duration:n.duration,y=d-p.loading.start,x=h.minAutoLevel,v=n.level,_=this._nextAutoLevel;if(p.aborted||p.loaded&&p.loaded===p.total||v<=x){this.clearTimer(),this._nextAutoLevel=-1;return}if(!l)return;const o=_>-1&&_!==v,c=!!t||o;if(!c&&(u.paused||!u.playbackRate||!u.readyState))return;const f=h.mainForwardBufferInfo;if(!c&&f===null)return;const m=this.bwEstimator.getEstimateTTFB(),S=Math.abs(u.playbackRate);if(y<=Math.max(m,1e3*(g/(S*2))))return;const T=f?f.len/S:0,b=p.loading.first?p.loading.first-p.loading.start:-1,A=p.loaded&&b>-1,I=this.getBwEstimate(),L=h.levels,w=L[v],R=Math.max(p.loaded,Math.round(g*(n.bitrate||w.averageBitrate)/8));let M=A?y-b:y;M<1&&A&&(M=Math.min(y,p.loaded*8/I));const k=A?p.loaded*1e3/M:0,z=m/1e3,O=k?(R-p.loaded)/k:R*8/I+z;if(O<=T)return;const U=k?k*8:I,j=((s=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,H=this.hls.config.abrBandWidthUpFactor;let V=Number.POSITIVE_INFINITY,J;for(J=v-1;J>x;J--){const ce=L[J].maxBitrate,K=!L[J].details||j;if(V=this.getTimeToLoadFrag(z,U,g*ce,K),V<Math.min(T,g+z))break}if(V>=O||V>g*10)return;A?this.bwEstimator.sample(y-Math.min(m,b),p.loaded):this.bwEstimator.sampleTTFB(y);const $=L[J].maxBitrate;this.getBwEstimate()*H>$&&this.resetEstimator($);const G=this.findBestLevel($,x,J,0,T,1,1);G>-1&&(J=G),this.warn(`Fragment ${n.sn}${a?" part "+a.index:""} of level ${v} is loading too slowly;
|
|
106
106
|
Fragment duration: ${n.duration.toFixed(3)}
|
|
107
107
|
Time to underbuffer: ${T.toFixed(3)} s
|
|
108
|
-
Estimated load time for current fragment: ${
|
|
109
|
-
Estimated load time for down switch fragment: ${
|
|
108
|
+
Estimated load time for current fragment: ${O.toFixed(3)} s
|
|
109
|
+
Estimated load time for down switch fragment: ${V.toFixed(3)} s
|
|
110
110
|
TTFB estimate: ${b|0} ms
|
|
111
|
-
Current BW estimate: ${
|
|
111
|
+
Current BW estimate: ${q(I)?I|0:"Unknown"} bps
|
|
112
112
|
New BW estimate: ${this.getBwEstimate()|0} bps
|
|
113
|
-
Switching to level ${
|
|
113
|
+
Switching to level ${J} @ ${$|0} bps`),h.nextLoadLevel=h.nextAutoLevel=J,this.clearTimer();const ie=()=>{if(this.clearTimer(),this.fragCurrent===n&&this.hls.loadLevel===J&&J>0){const ce=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${J>0?"and switching down":""}
|
|
114
114
|
Fragment duration: ${n.duration.toFixed(3)} s
|
|
115
|
-
Time to underbuffer: ${he.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,O>v){let W=this.findBestLevel(this.hls.levels[v].bitrate,v,O,0,he,1,1);W===-1&&(W=v),this.hls.nextLoadLevel=this.hls.nextAutoLevel=W,this.resetEstimator(this.hls.levels[W].bitrate)}}};o||$>F*2?se():this.timer=self.setInterval(se,F*1e3),h.trigger(_.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:a,stats:p})},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 e0(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.FRAG_LOADING,this.onFragLoading,this),e.on(_.FRAG_LOADED,this.onFragLoaded,this),e.on(_.FRAG_BUFFERED,this.onFragBuffered,this),e.on(_.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(_.LEVEL_LOADED,this.onLevelLoaded,this),e.on(_.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(_.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(_.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.FRAG_LOADING,this.onFragLoading,this),e.off(_.FRAG_LOADED,this.onFragLoaded,this),e.off(_.FRAG_BUFFERED,this.onFragBuffered,this),e.off(_.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(_.LEVEL_LOADED,this.onLevelLoaded,this),e.off(_.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(_.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(_.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 s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var n;this.fragCurrent=s,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 P.BUFFER_ADD_CODEC_ERROR:case P.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case P.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:n,partCurrent:a}=this;if(s&&n&&s.sn===n.sn&&s.level===n.level){const h=performance.now(),l=a?a.stats:s.stats,u=h-l.loading.start,d=l.loading.first?l.loading.first-l.loading.start:-1;if(l.loaded&&d>-1){const g=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(u-Math.min(g,d),l.loaded)}else this.bwEstimator.sampleTTFB(u)}break}}}getTimeToLoadFrag(e,t,s,n){const a=e+s/t,h=n?e+this.lastLevelLoadSec:0;return a+h}onLevelLoaded(e,t){const s=this.hls.config,{loading:n}=t.stats,a=n.end-n.first;K(a)&&(this.lastLevelLoadSec=a/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const n=s?s.stats:t.stats;if(t.type===X.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 a=s?s.duration:t.duration,h=this.hls.levels[t.level],l=(h.loaded?h.loaded.bytes:0)+n.loaded,u=(h.loaded?h.loaded.duration:0)+a;h.loaded={bytes:l,duration:u},h.realBitrate=Math.round(8*l/u)}if(t.bitrateTest){const a={stats:n,frag:t,part:s,id:t.type};this.onFragBuffered(_.FRAG_BUFFERED,a),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:n}=t,a=n!=null&&n.stats.loaded?n.stats:s.stats;if(a.aborted||this.ignoreFragment(s))return;const h=a.parsing.end-a.loading.start-Math.min(a.loading.first-a.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(h,a.loaded),a.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=h/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==X.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,a=this.findBestLevel(s,t,e,0,n,1,1);if(a>-1)return a;const h=this.hls.firstLevel,l=Math.min(Math.max(h,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${h} clamped to ${l}`),l}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const a=s&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const h=this.hls.levels;if(h.length>Math.max(e,a)&&h[e].loadError<=h[a].loadError)return e}return this._nextAutoLevel=a,this.nextAutoLevelKey=this.getAutoLevelKey(),a}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:n,config:a,minAutoLevel:h}=s,l=t?t.duration:e?e.duration:0,u=this.getBwEstimate(),d=this.getStarvationDelay();let p=a.abrBandWidthFactor,g=a.abrBandWidthUpFactor;if(d){const o=this.findBestLevel(u,h,n,d,0,p,g);if(o>=0)return this.rebufferNotice=-1,o}let y=l?Math.min(l,a.maxStarvationDelay):a.maxStarvationDelay;if(!d){const o=this.bitrateTestDelay;o&&(y=(l?Math.min(l,a.maxLoadingDelay):a.maxLoadingDelay)-o,this.info(`bitrate test took ${Math.round(1e3*o)}ms, set first fragment max fetchDuration to ${Math.round(1e3*y)} ms`),p=g=1)}const v=this.findBestLevel(u,h,n,d,y,p,g);if(this.rebufferNotice!==v&&(this.rebufferNotice=v,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${v}`)),v>-1)return v;const x=s.levels[h],E=s.loadLevelObj;return E&&(x==null?void 0:x.bitrate)<E.bitrate?h:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,n,a,h,l){var u;const d=n+a,p=this.lastLoadedFragLevel,g=p===-1?this.hls.firstLevel:p,{fragCurrent:y,partCurrent:v}=this,{levels:x,allAudioTracks:E,loadLevel:o,config:c}=this.hls;if(x.length===1)return 0;const f=x[g],m=!!((u=this.hls.latestLevelDetails)!=null&&u.live),S=o===-1||p===-1;let T,b="SDR",A=(f==null?void 0:f.frameRate)||0;const{audioPreference:I,videoPreference:L}=c,w=this.audioTracksByGroup||(this.audioTracksByGroup=sd(E));let C=-1;if(S){if(this.firstSelection!==-1)return this.firstSelection;const z=this.codecTiers||(this.codecTiers=G0(x,w,t,s)),j=$0(z,b,e,I,L),{codecSet:Y,videoRanges:F,minFramerate:O,minBitrate:te,minIndex:ee,preferHDR:se}=j;C=ee,T=Y,b=se?F[F.length-1]:F[0],A=O,e=Math.max(e,te),this.log(`picked start tier ${Ae(j)}`)}else T=f==null?void 0:f.codecSet,b=f==null?void 0:f.videoRange;const k=v?v.duration:y?y.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,G=[];for(let z=s;z>=t;z--){var $;const j=x[z],Y=z>g;if(!j)continue;if(c.useMediaCapabilities&&!j.supportedResult&&!j.supportedPromise){const W=navigator.mediaCapabilities;typeof(W==null?void 0:W.decodingInfo)=="function"&&(k0(j,w,b,A,e,I)||yr(j.videoCodec))?(j.supportedPromise=id(j,w,W),j.supportedPromise.then(me=>{if(!this.hls)return;j.supportedResult=me;const De=this.hls.levels,qe=De.indexOf(j);me.error?this.warn(`MediaCapabilities decodingInfo error: "${me.error}" for level ${qe} ${Ae(me)}`):me.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${qe} ${Ae(me)}`),qe>-1&&De.length>1&&(this.log(`Removing unsupported level ${qe}`),this.hls.removeLevel(qe),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))})):j.supportedResult=ed}if((T&&j.codecSet!==T||b&&j.videoRange!==b||Y&&A>j.frameRate||!Y&&A>0&&A<j.frameRate||j.supportedResult&&!(($=j.supportedResult.decodingInfoResults)!=null&&$[0].smooth))&&(!S||z!==C)){G.push(z);continue}const F=j.details,O=(v?F==null?void 0:F.partTarget:F==null?void 0:F.averagetargetduration)||k;let te;Y?te=l*e:te=h*e;const ee=k&&n>=k*2&&a===0?j.averageBitrate:j.maxBitrate,se=this.getTimeToLoadFrag(U,te,ee*O,F===void 0);if(te>=ee&&(z===p||j.loadError===0&&j.fragmentError===0)&&(se<=U||!K(se)||m&&!this.bitrateTestDelay||se<d)){const W=this.forcedAutoLevel;return z!==o&&(W===-1||W!==o)&&(G.length&&this.trace(`Skipped level(s) ${G.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${x[G[0]].codecs}" ${x[G[0]].videoRange}; not compatible with "${T}" ${b}`),this.info(`switch candidate:${g}->${z} adjustedbw(${Math.round(te)})-bitrate=${Math.round(te-ee)} ttfb:${U.toFixed(1)} avgDuration:${O.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${se.toFixed(1)} firstSelection:${S} codecSet:${j.codecSet} videoRange:${j.videoRange} hls.loadLevel:${o}`)),S&&(this.firstSelection=z),z}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const yo={search:function(r,e){let t=0,s=r.length-1,n=null,a=null;for(;t<=s;){n=(t+s)/2|0,a=r[n];const h=e(a);if(h>0)t=n+1;else if(h<0)s=n-1;else return a}return null}};function Y0(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!K(e))return null;const s=r[0].programDateTime;if(e<(s||0))return null;const n=r[r.length-1].endProgramDateTime;if(e>=(n||0))return null;t=t||0;for(let a=0;a<r.length;++a){const h=r[a];if(j0(e,t,h))return h}return null}function ki(r,e,t=0,s=0,n=.005){let a=null;if(r){a=e[1+r.sn-e[0].sn]||null;const l=r.endDTS-t;l>0&&l<15e-7&&(t+=15e-7),a&&r.level!==a.level&&a.end<=r.end&&(a=e[2+r.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(a=e[0]);if(a&&((!r||r.level===a.level)&&Ml(t,s,a)===0||W0(a,r,Math.min(n,s))))return a;const h=yo.search(e,Ml.bind(null,t,s));return h&&(h!==r||!a)?h:a}function W0(r,e,t){if(e&&e.start===0&&e.level<r.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((n,a)=>(a[0]==="INF"&&(n+=parseFloat(a[1])),n),t);return r.start<=s}return!1}function Ml(r=0,e=0,t){if(t.start<=r&&t.start+t.duration>r)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=r?1:t.start-s>r&&t.start?-1:0}function j0(r,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>r}function nd(r,e){return yo.search(r,t=>t.cc<e?1:t.cc>e?-1:0)}function q0(r,e,t){if(r&&r.startCC<=e&&r.endCC>=e){const s=t.start,n=t.end;let a=r.fragments;if(!t.relurl){const{fragmentHint:h}=r;h&&(a=a.concat(h))}return yo.search(a,h=>h.cc<e||h.end<=s?1:h.cc>e||h.start>=n?-1:0)}return null}function Vn(r){switch(r.details){case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_TIMEOUT:case P.LEVEL_LOAD_TIMEOUT:case P.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Fl(r,e){const t=Vn(e);return r.default[`${t?"timeout":"error"}Retry`]}function xo(r,e){const t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function Ul(r){return xe(xe({},r),{errorRetry:null,timeoutRetry:null})}function Kn(r,e,t,s){if(!r)return!1;const n=s==null?void 0:s.code,a=e<r.maxNumRetry&&(X0(n)||!!t);return r.shouldRetry?r.shouldRetry(r,e,t,s,a):a}function X0(r){return r===0&&navigator.onLine===!1||!!r&&(r<400||r>499)}var Ve={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},gt={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2};class Q0 extends Jt{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(_.ERROR,this.onError,this),e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(_.ERROR,this.onError,this),e.off(_.ERROR,this.onErrorOut,this),e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.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)===X.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const n=this.hls,a=t.context;switch(t.details){case P.FRAG_LOAD_ERROR:case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_ERROR:case P.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case P.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=ks();return}case P.FRAG_GAP:case P.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Ve.SendAlternateToPenaltyBox;return}case P.LEVEL_EMPTY_ERROR:case P.LEVEL_PARSING_ERROR:{var h,l;const d=t.parent===X.MAIN?t.level:n.loadLevel;t.details===P.LEVEL_EMPTY_ERROR&&((h=t.context)!=null&&(l=h.levelDetails)!=null&&l.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,d):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,d))}return;case P.LEVEL_LOAD_ERROR:case P.LEVEL_LOAD_TIMEOUT:typeof(a==null?void 0:a.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a.level));return;case P.AUDIO_TRACK_LOAD_ERROR:case P.AUDIO_TRACK_LOAD_TIMEOUT:case P.SUBTITLE_LOAD_ERROR:case P.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const d=n.loadLevelObj;if(d&&(a.type===ue.AUDIO_TRACK&&d.hasAudioGroup(a.groupId)||a.type===ue.SUBTITLE_TRACK&&d.hasSubtitleGroup(a.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=Ve.SendAlternateToPenaltyBox,t.errorAction.flags=gt.MoveAllAlternatesMatchingHost;return}}return;case P.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const d=n.loadLevelObj,p=d==null?void 0:d.attrs["HDCP-LEVEL"];p?t.errorAction={action:Ve.SendAlternateToPenaltyBox,flags:gt.MoveAllAlternatesMatchingHDCP,hdcpLevel:p}:this.keySystemError(t)}return;case P.BUFFER_ADD_CODEC_ERROR:case P.REMUX_ALLOC_ERROR:case P.BUFFER_APPEND_ERROR:if(!t.errorAction){var u;t.errorAction=this.getLevelSwitchAction(t,(u=t.level)!=null?u:n.loadLevel)}return;case P.INTERNAL_EXCEPTION:case P.BUFFER_APPENDING_ERROR:case P.BUFFER_FULL_ERROR:case P.LEVEL_SWITCH_ERROR:case P.BUFFER_STALLED_ERROR:case P.BUFFER_SEEK_OVER_HOLE:case P.BUFFER_NUDGE_ON_STALL:t.errorAction=ks();return}t.type===Q.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 s=this.hls,n=Fl(s.config.playlistLoadPolicy,e),a=this.playlistError++;if(Kn(n,a,Vn(e),e.response))return{action:Ve.RetryRequest,flags:gt.None,retryConfig:n,retryCount:a};const l=this.getLevelSwitchAction(e,t);return n&&(l.retryConfig=n,l.retryCount=a),l}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),n=t.levels[s],{fragLoadPolicy:a,keyLoadPolicy:h}=t.config,l=Fl(e.details.startsWith("key")?h:a,e),u=t.levels.reduce((p,g)=>p+g.fragmentError,0);if(n&&(e.details!==P.FRAG_GAP&&n.fragmentError++,Kn(l,u,Vn(e),e.response)))return{action:Ve.RetryRequest,flags:gt.None,retryConfig:l,retryCount:u};const d=this.getLevelSwitchAction(e,s);return l&&(d.retryConfig=l,d.retryCount=u),d}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const n=this.hls.levels[t];if(n){var a,h;const d=e.details;n.loadError++,d===P.BUFFER_APPEND_ERROR&&n.fragmentError++;let p=-1;const{levels:g,loadLevel:y,minAutoLevel:v,maxAutoLevel:x}=s;s.autoLevelEnabled||(s.loadLevel=-1);const E=(a=e.frag)==null?void 0:a.type,c=(E===X.AUDIO&&d===P.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===P.BUFFER_ADD_CODEC_ERROR||d===P.BUFFER_APPEND_ERROR))&&g.some(({audioCodec:b})=>n.audioCodec!==b),m=e.sourceBufferName==="video"&&(d===P.BUFFER_ADD_CODEC_ERROR||d===P.BUFFER_APPEND_ERROR)&&g.some(({codecSet:b,audioCodec:A})=>n.codecSet!==b&&n.audioCodec===A),{type:S,groupId:T}=(h=e.context)!=null?h:{};for(let b=g.length;b--;){const A=(b+y)%g.length;if(A!==y&&A>=v&&A<=x&&g[A].loadError===0){var l,u;const I=g[A];if(d===P.FRAG_GAP&&E===X.MAIN&&e.frag){const L=g[A].details;if(L){const w=ki(e.frag,L.fragments,e.frag.start);if(w!=null&&w.gap)continue}}else{if(S===ue.AUDIO_TRACK&&I.hasAudioGroup(T)||S===ue.SUBTITLE_TRACK&&I.hasSubtitleGroup(T))continue;if(E===X.AUDIO&&(l=n.audioGroups)!=null&&l.some(L=>I.hasAudioGroup(L))||E===X.SUBTITLE&&(u=n.subtitleGroups)!=null&&u.some(L=>I.hasSubtitleGroup(L))||c&&n.audioCodec===I.audioCodec||!c&&n.audioCodec!==I.audioCodec||m&&n.codecSet===I.codecSet)continue}p=A;break}}if(p>-1&&s.loadLevel!==p)return e.levelRetry=!0,this.playlistError=0,{action:Ve.SendAlternateToPenaltyBox,flags:gt.None,nextAutoLevel:p}}return{action:Ve.SendAlternateToPenaltyBox,flags:gt.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case Ve.DoNothing:break;case Ve.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==P.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,s=e.errorAction;if(!s)return;const{flags:n,hdcpLevel:a,nextAutoLevel:h}=s;switch(n){case gt.None:this.switchLevel(e,h);break;case gt.MoveAllAlternatesMatchingHDCP:a&&(t.maxHdcpLevel=Pa[Pa.indexOf(a)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}s.resolved||this.switchLevel(e,h)}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===P.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=Jc(e.mimeType),n=this.hls.levels;for(let a=n.length;a--;)n[a][`${e.sourceBufferName}Codec`]===s&&this.hls.removeLevel(a)}}}function ks(r){const e={action:Ve.DoNothing,flags:gt.None};return r&&(e.resolved=!0),e}var ke={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Z0{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(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.BUFFER_APPENDED,this.onBufferAppended,this),e.on(_.FRAG_BUFFERED,this.onFragBuffered,this),e.on(_.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.BUFFER_APPENDED,this.onBufferAppended,this),e.off(_.FRAG_BUFFERED,this.onFragBuffered,this),e.off(_.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let n=s.length;n--;){const a=s[n];if(!a)break;const h=a.end;if(a.start<=e&&h!==null&&e<=h)return a}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:n}=this,a=Object.keys(n);for(let h=a.length;h--;){const l=n[a[h]];if((l==null?void 0:l.body.type)===t&&(!s||l.buffered)){const u=l.body;if(u.start<=e&&e<=u.end)return u}}return null}detectEvictedFragments(e,t,s,n,a){this.timeRanges&&(this.timeRanges[e]=t);const h=(n==null?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(l=>{const u=this.fragments[l];if(!u||h>=u.body.sn)return;if(!u.buffered&&(!u.loaded||a)){u.body.type===s&&this.removeFragment(u.body);return}const d=u.range[e];if(d){if(d.time.length===0){this.removeFragment(u.body);return}d.time.some(p=>{const g=!this.isTimeBuffered(p.startPTS,p.endPTS,t);return g&&this.removeFragment(u.body),g})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,n=$i(s),a=this.fragments[n];if(!a||a.buffered&&s.gap)return;const h=!s.relurl;Object.keys(t).forEach(l=>{const u=s.elementaryStreams[l];if(!u)return;const d=t[l],p=h||u.partial===!0;a.range[l]=this.getBufferedTimes(s,e.part,p,d)}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=s.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),rn(a)||this.removeParts(s.sn-1,s.type)):this.removeFragment(a.body)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Ol(s,n=>n.fragment.sn>=e))}fragBuffered(e,t){const s=$i(e);let n=this.fragments[s];!n&&t&&(n=this.fragments[s]={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,s,n){const a={time:[],partial:s},h=e.start,l=e.end,u=e.minEndPTS||l,d=e.maxStartPTS||h;for(let p=0;p<n.length;p++){const g=n.start(p)-this.bufferPadding,y=n.end(p)+this.bufferPadding;if(d>=g&&u<=y){a.time.push({startPTS:Math.max(h,n.start(p)),endPTS:Math.min(l,n.end(p))});break}else if(h<y&&l>g){const v=Math.max(h,n.start(p)),x=Math.min(l,n.end(p));x>v&&(a.partial=!0,a.time.push({startPTS:v,endPTS:x}))}else if(l<=g)break}return a}getPartialFragment(e){let t=null,s,n,a,h=0;const{bufferPadding:l,fragments:u}=this;return Object.keys(u).forEach(d=>{const p=u[d];p&&rn(p)&&(n=p.body.start-l,a=p.body.end+l,e>=n&&e<=a&&(s=Math.min(e-n,a-e),h<=s&&(t=p.body,h=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||rn(t))}getState(e){const t=$i(e),s=this.fragments[t];return s?s.buffered?rn(s)?ke.PARTIAL:ke.OK:ke.APPENDING:ke.NOT_LOADED}isTimeBuffered(e,t,s){let n,a;for(let h=0;h<s.length;h++){if(n=s.start(h)-this.bufferPadding,a=s.end(h)+this.bufferPadding,e>=n&&t<=a)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 s=t.frag,n=t.part?null:t,a=$i(s);this.fragments[a]={body:s,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:n,timeRanges:a,type:h}=t;if(s.sn==="initSegment")return;const l=s.type;if(n){let d=this.activePartLists[l];d||(this.activePartLists[l]=d=[]),d.push(n)}this.timeRanges=a;const u=a[h];this.detectEvictedFragments(h,u,l,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=$i(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let n=s.length;n--;){const a=t[s[n]];if((a==null?void 0:a.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,n,a){n&&!this.hasGaps||Object.keys(this.fragments).forEach(h=>{const l=this.fragments[h];if(!l)return;const u=l.body;u.type!==s||n&&!u.gap||u.start<t&&u.end>e&&(l.buffered||a)&&this.removeFragment(u)})}removeFragment(e){const t=$i(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const n=e.sn;this.activePartLists[e.type]=Ol(s,a=>a.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 s=(e=this.hls)==null||(t=e.latestLevelDetails)==null?void 0:t.partList;s&&s.forEach(n=>n.clearElementaryStreamInfo())}}function rn(r){var e,t,s;return r.buffered&&(r.body.gap||((e=r.range.video)==null?void 0:e.partial)||((t=r.range.audio)==null?void 0:t.partial)||((s=r.range.audiovideo)==null?void 0:s.partial))}function $i(r){return`${r.type}_${r.level}_${r.sn}`}function Ol(r,e){return r.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var gi={cbc:0,ctr:1};class J0{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case gi.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case gi.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 em(r){const e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?r.slice(0,e-t):r}class tm{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),s=new Uint32Array(4);for(let n=0;n<4;n++)s[n]=t.getUint32(n*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,n=s[0],a=s[1],h=s[2],l=s[3],u=this.invSubMix,d=u[0],p=u[1],g=u[2],y=u[3],v=new Uint32Array(256);let x=0,E=0,o=0;for(o=0;o<256;o++)o<128?v[o]=o<<1:v[o]=o<<1^283;for(o=0;o<256;o++){let c=E^E<<1^E<<2^E<<3^E<<4;c=c>>>8^c&255^99,e[x]=c,t[c]=x;const f=v[x],m=v[f],S=v[m];let T=v[c]*257^c*16843008;n[x]=T<<24|T>>>8,a[x]=T<<16|T>>>16,h[x]=T<<8|T>>>24,l[x]=T,T=S*16843009^m*65537^f*257^x*16843008,d[c]=T<<24|T>>>8,p[c]=T<<16|T>>>16,g[c]=T<<8|T>>>24,y[c]=T,x?(x=f^v[v[v[S^f]]],E^=v[v[E]]):x=E=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,n=0;for(;n<t.length&&s;)s=t[n]===this.key[n],n++;if(s)return;this.key=t;const a=this.keySize=t.length;if(a!==4&&a!==6&&a!==8)throw new Error("Invalid aes key size="+a);const h=this.ksRows=(a+6+1)*4;let l,u;const d=this.keySchedule=new Uint32Array(h),p=this.invKeySchedule=new Uint32Array(h),g=this.sBox,y=this.rcon,v=this.invSubMix,x=v[0],E=v[1],o=v[2],c=v[3];let f,m;for(l=0;l<h;l++){if(l<a){f=d[l]=t[l];continue}m=f,l%a===0?(m=m<<8|m>>>24,m=g[m>>>24]<<24|g[m>>>16&255]<<16|g[m>>>8&255]<<8|g[m&255],m^=y[l/a|0]<<24):a>6&&l%a===4&&(m=g[m>>>24]<<24|g[m>>>16&255]<<16|g[m>>>8&255]<<8|g[m&255]),d[l]=f=(d[l-a]^m)>>>0}for(u=0;u<h;u++)l=h-u,u&3?m=d[l]:m=d[l-4],u<4||l<=4?p[u]=m:p[u]=x[g[m>>>24]]^E[g[m>>>16&255]]^o[g[m>>>8&255]]^c[g[m&255]],p[u]=p[u]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const n=this.keySize+6,a=this.invKeySchedule,h=this.invSBox,l=this.invSubMix,u=l[0],d=l[1],p=l[2],g=l[3],y=this.uint8ArrayToUint32Array_(s);let v=y[0],x=y[1],E=y[2],o=y[3];const c=new Int32Array(e),f=new Int32Array(c.length);let m,S,T,b,A,I,L,w,C,k,U,G,$,z;const j=this.networkToHostOrderSwap;for(;t<c.length;){for(C=j(c[t]),k=j(c[t+1]),U=j(c[t+2]),G=j(c[t+3]),A=C^a[0],I=G^a[1],L=U^a[2],w=k^a[3],$=4,z=1;z<n;z++)m=u[A>>>24]^d[I>>16&255]^p[L>>8&255]^g[w&255]^a[$],S=u[I>>>24]^d[L>>16&255]^p[w>>8&255]^g[A&255]^a[$+1],T=u[L>>>24]^d[w>>16&255]^p[A>>8&255]^g[I&255]^a[$+2],b=u[w>>>24]^d[A>>16&255]^p[I>>8&255]^g[L&255]^a[$+3],A=m,I=S,L=T,w=b,$=$+4;m=h[A>>>24]<<24^h[I>>16&255]<<16^h[L>>8&255]<<8^h[w&255]^a[$],S=h[I>>>24]<<24^h[L>>16&255]<<16^h[w>>8&255]<<8^h[A&255]^a[$+1],T=h[L>>>24]<<24^h[w>>16&255]<<16^h[A>>8&255]<<8^h[I&255]^a[$+2],b=h[w>>>24]<<24^h[A>>16&255]<<16^h[I>>8&255]<<8^h[L&255]^a[$+3],f[t]=j(m^v),f[t+1]=j(b^x),f[t+2]=j(T^E),f[t+3]=j(S^o),v=C,x=k,E=U,o=G,t=t+4}return f.buffer}}class im{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=sm(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function sm(r){switch(r){case gi.cbc:return"AES-CBC";case gi.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${r}`)}}const nm=16;class vo{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 s=self.crypto;s&&(this.subtle=s.subtle||s.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 s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?em(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,n){return this.useSoftware?new Promise((a,h)=>{const l=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(l,t,s,n);const u=this.flush();u?a(u.buffer):h(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,n)}softwareDecrypt(e,t,s,n){const{currentIV:a,currentResult:h,remainderData:l}=this;if(n!==gi.cbc||t.byteLength!==16)return pe.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),l&&(e=ct(l,e),this.remainderData=null);const u=this.getValidChunk(e);if(!u.length)return null;a&&(s=a);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new tm),d.expandKey(t);const p=h;return this.currentResult=d.decrypt(u.buffer,0,s),this.currentIV=u.slice(-16).buffer,p||null}webCryptoDecrypt(e,t,s,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,n));this.key=t,this.fastAesKey=new im(this.subtle,t,n)}return this.fastAesKey.expandKey().then(a=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new J0(this.subtle,new Uint8Array(s),n).decrypt(e.buffer,a)):Promise.reject(new Error("web crypto not initialized"))).catch(a=>(pe.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${a.name}: ${a.message}`),this.onWebCryptoError(e,t,s,n)))}onWebCryptoError(e,t,s,n){const a=this.enableSoftwareAES;if(a){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,n);const h=this.flush();if(h)return h.buffer}throw new Error("WebCrypto"+(a?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%nm;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(pe.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Bl=Math.pow(2,17);class rm{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 s=e.url;if(!s)return Promise.reject(new Gt({type:Q.NETWORK_ERROR,details:P.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,a=n.fLoader,h=n.loader;return new Promise((l,u)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(x=>x[0]==="GAP")){u($l(e));return}else e.gap=!1;const d=this.loader=a?new a(n):new h(n),p=Nl(e);e.loader=d;const g=Ul(n.fragLoadPolicy.default),y={loadPolicy:g,timeout:g.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Bl};e.stats=d.stats;const v={onSuccess:(x,E,o,c)=>{this.resetLoader(e,d);let f=x.data;o.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(f.slice(0,16)),f=f.slice(16)),l({frag:e,part:null,payload:f,networkDetails:c})},onError:(x,E,o,c)=>{this.resetLoader(e,d),u(new Gt({type:Q.NETWORK_ERROR,details:P.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:xe({url:s,data:void 0},x),error:new Error(`HTTP Error ${x.code} ${x.text}`),networkDetails:o,stats:c}))},onAbort:(x,E,o)=>{this.resetLoader(e,d),u(new Gt({type:Q.NETWORK_ERROR,details:P.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:o,stats:x}))},onTimeout:(x,E,o)=>{this.resetLoader(e,d),u(new Gt({type:Q.NETWORK_ERROR,details:P.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${y.timeout}ms`),networkDetails:o,stats:x}))}};t&&(v.onProgress=(x,E,o,c)=>t({frag:e,part:null,payload:o,networkDetails:c})),d.load(p,y,v)})}loadPart(e,t,s){this.abort();const n=this.config,a=n.fLoader,h=n.loader;return new Promise((l,u)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){u($l(e,t));return}const d=this.loader=a?new a(n):new h(n),p=Nl(e,t);e.loader=d;const g=Ul(n.fragLoadPolicy.default),y={loadPolicy:g,timeout:g.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Bl};t.stats=d.stats,d.load(p,y,{onSuccess:(v,x,E,o)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);const c={frag:e,part:t,payload:v.data,networkDetails:o};s(c),l(c)},onError:(v,x,E,o)=>{this.resetLoader(e,d),u(new Gt({type:Q.NETWORK_ERROR,details:P.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:xe({url:p.url,data:void 0},v),error:new Error(`HTTP Error ${v.code} ${v.text}`),networkDetails:E,stats:o}))},onAbort:(v,x,E)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),u(new Gt({type:Q.NETWORK_ERROR,details:P.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:E,stats:v}))},onTimeout:(v,x,E)=>{this.resetLoader(e,d),u(new Gt({type:Q.NETWORK_ERROR,details:P.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${y.timeout}ms`),networkDetails:E,stats:v}))}})})}updateStatsFromPart(e,t){const s=e.stats,n=t.stats,a=n.total;if(s.loaded+=n.loaded,a){const u=Math.round(e.duration/t.duration),d=Math.min(Math.round(s.loaded/a),u),g=(u-d)*Math.round(s.loaded/d);s.total=s.loaded+g}else s.total=Math.max(s.loaded,s.total);const h=s.loading,l=n.loading;h.start?h.first+=l.first-l.start:(h.start=l.start,h.first=l.first),h.end=l.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Nl(r,e=null){const t=e||r,s={frag:r,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},n=t.byteRangeStartOffset,a=t.byteRangeEndOffset;if(K(n)&&K(a)){var h;let l=n,u=a;if(r.sn==="initSegment"&&am((h=r.decryptdata)==null?void 0:h.method)){const d=a-n;d%16&&(u=a+(16-d%16)),n!==0&&(s.resetIV=!0,l=n-16)}s.rangeStart=l,s.rangeEnd=u}return s}function $l(r,e){const t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),s={type:Q.MEDIA_ERROR,details:P.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(s.part=e),(e||r).stats.aborted=!0,new Gt(s)}function am(r){return r==="AES-128"||r==="AES-256"}class Gt extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class rd extends Jt{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 So{constructor(e,t,s,n=0,a=-1,h=!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=an(),this.buffering={audio:an(),video:an(),audiovideo:an()},this.level=e,this.sn=t,this.id=s,this.size=n,this.part=a,this.partial=h}}function an(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Gl={length:0,start:()=>0,end:()=>0};class ce{static isBuffered(e,t){if(e){const s=ce.getBuffered(e);for(let n=s.length;n--;)if(t>=s.start(n)&&t<=s.end(n))return!0}return!1}static bufferedRanges(e){if(e){const t=ce.getBuffered(e);return ce.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const n=ce.bufferedRanges(e);if(n.length)return ce.bufferedInfo(n,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((p,g)=>p.start-g.start||g.end-p.end);let n=-1,a=[];if(s)for(let p=0;p<e.length;p++){t>=e[p].start&&t<=e[p].end&&(n=p);const g=a.length;if(g){const y=a[g-1].end;e[p].start-y<s?e[p].end>y&&(a[g-1].end=e[p].end):a.push(e[p])}else a.push(e[p])}else a=e;let h=0,l,u=t,d=t;for(let p=0;p<a.length;p++){const g=a[p].start,y=a[p].end;if(n===-1&&t>=g&&t<=y&&(n=p),t+s>=g&&t<y)u=g,d=y,h=d-t;else if(t+s<g){l=g;break}}return{len:h,start:u||0,end:d||0,nextStart:l,buffered:e,bufferedIndex:n}}static getBuffered(e){try{return e.buffered||Gl}catch(t){return pe.log("failed to get media.buffered",t),Gl}}}const ad=/\{\$([a-zA-Z0-9-_]+)\}/g;function zl(r){return ad.test(r)}function ka(r,e){if(r.variableList!==null||r.hasVariableRefs){const t=r.variableList;return e.replace(ad,s=>{const n=s.substring(2,s.length-1),a=t==null?void 0:t[n];return a===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),s):a})}return e}function Hl(r,e,t){let s=r.variableList;s||(r.variableList=s={});let n,a;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const h=new self.URL(t).searchParams;if(h.has(n))a=h.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(h){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${h.message}`))}}else n=e.NAME,a=e.VALUE;n in s?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):s[n]=a||""}function om(r,e,t){const s=e.IMPORT;if(t&&s in t){let n=r.variableList;n||(r.variableList=n={}),n[s]=t[s]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const lm=/^(\d+)x(\d+)$/,Vl=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Ie{constructor(e,t){typeof e=="string"&&(e=Ie.parseAttrList(e,t)),Te(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 s=new Uint8Array(t.length/2);for(let n=0;n<t.length/2;n++)s[n]=parseInt(t.slice(n*2,n*2+2),16);return s}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 s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((n,a)=>(n[a.toLowerCase()]=!0,n),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=lm.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const n={},a='"';for(Vl.lastIndex=0;(s=Vl.exec(e))!==null;){const h=s[1].trim();let l=s[2];const u=l.indexOf(a)===0&&l.lastIndexOf(a)===l.length-1;let d=!1;if(u)l=l.slice(1,-1);else switch(h){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(u||d))l=ka(t,l);else if(!d&&!u)switch(h){case"CLOSED-CAPTIONS":if(l==="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":pe.warn(`${e}: attribute ${h} is missing quotes`)}n[h]=l}return n}}const hm="com.apple.hls.interstitial";function cm(r){return r!=="ID"&&r!=="CLASS"&&r!=="CUE"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function dm(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"||r==="SCTE35-CMD"}class od{constructor(e,t,s=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:s,t){const a=t.attr;for(const h in a)if(Object.prototype.hasOwnProperty.call(e,h)&&e[h]!==a[h]){pe.warn(`DATERANGE tag attribute: "${h}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=h;break}e=Te(new Ie({}),a,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 a=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);K(a.getTime())&&(this._endDate=a)}}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?(pe.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(K(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===hm}get isValid(){return!!this.id&&!this._badValueForSameId&&K(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 um=10;class fm{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,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}get hasProgramDateTime(){return this.fragments.length?K(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||um}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 s=e.length;s--;)if(e[s].index>t)return e[s].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 Zi(r){return r==="AES-128"||r==="AES-256"||r==="AES-256-CTR"}function _o(r){switch(r){case"AES-128":case"AES-256":return gi.cbc;case"AES-256-CTR":return gi.ctr;default:throw new Error(`invalid full segment method ${r}`)}}function Eo(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function Ma(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}function pm(r){const e=Ma(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function gm(r){const e=function(s,n,a){const h=s[n];s[n]=s[a],s[a]=h};e(r,0,3),e(r,1,2),e(r,4,5),e(r,6,7)}function mm(r){const e=r.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),n=s[s.length-1].split(",");if(n.length===2){const a=n[0]==="base64",h=n[1];a?(s.splice(-1,1),t=Eo(h)):t=pm(h)}}return t}const Yn=typeof self<"u"?self:void 0;var ve={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Qe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function qr(r){switch(r){case Qe.FAIRPLAY:return ve.FAIRPLAY;case Qe.PLAYREADY:return ve.PLAYREADY;case Qe.WIDEVINE:return ve.WIDEVINE;case Qe.CLEARKEY:return ve.CLEARKEY}}var on={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Xr(r){if(r===on.WIDEVINE)return ve.WIDEVINE;if(r===on.PLAYREADY)return ve.PLAYREADY;if(r===on.CENC||r===on.CLEARKEY)return ve.CLEARKEY}function Qr(r){switch(r){case ve.FAIRPLAY:return Qe.FAIRPLAY;case ve.PLAYREADY:return Qe.PLAYREADY;case ve.WIDEVINE:return Qe.WIDEVINE;case ve.CLEARKEY:return Qe.CLEARKEY}}function ln(r){const{drmSystems:e,widevineLicenseUrl:t}=r,s=e?[ve.FAIRPLAY,ve.WIDEVINE,ve.PLAYREADY,ve.CLEARKEY].filter(n=>!!e[n]):[];return!s[ve.WIDEVINE]&&t&&s.push(ve.WIDEVINE),s}const ld=function(r){return Yn!=null&&(r=Yn.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function ym(r,e,t,s){let n;switch(r){case ve.FAIRPLAY:n=["cenc","sinf"];break;case ve.WIDEVINE:case ve.PLAYREADY:n=["cenc"];break;case ve.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return xm(n,e,t,s)}function xm(r,e,t,s){return[{initDataTypes:r,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(a=>({contentType:`audio/mp4; codecs=${a}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(a=>({contentType:`video/mp4; codecs=${a}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function vm(r){var e;return r.sessionType==="persistent-license"||!!((e=r.sessionTypes)!=null&&e.some(t=>t==="persistent-license"))}function hd(r){const e=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),h=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(h){const l=h.childNodes[0]?h.childNodes[0].nodeValue:h.getAttribute("VALUE");if(l){const u=Eo(l).subarray(0,16);return gm(u),u}}return null}let hn={};class Ms{static clearKeyUriToKeyIdMap(){hn={}}constructor(e,t,s,n=[1],a=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=s,this.keyFormatVersions=n,this.iv=a,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Zi(e)}isSupported(){if(this.method){if(Zi(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Qe.FAIRPLAY:case Qe.WIDEVINE:case Qe.PLAYREADY:case Qe.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(Zi(this.method)&&this.uri&&!this.iv){typeof e!="number"&&(pe.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const s=Sm(e);return new Ms(this.method,this.uri,"identity",this.keyFormatVersions,s)}const t=mm(this.uri);if(t)switch(this.keyFormat){case Qe.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Qe.PLAYREADY:{const s=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=A0(s,null,t),this.keyId=hd(t);break}default:{let s=t.subarray(0,16);if(s.length!==16){const n=new Uint8Array(16);n.set(s,16-s.length),s=n}this.keyId=s;break}}if(!this.keyId||this.keyId.byteLength!==16){let s=hn[this.uri];if(!s){const n=Object.keys(hn).length%Number.MAX_SAFE_INTEGER;s=new Uint8Array(16),new DataView(s.buffer,12,4).setUint32(0,n),hn[this.uri]=s}this.keyId=s}return this}}function Sm(r){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}const Kl=/#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,Yl=/#EXT-X-MEDIA:(.*)/g,_m=/^#EXT(?:INF|-X-TARGETDURATION):/m,Zr=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Em=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 Lt{static findGroup(e,t){for(let s=0;s<e.length;s++){const n=e[s];if(n.id===t)return n}}static resolve(e,t){return po.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return _m.test(e)}static parseMasterPlaylist(e,t){const s=zl(e),n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},a=[];Kl.lastIndex=0;let h;for(;(h=Kl.exec(e))!=null;)if(h[1]){var l;const d=new Ie(h[1],n),p=ka(n,h[2]),g={attrs:d,bitrate:d.decimalInteger("BANDWIDTH")||d.decimalInteger("AVERAGE-BANDWIDTH"),name:d.NAME,url:Lt.resolve(p,t)},y=d.decimalResolution("RESOLUTION");y&&(g.width=y.width,g.height=y.height),ql(d.CODECS,g);const v=d["SUPPLEMENTAL-CODECS"];v&&(g.supplemental={},ql(v,g.supplemental)),(l=g.unknownCodecs)!=null&&l.length||a.push(g),n.levels.push(g)}else if(h[3]){const d=h[3],p=h[4];switch(d){case"SESSION-DATA":{const g=new Ie(p,n),y=g["DATA-ID"];y&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[y]=g);break}case"SESSION-KEY":{const g=Wl(p,t,n);g.encrypted&&g.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(g)):pe.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${p}"`);break}case"DEFINE":{{const g=new Ie(p,n);Hl(n,g,t)}break}case"CONTENT-STEERING":{const g=new Ie(p,n);n.contentSteering={uri:Lt.resolve(g["SERVER-URI"],t),pathwayId:g["PATHWAY-ID"]||"."};break}case"START":{n.startTimeOffset=jl(p);break}}}const u=a.length>0&&a.length<n.levels.length;return n.levels=u?a:n.levels,n.levels.length===0&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(e,t,s){let n;const a={},h=s.levels,l={AUDIO:h.map(d=>({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:h.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let u=0;for(Yl.lastIndex=0;(n=Yl.exec(e))!==null;){const d=new Ie(n[1],s),p=d.TYPE;if(p){const g=l[p],y=a[p]||[];a[p]=y;const v=d.LANGUAGE,x=d["ASSOC-LANGUAGE"],E=d.CHANNELS,o=d.CHARACTERISTICS,c=d["INSTREAM-ID"],f={attrs:d,bitrate:0,id:u++,groupId:d["GROUP-ID"]||"",name:d.NAME||v||"",type:p,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:v,url:d.URI?Lt.resolve(d.URI,t):""};if(x&&(f.assocLang=x),E&&(f.channels=E),o&&(f.characteristics=o),c&&(f.instreamId=c),g!=null&&g.length){const m=Lt.findGroup(g,f.groupId)||g[0];Xl(f,m,"audioCodec"),Xl(f,m,"textCodec")}y.push(f)}}return a}static parseLevelPlaylist(e,t,s,n,a,h){var l;const u={url:t},d=new fm(t),p=d.fragments,g=[];let y=null,v=0,x=0,E=0,o=0,c=0,f=null,m=new Kr(n,u),S,T,b,A=-1,I=!1,L=null,w;if(Zr.lastIndex=0,d.m3u8=e,d.hasVariableRefs=zl(e),((l=Zr.exec(e))==null?void 0:l[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(S=Zr.exec(e))!==null;){I&&(I=!1,m=new Kr(n,u),m.playlistOffset=E,m.start=E,m.sn=v,m.cc=o,c&&(m.bitrate=c),m.level=s,y&&(m.initSegment=y,y.rawProgramDateTime&&(m.rawProgramDateTime=y.rawProgramDateTime,y.rawProgramDateTime=null),L&&(m.setByteRange(L),L=null)));const G=S[1];if(G){m.duration=parseFloat(G);const $=(" "+S[2]).slice(1);m.title=$||null,m.tagList.push($?["INF",G,$]:["INF",G])}else if(S[3]){if(K(m.duration)){m.playlistOffset=E,m.start=E,b&&Zl(m,b,d),m.sn=v,m.level=s,m.cc=o,p.push(m);const $=(" "+S[3]).slice(1);m.relurl=ka(d,$),Fa(m,f,g),f=m,E+=m.duration,v++,x=0,I=!0}}else{if(S=S[0].match(Em),!S){pe.warn("No matches on slow regex match for level playlist!");continue}for(T=1;T<S.length&&S[T]===void 0;T++);const $=(" "+S[T]).slice(1),z=(" "+S[T+1]).slice(1),j=S[T+2]?(" "+S[T+2]).slice(1):null;switch($){case"BYTERANGE":f?m.setByteRange(z,f):m.setByteRange(z);break;case"PROGRAM-DATE-TIME":m.rawProgramDateTime=z,m.tagList.push(["PROGRAM-DATE-TIME",z]),A===-1&&(A=p.length);break;case"PLAYLIST-TYPE":d.type&&Ot(d,$,S),d.type=z.toUpperCase();break;case"MEDIA-SEQUENCE":d.startSN!==0?Ot(d,$,S):p.length>0&&Jl(d,$,S),v=d.startSN=parseInt(z);break;case"SKIP":{d.skippedSegments&&Ot(d,$,S);const Y=new Ie(z,d),F=Y.decimalInteger("SKIPPED-SEGMENTS");if(K(F)){d.skippedSegments+=F;for(let te=F;te--;)p.push(null);v+=F}const O=Y.enumeratedString("RECENTLY-REMOVED-DATERANGES");O&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(O.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&Ot(d,$,S),d.targetduration=Math.max(parseInt(z),1);break;case"VERSION":d.version!==null&&Ot(d,$,S),d.version=parseInt(z);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||Ot(d,$,S),d.live=!1;break;case"#":(z||j)&&m.tagList.push(j?[z,j]:[z]);break;case"DISCONTINUITY":o++,m.tagList.push(["DIS"]);break;case"GAP":m.gap=!0,m.tagList.push([$]);break;case"BITRATE":m.tagList.push([$,z]),c=parseInt(z)*1e3,K(c)?m.bitrate=c:c=0;break;case"DATERANGE":{const Y=new Ie(z,d),F=new od(Y,d.dateRanges[Y.ID],d.dateRangeTagCount);d.dateRangeTagCount++,F.isValid||d.skippedSegments?d.dateRanges[F.id]=F:pe.warn(`Ignoring invalid DATERANGE tag: "${z}"`),m.tagList.push(["EXT-X-DATERANGE",z]);break}case"DEFINE":{{const Y=new Ie(z,d);"IMPORT"in Y?om(d,Y,h):Hl(d,Y,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?Ot(d,$,S):p.length>0&&Jl(d,$,S),d.startCC=o=parseInt(z);break;case"KEY":{const Y=Wl(z,t,d);if(Y.isSupported()){if(Y.method==="NONE"){b=void 0;break}b||(b={}),b[Y.keyFormat]&&(b=Te({},b)),b[Y.keyFormat]=Y}else pe.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${z}"`);break}case"START":d.startTimeOffset=jl(z);break;case"MAP":{const Y=new Ie(z,d);if(m.duration){const F=new Kr(n,u);Ql(F,Y,s,b),y=F,m.initSegment=y,y.rawProgramDateTime&&!m.rawProgramDateTime&&(m.rawProgramDateTime=y.rawProgramDateTime)}else{const F=m.byteRangeEndOffset;if(F){const O=m.byteRangeStartOffset;L=`${F-O}@${O}`}else L=null;Ql(m,Y,s,b),y=m,I=!0}y.cc=o;break}case"SERVER-CONTROL":{w&&Ot(d,$,S),w=new Ie(z),d.canBlockReload=w.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=w.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&w.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=w.optionalFloat("PART-HOLD-BACK",0),d.holdBack=w.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&Ot(d,$,S);const Y=new Ie(z);d.partTarget=Y.decimalFloatingPoint("PART-TARGET");break}case"PART":{let Y=d.partList;Y||(Y=d.partList=[]);const F=x>0?Y[Y.length-1]:void 0,O=x++,te=new Ie(z,d),ee=new c0(te,m,u,O,F);Y.push(ee),m.duration+=ee.duration;break}case"PRELOAD-HINT":{const Y=new Ie(z,d);d.preloadHint=Y;break}case"RENDITION-REPORT":{const Y=new Ie(z,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(Y);break}default:pe.warn(`line parsed but not handled: ${S}`);break}}}f&&!f.relurl?(p.pop(),E-=f.duration,d.partList&&(d.fragmentHint=f)):d.partList&&(Fa(m,f,g),m.cc=o,d.fragmentHint=m,b&&Zl(m,b,d)),d.targetduration||(d.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const C=p.length,k=p[0],U=p[C-1];if(E+=d.skippedSegments*d.targetduration,E>0&&C&&U){d.averagetargetduration=E/C;const G=U.sn;d.endSN=G!=="initSegment"?G:0,d.live||(U.endList=!0),k&&d.startCC===void 0&&(d.startCC=k.cc),A>0&&(bm(p,A),k&&g.unshift(k))}else d.endSN=0,d.startCC=0;return d.fragmentHint&&(E+=d.fragmentHint.duration),d.totalduration=E,g.length&&d.dateRangeTagCount&&k&&cd(g,d),d.endCC=o,d}}function cd(r,e){const t=r.length,s=r[t-1],n=e.live?1/0:e.totalduration,a=Object.keys(e.dateRanges);for(let h=a.length;h--;){const l=e.dateRanges[a[h]],u=l.startDate.getTime();l.tagAnchor=s.ref;for(let d=t;d--;){const p=Tm(e,u,r,d,n);if(p!==-1){l.tagAnchor=e.fragments[p].ref;break}}}}function Tm(r,e,t,s,n){const a=t[s];if(a){const l=a.programDateTime;if(e>=l||s===0){var h;const u=(((h=t[s+1])==null?void 0:h.start)||n)-a.start;if(e<=l+u*1e3){const d=t[s].sn-r.startSN,p=r.fragments;if(p.length>t.length){const y=(t[s+1]||p[p.length-1]).sn-r.startSN;for(let v=y;v>d;v--){const x=p[v].programDateTime;if(e>=x&&e<x+p[v].duration*1e3)return v}}return d}}}return-1}function Wl(r,e,t){var s,n;const a=new Ie(r,t),h=(s=a.METHOD)!=null?s:"",l=a.URI,u=a.hexadecimalInteger("IV"),d=a.KEYFORMATVERSIONS,p=(n=a.KEYFORMAT)!=null?n:"identity";l&&a.IV&&!u&&pe.error(`Invalid IV: ${a.IV}`);const g=l?Lt.resolve(l,e):"",y=(d||"1").split("/").map(Number).filter(Number.isFinite);return new Ms(h,g,p,y,u)}function jl(r){const t=new Ie(r).decimalFloatingPoint("TIME-OFFSET");return K(t)?t:null}function ql(r,e){let t=(r||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const n=t.filter(a=>Qc(a,s));n.length&&(e[`${s}Codec`]=n.map(a=>a.split("/")[0]).join(","),t=t.filter(a=>n.indexOf(a)===-1))}),e.unknownCodecs=t}function Xl(r,e,t){const s=e[t];s&&(r[t]=s)}function bm(r,e){let t=r[e];for(let s=e;s--;){const n=r[s];if(!n)return;n.programDateTime=t.programDateTime-n.duration*1e3,t=n}}function Fa(r,e,t){r.rawProgramDateTime?t.push(r):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime)}function Ql(r,e,t,s){r.relurl=e.URI,e.BYTERANGE&&r.setByteRange(e.BYTERANGE),r.level=t,r.sn="initSegment",s&&(r.levelkeys=s),r.initSegment=null}function Zl(r,e,t){r.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(n=>e[n].isCommonEncryption)&&s.push(r)}function Ot(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function Jl(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Jr(r,e){const t=e.startPTS;if(K(t)){let s=0,n;e.sn>r.sn?(s=t-r.start,n=r):(s=r.start-t,n=e),n.duration!==s&&n.setDuration(s)}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 dd(r,e,t,s,n,a){s-t<=0&&(pe.warn("Fragment should have a positive duration",e),s=t+e.duration,a=n+e.duration);let l=t,u=s;const d=e.startPTS,p=e.endPTS;if(K(d)){const o=Math.abs(d-t);K(e.deltaPTS)?e.deltaPTS=Math.max(o,e.deltaPTS):e.deltaPTS=o,l=Math.max(t,d),t=Math.min(t,d),n=Math.min(n,e.startDTS),u=Math.min(s,p),s=Math.max(s,p),a=Math.max(a,e.endDTS)}const g=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=l,e.startDTS=n,e.endPTS=s,e.minEndPTS=u,e.endDTS=a;const y=e.sn;if(!r||y<r.startSN||y>r.endSN)return 0;let v;const x=y-r.startSN,E=r.fragments;for(E[x]=e,v=x;v>0;v--)Jr(E[v],E[v-1]);for(v=x;v<E.length-1;v++)Jr(E[v],E[v+1]);return r.fragmentHint&&Jr(E[E.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,g}function Am(r,e){if(r===e)return;let t=null;const s=r.fragments;for(let u=s.length-1;u>=0;u--){const d=s[u].initSegment;if(d){t=d;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let n;Lm(r,e,(u,d,p,g)=>{if(!e.startCC&&d.cc!==u.cc){var y,v;const x=u.cc-d.cc;for(let E=p;E<g.length;E++)g[E].cc+=x;e.startCC=(y=(v=pd(r,e.startSN-1))==null?void 0:v.cc)!=null?y:g[0].cc,e.endCC=g[g.length-1].cc}K(u.startPTS)&&K(u.endPTS)&&(d.setStart(d.startPTS=u.startPTS),d.startDTS=u.startDTS,d.maxStartPTS=u.maxStartPTS,d.endPTS=u.endPTS,d.endDTS=u.endDTS,d.minEndPTS=u.minEndPTS,d.setDuration(u.endPTS-u.startPTS),d.duration&&(n=d),e.PTSKnown=e.alignedSliding=!0),u.hasStreams&&(d.elementaryStreams=u.elementaryStreams),d.loader=u.loader,u.hasStats&&(d.stats=u.stats),u.initSegment&&(d.initSegment=u.initSegment,t=u.initSegment)});const a=e.fragments,h=e.fragmentHint?a.concat(e.fragmentHint):a;if(t&&h.forEach(u=>{var d;u&&(!u.initSegment||u.initSegment.relurl===((d=t)==null?void 0:d.relurl))&&(u.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=a.some(u=>!u),e.deltaUpdateFailed){pe.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=e.skippedSegments;u--;)a.shift();e.startSN=a[0].sn}else{e.endCC=a[a.length-1].cc,e.canSkipDateRanges&&(e.dateRanges=Im(r.dateRanges,e));const u=r.fragments.filter(d=>d.rawProgramDateTime);if(r.hasProgramDateTime&&!e.hasProgramDateTime)for(let d=1;d<h.length;d++)h[d].programDateTime===null&&Fa(h[d],h[d-1],u);cd(u,e)}wm(r.partList,e.partList,(u,d)=>{d.elementaryStreams=u.elementaryStreams,d.stats=u.stats}),n?dd(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):ud(r,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=r.driftStartTime,e.driftStart=r.driftStart;const l=e.advancedDateTime;if(e.advanced&&l){const u=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=u),e.driftEndTime=l,e.driftEnd=u}else e.driftEndTime=r.driftEndTime,e.driftEnd=r.driftEnd,e.advancedDateTime=r.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=r.requestScheduled)}function Im(r,e){const{dateRanges:t,recentlyRemovedDateranges:s}=e,n=Te({},r);s&&s.forEach(l=>{delete n[l]});const h=Object.keys(n).length;return h&&Object.keys(t).forEach(l=>{const u=n[l],d=new od(t[l].attr,u);d.isValid?(n[l]=d,u||(d.tagOrder+=h)):pe.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Ae(t[l].attr)}"`)}),n}function wm(r,e,t){if(r&&e){let s=0;for(let n=0,a=r.length;n<=a;n++){const h=r[n],l=e[n+s];h&&l&&h.index===l.index&&h.fragment.sn===l.fragment.sn?t(h,l):s--}}}function Lm(r,e,t){const s=e.skippedSegments,n=Math.max(r.startSN,e.startSN)-e.startSN,a=(r.fragmentHint?1:0)+(s?e.endSN:Math.min(r.endSN,e.endSN))-e.startSN,h=e.startSN-r.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,u=r.fragmentHint?r.fragments.concat(r.fragmentHint):r.fragments;for(let d=n;d<=a;d++){const p=u[h+d];let g=l[d];if(s&&!g&&p&&(g=e.fragments[d]=p),p&&g){if(t(p,g,d,l),p.url&&p.url!==g.url){e.playlistParsingError=eh(`media sequence mismatch ${g.sn}:`,r,e,p,g);return}else if(p.cc!==g.cc){e.playlistParsingError=eh(`discontinuity sequence mismatch (${p.cc}!=${g.cc})`,r,e,p,g);return}}}}function eh(r,e,t,s,n){return new Error(`${r} ${n.url}
|
|
115
|
+
Time to underbuffer: ${ce.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,J>x){let K=this.findBestLevel(this.hls.levels[x].bitrate,x,J,0,ce,1,1);K===-1&&(K=x),this.hls.nextLoadLevel=this.hls.nextAutoLevel=K,this.resetEstimator(this.hls.levels[K].bitrate)}}};o||O>V*2?ie():this.timer=self.setInterval(ie,V*1e3),h.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:a,stats:p})},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 I0(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(E.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var n;this.fragCurrent=s,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 D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case D.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:n,partCurrent:a}=this;if(s&&n&&s.sn===n.sn&&s.level===n.level){const h=performance.now(),l=a?a.stats:s.stats,u=h-l.loading.start,d=l.loading.first?l.loading.first-l.loading.start:-1;if(l.loaded&&d>-1){const g=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(u-Math.min(g,d),l.loaded)}else this.bwEstimator.sampleTTFB(u)}break}}}getTimeToLoadFrag(e,t,s,n){const a=e+s/t,h=n?e+this.lastLevelLoadSec:0;return a+h}onLevelLoaded(e,t){const s=this.hls.config,{loading:n}=t.stats,a=n.end-n.first;q(a)&&(this.lastLevelLoadSec=a/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const n=s?s.stats:t.stats;if(t.type===X.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 a=s?s.duration:t.duration,h=this.hls.levels[t.level],l=(h.loaded?h.loaded.bytes:0)+n.loaded,u=(h.loaded?h.loaded.duration:0)+a;h.loaded={bytes:l,duration:u},h.realBitrate=Math.round(8*l/u)}if(t.bitrateTest){const a={stats:n,frag:t,part:s,id:t.type};this.onFragBuffered(E.FRAG_BUFFERED,a),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:n}=t,a=n!=null&&n.stats.loaded?n.stats:s.stats;if(a.aborted||this.ignoreFragment(s))return;const h=a.parsing.end-a.loading.start-Math.min(a.loading.first-a.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(h,a.loaded),a.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=h/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==X.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,a=this.findBestLevel(s,t,e,0,n,1,1);if(a>-1)return a;const h=this.hls.firstLevel,l=Math.min(Math.max(h,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${h} clamped to ${l}`),l}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const a=s&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const h=this.hls.levels;if(h.length>Math.max(e,a)&&h[e].loadError<=h[a].loadError)return e}return this._nextAutoLevel=a,this.nextAutoLevelKey=this.getAutoLevelKey(),a}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:n,config:a,minAutoLevel:h}=s,l=t?t.duration:e?e.duration:0,u=this.getBwEstimate(),d=this.getStarvationDelay();let p=a.abrBandWidthFactor,g=a.abrBandWidthUpFactor;if(d){const o=this.findBestLevel(u,h,n,d,0,p,g);if(o>=0)return this.rebufferNotice=-1,o}let y=l?Math.min(l,a.maxStarvationDelay):a.maxStarvationDelay;if(!d){const o=this.bitrateTestDelay;o&&(y=(l?Math.min(l,a.maxLoadingDelay):a.maxLoadingDelay)-o,this.info(`bitrate test took ${Math.round(1e3*o)}ms, set first fragment max fetchDuration to ${Math.round(1e3*y)} ms`),p=g=1)}const x=this.findBestLevel(u,h,n,d,y,p,g);if(this.rebufferNotice!==x&&(this.rebufferNotice=x,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${x}`)),x>-1)return x;const v=s.levels[h],_=s.loadLevelObj;return _&&(v==null?void 0:v.bitrate)<_.bitrate?h:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,n,a,h,l){var u;const d=n+a,p=this.lastLoadedFragLevel,g=p===-1?this.hls.firstLevel:p,{fragCurrent:y,partCurrent:x}=this,{levels:v,allAudioTracks:_,loadLevel:o,config:c}=this.hls;if(v.length===1)return 0;const f=v[g],m=!!((u=this.hls.latestLevelDetails)!=null&&u.live),S=o===-1||p===-1;let T,b="SDR",A=(f==null?void 0:f.frameRate)||0;const{audioPreference:I,videoPreference:L}=c,w=this.audioTracksByGroup||(this.audioTracksByGroup=Sd(_));let R=-1;if(S){if(this.firstSelection!==-1)return this.firstSelection;const U=this.codecTiers||(this.codecTiers=ym(v,w,t,s)),j=mm(U,b,e,I,L),{codecSet:H,videoRanges:V,minFramerate:J,minBitrate:$,minIndex:G,preferHDR:ie}=j;R=G,T=H,b=ie?V[V.length-1]:V[0],A=J,e=Math.max(e,$),this.log(`picked start tier ${be(j)}`)}else T=f==null?void 0:f.codecSet,b=f==null?void 0:f.videoRange;const M=x?x.duration:y?y.duration:0,k=this.bwEstimator.getEstimateTTFB()/1e3,z=[];for(let U=s;U>=t;U--){var O;const j=v[U],H=U>g;if(!j)continue;if(c.useMediaCapabilities&&!j.supportedResult&&!j.supportedPromise){const K=navigator.mediaCapabilities;typeof(K==null?void 0:K.decodingInfo)=="function"&&am(j,w,b,A,e,I)?(j.supportedPromise=vd(j,w,K,this.supportedCache),j.supportedPromise.then(ue=>{if(!this.hls)return;j.supportedResult=ue;const Ce=this.hls.levels,Ge=Ce.indexOf(j);ue.error?this.warn(`MediaCapabilities decodingInfo error: "${ue.error}" for level ${Ge} ${be(ue)}`):ue.supported?ue.decodingInfoResults.some(pt=>pt.smooth===!1||pt.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Ge} not smooth or powerEfficient: ${be(ue)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Ge} ${be(ue)}`),Ge>-1&&Ce.length>1&&(this.log(`Removing unsupported level ${Ge}`),this.hls.removeLevel(Ge),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(ue=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${ue}`)})):j.supportedResult=md}if((T&&j.codecSet!==T||b&&j.videoRange!==b||H&&A>j.frameRate||!H&&A>0&&A<j.frameRate||(O=j.supportedResult)!=null&&(O=O.decodingInfoResults)!=null&&O.some(K=>K.smooth===!1))&&(!S||U!==R)){z.push(U);continue}const V=j.details,J=(x?V==null?void 0:V.partTarget:V==null?void 0:V.averagetargetduration)||M;let $;H?$=l*e:$=h*e;const G=M&&n>=M*2&&a===0?j.averageBitrate:j.maxBitrate,ie=this.getTimeToLoadFrag(k,$,G*J,V===void 0);if($>=G&&(U===p||j.loadError===0&&j.fragmentError===0)&&(ie<=k||!q(ie)||m&&!this.bitrateTestDelay||ie<d)){const K=this.forcedAutoLevel;return U!==o&&(K===-1||K!==o)&&(z.length&&this.trace(`Skipped level(s) ${z.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${v[z[0]].codecs}" ${v[z[0]].videoRange}; not compatible with "${T}" ${b}`),this.info(`switch candidate:${g}->${U} adjustedbw(${Math.round($)})-bitrate=${Math.round($-G)} ttfb:${k.toFixed(1)} avgDuration:${J.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${ie.toFixed(1)} firstSelection:${S} codecSet:${j.codecSet} videoRange:${j.videoRange} hls.loadLevel:${o}`)),S&&(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:s}=this.hls;return Math.min(Math.max(e,s),t)}}const _d={search:function(r,e){let t=0,s=r.length-1,n=null,a=null;for(;t<=s;){n=(t+s)/2|0,a=r[n];const h=e(a);if(h>0)t=n+1;else if(h<0)s=n-1;else return a}return null}};function Em(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!q(e))return null;const s=r[0].programDateTime;if(e<(s||0))return null;const n=r[r.length-1].endProgramDateTime;if(e>=(n||0))return null;for(let a=0;a<r.length;++a){const h=r[a];if(bm(e,t,h))return h}return null}function zi(r,e,t=0,s=0,n=.005){let a=null;if(r){a=e[1+r.sn-e[0].sn]||null;const l=r.endDTS-t;l>0&&l<15e-7&&(t+=15e-7),a&&r.level!==a.level&&a.end<=r.end&&(a=e[2+r.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(a=e[0]);if(a&&((!r||r.level===a.level)&&ql(t,s,a)===0||Tm(a,r,Math.min(n,s))))return a;const h=_d.search(e,ql.bind(null,t,s));return h&&(h!==r||!a)?h:a}function Tm(r,e,t){if(e&&e.start===0&&e.level<r.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((n,a)=>(a[0]==="INF"&&(n+=parseFloat(a[1])),n),t);return r.start<=s}return!1}function ql(r=0,e=0,t){if(t.start<=r&&t.start+t.duration>r)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=r?1:t.start-s>r&&t.start?-1:0}function bm(r,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>r}function Ed(r,e,t){if(r&&r.startCC<=e&&r.endCC>=e){let s=r.fragments;const{fragmentHint:n}=r;n&&(s=s.concat(n));let a;return _d.search(s,h=>h.cc<e?1:h.cc>e?-1:(a=h,h.end<=t?1:h.start>t?-1:0)),a||null}return null}function er(r){switch(r.details){case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_TIMEOUT:case D.LEVEL_LOAD_TIMEOUT:case D.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Td(r){return r.details.startsWith("key")}function bd(r){return Td(r)&&!!r.frag&&!r.frag.decryptdata}function Xl(r,e){const t=er(e);return r.default[`${t?"timeout":"error"}Retry`]}function Do(r,e){const t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function Ql(r){return xe(xe({},r),{errorRetry:null,timeoutRetry:null})}function tr(r,e,t,s){if(!r)return!1;const n=s==null?void 0:s.code,a=e<r.maxNumRetry&&(Am(n)||!!t);return r.shouldRetry?r.shouldRetry(r,e,t,s,a):a}function Am(r){return Ka(r)||!!r&&(r<400||r>499)}function Ka(r){return r===0&&navigator.onLine===!1}var He={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},ot={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class Im extends xt{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(E.ERROR,this.onError,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(E.ERROR,this.onError,this),e.off(E.ERROR,this.onErrorOut,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===X.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;const n=e.audioGroups;if(n)return this.hls.allAudioTracks.filter(h=>n.indexOf(h.groupId)>=0).some(h=>{var l;return(l=h.details)==null?void 0:l.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const n=this.hls,a=t.context;switch(t.details){case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case D.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=ls();return}case D.FRAG_GAP:case D.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=He.SendAlternateToPenaltyBox;return}case D.LEVEL_EMPTY_ERROR:case D.LEVEL_PARSING_ERROR:{var h;const u=t.parent===X.MAIN?t.level:n.loadLevel;t.details===D.LEVEL_EMPTY_ERROR&&((h=t.context)!=null&&(h=h.levelDetails)!=null&&h.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,u):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,u))}return;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:typeof(a==null?void 0:a.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a.level));return;case D.AUDIO_TRACK_LOAD_ERROR:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.SUBTITLE_LOAD_ERROR:case D.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const u=n.loadLevelObj;if(u&&(a.type===fe.AUDIO_TRACK&&u.hasAudioGroup(a.groupId)||a.type===fe.SUBTITLE_TRACK&&u.hasSubtitleGroup(a.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=He.SendAlternateToPenaltyBox,t.errorAction.flags=ot.MoveAllAlternatesMatchingHost;return}}return;case D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:He.SendAlternateToPenaltyBox,flags:ot.MoveAllAlternatesMatchingHDCP};return;case D.KEY_SYSTEM_SESSION_UPDATE_FAILED:case D.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case D.KEY_SYSTEM_NO_SESSION:t.errorAction={action:He.SendAlternateToPenaltyBox,flags:ot.MoveAllAlternatesMatchingKey};return;case D.BUFFER_ADD_CODEC_ERROR:case D.REMUX_ALLOC_ERROR:case D.BUFFER_APPEND_ERROR:if(!t.errorAction){var l;t.errorAction=this.getLevelSwitchAction(t,(l=t.level)!=null?l:n.loadLevel)}return;case D.INTERNAL_EXCEPTION:case D.BUFFER_APPENDING_ERROR:case D.BUFFER_FULL_ERROR:case D.LEVEL_SWITCH_ERROR:case D.BUFFER_STALLED_ERROR:case D.BUFFER_SEEK_OVER_HOLE:case D.BUFFER_NUDGE_ON_STALL:t.errorAction=ls();return}t.type===Z.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=ls())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,n=Xl(s.config.playlistLoadPolicy,e),a=this.playlistError++;if(tr(n,a,er(e),e.response))return{action:He.RetryRequest,flags:ot.None,retryConfig:n,retryCount:a};const l=this.getLevelSwitchAction(e,t);return n&&(l.retryConfig=n,l.retryCount=a),l}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),n=t.levels[s],{fragLoadPolicy:a,keyLoadPolicy:h}=t.config,l=Xl(Td(e)?h:a,e),u=t.levels.reduce((p,g)=>p+g.fragmentError,0);if(n&&(e.details!==D.FRAG_GAP&&n.fragmentError++,!bd(e)&&tr(l,u,er(e),e.response)))return{action:He.RetryRequest,flags:ot.None,retryConfig:l,retryCount:u};const d=this.getLevelSwitchAction(e,s);return l&&(d.retryConfig=l,d.retryCount=u),d}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const n=this.hls.levels[t];if(n){var a,h;const d=e.details;n.loadError++,d===D.BUFFER_APPEND_ERROR&&n.fragmentError++;let p=-1;const{levels:g,loadLevel:y,minAutoLevel:x,maxAutoLevel:v}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const _=(a=e.frag)==null?void 0:a.type,c=(_===X.AUDIO&&d===D.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===D.BUFFER_ADD_CODEC_ERROR||d===D.BUFFER_APPEND_ERROR))&&g.some(({audioCodec:b})=>n.audioCodec!==b),m=e.sourceBufferName==="video"&&(d===D.BUFFER_ADD_CODEC_ERROR||d===D.BUFFER_APPEND_ERROR)&&g.some(({codecSet:b,audioCodec:A})=>n.codecSet!==b&&n.audioCodec===A),{type:S,groupId:T}=(h=e.context)!=null?h:{};for(let b=g.length;b--;){const A=(b+y)%g.length;if(A!==y&&A>=x&&A<=v&&g[A].loadError===0){var l,u;const I=g[A];if(d===D.FRAG_GAP&&_===X.MAIN&&e.frag){const L=g[A].details;if(L){const w=zi(e.frag,L.fragments,e.frag.start);if(w!=null&&w.gap)continue}}else{if(S===fe.AUDIO_TRACK&&I.hasAudioGroup(T)||S===fe.SUBTITLE_TRACK&&I.hasSubtitleGroup(T))continue;if(_===X.AUDIO&&(l=n.audioGroups)!=null&&l.some(L=>I.hasAudioGroup(L))||_===X.SUBTITLE&&(u=n.subtitleGroups)!=null&&u.some(L=>I.hasSubtitleGroup(L))||c&&n.audioCodec===I.audioCodec||m&&n.codecSet===I.codecSet||!c&&n.codecSet!==I.codecSet)continue}p=A;break}}if(p>-1&&s.loadLevel!==p)return e.levelRetry=!0,this.playlistError=0,{action:He.SendAlternateToPenaltyBox,flags:ot.None,nextAutoLevel:p}}return{action:He.SendAlternateToPenaltyBox,flags:ot.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case He.DoNothing:break;case He.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==D.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,s=e.errorAction;if(!s)return;const{flags:n}=s,a=s.nextAutoLevel;switch(n){case ot.None:this.switchLevel(e,a);break;case ot.MoveAllAlternatesMatchingHDCP:{const u=this.getVariantLevelIndex(e.frag),d=t.levels[u],p=d==null?void 0:d.attrs["HDCP-LEVEL"];if(s.hdcpLevel=p,p==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(p){t.maxHdcpLevel=Va[Va.indexOf(p)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case ot.MoveAllAlternatesMatchingKey:{const u=e.decryptdata;if(u){const d=this.hls.levels,p=d.length;for(let y=p;y--;)if(this.variantHasKey(d[y],u)){var h,l;this.log(`Banned key found in level ${y} (${d[y].bitrate}bps) or audio group "${(h=d[y].audioGroups)==null?void 0:h.join(",")}" (${(l=e.frag)==null?void 0:l.type} fragment) ${Ze(u.keyId||[])}`),d[y].fragmentError++,d[y].loadError++,this.log(`Removing level ${y} with key error (${e.error})`),this.hls.removeLevel(y)}const g=e.frag;if(this.hls.levels.length<p)s.resolved=!0;else if(g&&g.type!==X.MAIN){const y=g.decryptdata;y&&!u.matches(y)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,a)}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===D.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=Ha(e.mimeType),n=this.hls.levels;for(let a=n.length;a--;)n[a][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${a} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(a))}}}function ls(r){const e={action:He.DoNothing,flags:ot.None};return r&&(e.resolved=!0),e}var Fe={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class wm{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&&(e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let n=s.length;n--;){const a=s[n];if(!a)break;if(a.start<=e&&e<=a.end&&a.loaded)return a}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:n}=this,a=Object.keys(n);for(let h=a.length;h--;){const l=n[a[h]];if((l==null?void 0:l.body.type)===t&&(!s||l.buffered)){const u=l.body;if(u.start<=e&&e<=u.end)return u}}return null}detectEvictedFragments(e,t,s,n,a){this.timeRanges&&(this.timeRanges[e]=t);const h=(n==null?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(l=>{const u=this.fragments[l];if(!u||h>=u.body.sn)return;if(!u.buffered&&(!u.loaded||a)){u.body.type===s&&this.removeFragment(u.body);return}const d=u.range[e];if(d){if(d.time.length===0){this.removeFragment(u.body);return}d.time.some(p=>{const g=!this.isTimeBuffered(p.startPTS,p.endPTS,t);return g&&this.removeFragment(u.body),g})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,n=qi(s),a=this.fragments[n];if(!a||a.buffered&&s.gap)return;const h=!s.relurl;Object.keys(t).forEach(l=>{const u=s.elementaryStreams[l];if(!u)return;const d=t[l],p=h||u.partial===!0;a.range[l]=this.getBufferedTimes(s,e.part,p,d)}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=s.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),pn(a)||this.removeParts(s.sn-1,s.type)):this.removeFragment(a.body)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Zl(s,n=>n.fragment.sn>=e))}fragBuffered(e,t){const s=qi(e);let n=this.fragments[s];!n&&t&&(n=this.fragments[s]={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,s,n){const a={time:[],partial:s},h=e.start,l=e.end,u=e.minEndPTS||l,d=e.maxStartPTS||h;for(let p=0;p<n.length;p++){const g=n.start(p)-this.bufferPadding,y=n.end(p)+this.bufferPadding;if(d>=g&&u<=y){a.time.push({startPTS:Math.max(h,n.start(p)),endPTS:Math.min(l,n.end(p))});break}else if(h<y&&l>g){const x=Math.max(h,n.start(p)),v=Math.min(l,n.end(p));v>x&&(a.partial=!0,a.time.push({startPTS:x,endPTS:v}))}else if(l<=g)break}return a}getPartialFragment(e){let t=null,s,n,a,h=0;const{bufferPadding:l,fragments:u}=this;return Object.keys(u).forEach(d=>{const p=u[d];p&&pn(p)&&(n=p.body.start-l,a=p.body.end+l,e>=n&&e<=a&&(s=Math.min(e-n,a-e),h<=s&&(t=p.body,h=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||pn(t))}getState(e){const t=qi(e),s=this.fragments[t];return s?s.buffered?pn(s)?Fe.PARTIAL:Fe.OK:Fe.APPENDING:Fe.NOT_LOADED}isTimeBuffered(e,t,s){let n,a;for(let h=0;h<s.length;h++){if(n=s.start(h)-this.bufferPadding,a=s.end(h)+this.bufferPadding,e>=n&&t<=a)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 s=t.frag,n=t.part?null:t,a=qi(s);this.fragments[a]={body:s,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:n,timeRanges:a,type:h}=t;if(s.sn==="initSegment")return;const l=s.type;if(n){let d=this.activePartLists[l];d||(this.activePartLists[l]=d=[]),d.push(n)}this.timeRanges=a;const u=a[h];this.detectEvictedFragments(h,u,l,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=qi(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let n=s.length;n--;){const a=t[s[n]];if((a==null?void 0:a.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,n,a){n&&!this.hasGaps||Object.keys(this.fragments).forEach(h=>{const l=this.fragments[h];if(!l)return;const u=l.body;u.type!==s||n&&!u.gap||u.start<t&&u.end>e&&(l.buffered||a)&&this.removeFragment(u)})}removeFragment(e){const t=qi(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const n=e.sn;this.activePartLists[e.type]=Zl(s,a=>a.fragment.sn!==n)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(s=>s.clearElementaryStreamInfo())}}function pn(r){var e,t,s;return r.buffered&&!!(r.body.gap||(e=r.range.video)!=null&&e.partial||(t=r.range.audio)!=null&&t.partial||(s=r.range.audiovideo)!=null&&s.partial)}function qi(r){return`${r.type}_${r.level}_${r.sn}`}function Zl(r,e){return r.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var _i={cbc:0,ctr:1};class Lm{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case _i.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case _i.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 Rm(r){const e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?r.slice(0,e-t):r}class Cm{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),s=new Uint32Array(4);for(let n=0;n<4;n++)s[n]=t.getUint32(n*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,n=s[0],a=s[1],h=s[2],l=s[3],u=this.invSubMix,d=u[0],p=u[1],g=u[2],y=u[3],x=new Uint32Array(256);let v=0,_=0,o=0;for(o=0;o<256;o++)o<128?x[o]=o<<1:x[o]=o<<1^283;for(o=0;o<256;o++){let c=_^_<<1^_<<2^_<<3^_<<4;c=c>>>8^c&255^99,e[v]=c,t[c]=v;const f=x[v],m=x[f],S=x[m];let T=x[c]*257^c*16843008;n[v]=T<<24|T>>>8,a[v]=T<<16|T>>>16,h[v]=T<<8|T>>>24,l[v]=T,T=S*16843009^m*65537^f*257^v*16843008,d[c]=T<<24|T>>>8,p[c]=T<<16|T>>>16,g[c]=T<<8|T>>>24,y[c]=T,v?(v=f^x[x[x[S^f]]],_^=x[x[_]]):v=_=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,n=0;for(;n<t.length&&s;)s=t[n]===this.key[n],n++;if(s)return;this.key=t;const a=this.keySize=t.length;if(a!==4&&a!==6&&a!==8)throw new Error("Invalid aes key size="+a);const h=this.ksRows=(a+6+1)*4;let l,u;const d=this.keySchedule=new Uint32Array(h),p=this.invKeySchedule=new Uint32Array(h),g=this.sBox,y=this.rcon,x=this.invSubMix,v=x[0],_=x[1],o=x[2],c=x[3];let f,m;for(l=0;l<h;l++){if(l<a){f=d[l]=t[l];continue}m=f,l%a===0?(m=m<<8|m>>>24,m=g[m>>>24]<<24|g[m>>>16&255]<<16|g[m>>>8&255]<<8|g[m&255],m^=y[l/a|0]<<24):a>6&&l%a===4&&(m=g[m>>>24]<<24|g[m>>>16&255]<<16|g[m>>>8&255]<<8|g[m&255]),d[l]=f=(d[l-a]^m)>>>0}for(u=0;u<h;u++)l=h-u,u&3?m=d[l]:m=d[l-4],u<4||l<=4?p[u]=m:p[u]=v[g[m>>>24]]^_[g[m>>>16&255]]^o[g[m>>>8&255]]^c[g[m&255]],p[u]=p[u]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const n=this.keySize+6,a=this.invKeySchedule,h=this.invSBox,l=this.invSubMix,u=l[0],d=l[1],p=l[2],g=l[3],y=this.uint8ArrayToUint32Array_(s);let x=y[0],v=y[1],_=y[2],o=y[3];const c=new Int32Array(e),f=new Int32Array(c.length);let m,S,T,b,A,I,L,w,R,M,k,z,O,U;const j=this.networkToHostOrderSwap;for(;t<c.length;){for(R=j(c[t]),M=j(c[t+1]),k=j(c[t+2]),z=j(c[t+3]),A=R^a[0],I=z^a[1],L=k^a[2],w=M^a[3],O=4,U=1;U<n;U++)m=u[A>>>24]^d[I>>16&255]^p[L>>8&255]^g[w&255]^a[O],S=u[I>>>24]^d[L>>16&255]^p[w>>8&255]^g[A&255]^a[O+1],T=u[L>>>24]^d[w>>16&255]^p[A>>8&255]^g[I&255]^a[O+2],b=u[w>>>24]^d[A>>16&255]^p[I>>8&255]^g[L&255]^a[O+3],A=m,I=S,L=T,w=b,O=O+4;m=h[A>>>24]<<24^h[I>>16&255]<<16^h[L>>8&255]<<8^h[w&255]^a[O],S=h[I>>>24]<<24^h[L>>16&255]<<16^h[w>>8&255]<<8^h[A&255]^a[O+1],T=h[L>>>24]<<24^h[w>>16&255]<<16^h[A>>8&255]<<8^h[I&255]^a[O+2],b=h[w>>>24]<<24^h[A>>16&255]<<16^h[I>>8&255]<<8^h[L&255]^a[O+3],f[t]=j(m^x),f[t+1]=j(b^v),f[t+2]=j(T^_),f[t+3]=j(S^o),x=R,v=M,_=k,o=z,t=t+4}return f.buffer}}class Pm{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=Dm(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function Dm(r){switch(r){case _i.cbc:return"AES-CBC";case _i.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${r}`)}}const km=16;class ko{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 s=self.crypto;s&&(this.subtle=s.subtle||s.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 s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Rm(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,n){return this.useSoftware?new Promise((a,h)=>{const l=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(l,t,s,n);const u=this.flush();u?a(u.buffer):h(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,n)}softwareDecrypt(e,t,s,n){const{currentIV:a,currentResult:h,remainderData:l}=this;if(n!==_i.cbc||t.byteLength!==16)return _e.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),l&&(e=yt(l,e),this.remainderData=null);const u=this.getValidChunk(e);if(!u.length)return null;a&&(s=a);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new Cm),d.expandKey(t);const p=h;return this.currentResult=d.decrypt(u.buffer,0,s),this.currentIV=u.slice(-16).buffer,p||null}webCryptoDecrypt(e,t,s,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,n));this.key=t,this.fastAesKey=new Pm(this.subtle,t,n)}return this.fastAesKey.expandKey().then(a=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Lm(this.subtle,new Uint8Array(s),n).decrypt(e.buffer,a)):Promise.reject(new Error("web crypto not initialized"))).catch(a=>(_e.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${a.name}: ${a.message}`),this.onWebCryptoError(e,t,s,n)))}onWebCryptoError(e,t,s,n){const a=this.enableSoftwareAES;if(a){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,n);const h=this.flush();if(h)return h.buffer}throw new Error("WebCrypto"+(a?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%km;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(_e.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Jl=Math.pow(2,17);class Mm{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 s=e.url;if(!s)return Promise.reject(new qt({type:Z.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,a=n.fLoader,h=n.loader;return new Promise((l,u)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(v=>v[0]==="GAP")){u(th(e));return}else e.gap=!1;const d=this.loader=a?new a(n):new h(n),p=eh(e);e.loader=d;const g=Ql(n.fragLoadPolicy.default),y={loadPolicy:g,timeout:g.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Jl};e.stats=d.stats;const x={onSuccess:(v,_,o,c)=>{this.resetLoader(e,d);let f=v.data;o.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(f.slice(0,16)),f=f.slice(16)),l({frag:e,part:null,payload:f,networkDetails:c})},onError:(v,_,o,c)=>{this.resetLoader(e,d),u(new qt({type:Z.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:xe({url:s,data:void 0},v),error:new Error(`HTTP Error ${v.code} ${v.text}`),networkDetails:o,stats:c}))},onAbort:(v,_,o)=>{this.resetLoader(e,d),u(new qt({type:Z.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:o,stats:v}))},onTimeout:(v,_,o)=>{this.resetLoader(e,d),u(new qt({type:Z.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${y.timeout}ms`),networkDetails:o,stats:v}))}};t&&(x.onProgress=(v,_,o,c)=>t({frag:e,part:null,payload:o,networkDetails:c})),d.load(p,y,x)})}loadPart(e,t,s){this.abort();const n=this.config,a=n.fLoader,h=n.loader;return new Promise((l,u)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){u(th(e,t));return}const d=this.loader=a?new a(n):new h(n),p=eh(e,t);e.loader=d;const g=Ql(n.fragLoadPolicy.default),y={loadPolicy:g,timeout:g.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Jl};t.stats=d.stats,d.load(p,y,{onSuccess:(x,v,_,o)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);const c={frag:e,part:t,payload:x.data,networkDetails:o};s(c),l(c)},onError:(x,v,_,o)=>{this.resetLoader(e,d),u(new qt({type:Z.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:xe({url:p.url,data:void 0},x),error:new Error(`HTTP Error ${x.code} ${x.text}`),networkDetails:_,stats:o}))},onAbort:(x,v,_)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),u(new qt({type:Z.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:_,stats:x}))},onTimeout:(x,v,_)=>{this.resetLoader(e,d),u(new qt({type:Z.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${y.timeout}ms`),networkDetails:_,stats:x}))}})})}updateStatsFromPart(e,t){const s=e.stats,n=t.stats,a=n.total;if(s.loaded+=n.loaded,a){const u=Math.round(e.duration/t.duration),d=Math.min(Math.round(s.loaded/a),u),g=(u-d)*Math.round(s.loaded/d);s.total=s.loaded+g}else s.total=Math.max(s.loaded,s.total);const h=s.loading,l=n.loading;h.start?h.first+=l.first-l.start:(h.start=l.start,h.first=l.first),h.end=l.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function eh(r,e=null){const t=e||r,s={frag:r,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},n=t.byteRangeStartOffset,a=t.byteRangeEndOffset;if(q(n)&&q(a)){var h;let l=n,u=a;if(r.sn==="initSegment"&&Fm((h=r.decryptdata)==null?void 0:h.method)){const d=a-n;d%16&&(u=a+(16-d%16)),n!==0&&(s.resetIV=!0,l=n-16)}s.rangeStart=l,s.rangeEnd=u}return s}function th(r,e){const t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),s={type:Z.MEDIA_ERROR,details:D.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(s.part=e),(e||r).stats.aborted=!0,new qt(s)}function Fm(r){return r==="AES-128"||r==="AES-256"}class qt extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Ad extends xt{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 Mo{constructor(e,t,s,n=0,a=-1,h=!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=gn(),this.buffering={audio:gn(),video:gn(),audiovideo:gn()},this.level=e,this.sn=t,this.id=s,this.size=n,this.part=a,this.partial=h}}function gn(){return{start:0,executeStart:0,executeEnd:0,end:0}}const ih={length:0,start:()=>0,end:()=>0};class ae{static isBuffered(e,t){if(e){const s=ae.getBuffered(e);for(let n=s.length;n--;)if(t>=s.start(n)&&t<=s.end(n))return!0}return!1}static bufferedRanges(e){if(e){const t=ae.getBuffered(e);return ae.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const n=ae.bufferedRanges(e);if(n.length)return ae.bufferedInfo(n,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((p,g)=>p.start-g.start||g.end-p.end);let n=-1,a=[];if(s)for(let p=0;p<e.length;p++){t>=e[p].start&&t<=e[p].end&&(n=p);const g=a.length;if(g){const y=a[g-1].end;e[p].start-y<s?e[p].end>y&&(a[g-1].end=e[p].end):a.push(e[p])}else a.push(e[p])}else a=e;let h=0,l,u=t,d=t;for(let p=0;p<a.length;p++){const g=a[p].start,y=a[p].end;if(n===-1&&t>=g&&t<=y&&(n=p),t+s>=g&&t<y)u=g,d=y,h=d-t;else if(t+s<g){l=g;break}}return{len:h,start:u||0,end:d||0,nextStart:l,buffered:e,bufferedIndex:n}}static getBuffered(e){try{return e.buffered||ih}catch(t){return _e.log("failed to get media.buffered",t),ih}}}const Id=/\{\$([a-zA-Z0-9-_]+)\}/g;function sh(r){return Id.test(r)}function Ya(r,e){if(r.variableList!==null||r.hasVariableRefs){const t=r.variableList;return e.replace(Id,s=>{const n=s.substring(2,s.length-1),a=t==null?void 0:t[n];return a===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),s):a})}return e}function nh(r,e,t){let s=r.variableList;s||(r.variableList=s={});let n,a;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const h=new self.URL(t).searchParams;if(h.has(n))a=h.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(h){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${h.message}`))}}else n=e.NAME,a=e.VALUE;n in s?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):s[n]=a||""}function Um(r,e,t){const s=e.IMPORT;if(t&&s in t){let n=r.variableList;n||(r.variableList=n={}),n[s]=t[s]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const Om=/^(\d+)x(\d+)$/,rh=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Ae{constructor(e,t){typeof e=="string"&&(e=Ae.parseAttrList(e,t)),Ee(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 s=new Uint8Array(t.length/2);for(let n=0;n<t.length/2;n++)s[n]=parseInt(t.slice(n*2,n*2+2),16);return s}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 s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((n,a)=>(n[a.toLowerCase()]=!0,n),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=Om.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const n={},a='"';for(rh.lastIndex=0;(s=rh.exec(e))!==null;){const h=s[1].trim();let l=s[2];const u=l.indexOf(a)===0&&l.lastIndexOf(a)===l.length-1;let d=!1;if(u)l=l.slice(1,-1);else switch(h){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(u||d))l=Ya(t,l);else if(!d&&!u)switch(h){case"CLOSED-CAPTIONS":if(l==="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":_e.warn(`${e}: attribute ${h} is missing quotes`)}n[h]=l}return n}}const Bm="com.apple.hls.interstitial";function Nm(r){return r!=="ID"&&r!=="CLASS"&&r!=="CUE"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function $m(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"||r==="SCTE35-CMD"}class wd{constructor(e,t,s=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:s,t){const a=t.attr;for(const h in a)if(Object.prototype.hasOwnProperty.call(e,h)&&e[h]!==a[h]){_e.warn(`DATERANGE tag attribute: "${h}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=h;break}e=Ee(new Ae({}),a,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 a=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);q(a.getTime())&&(this._endDate=a)}}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?(_e.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(q(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===Bm}get isValid(){return!!this.id&&!this._badValueForSameId&&q(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const Gm=10;class zm{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,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?q(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Gm}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(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let s=e.length;s--;)if(e[s].index>t)return e[s].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 ir(r,e){return r.length===e.length?!r.some((t,s)=>t!==e[s]):!1}function ah(r,e){return!r&&!e?!0:!r||!e?!1:ir(r,e)}function hs(r){return r==="AES-128"||r==="AES-256"||r==="AES-256-CTR"}function Fo(r){switch(r){case"AES-128":case"AES-256":return _i.cbc;case"AES-256-CTR":return _i.ctr;default:throw new Error(`invalid full segment method ${r}`)}}function Uo(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function Wa(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}function Hm(r){const e=Wa(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Ld(r){const e=function(s,n,a){const h=s[n];s[n]=s[a],s[a]=h};e(r,0,3),e(r,1,2),e(r,4,5),e(r,6,7)}function Rd(r){const e=r.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),n=s[s.length-1].split(",");if(n.length===2){const a=n[0]==="base64",h=n[1];a?(s.splice(-1,1),t=Uo(h)):t=Hm(h)}}return t}const sr=typeof self<"u"?self:void 0;var Le={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ve={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Un(r){switch(r){case Ve.FAIRPLAY:return Le.FAIRPLAY;case Ve.PLAYREADY:return Le.PLAYREADY;case Ve.WIDEVINE:return Le.WIDEVINE;case Ve.CLEARKEY:return Le.CLEARKEY}}function aa(r){switch(r){case Le.FAIRPLAY:return Ve.FAIRPLAY;case Le.PLAYREADY:return Ve.PLAYREADY;case Le.WIDEVINE:return Ve.WIDEVINE;case Le.CLEARKEY:return Ve.CLEARKEY}}function Rs(r){const{drmSystems:e,widevineLicenseUrl:t}=r,s=e?[Le.FAIRPLAY,Le.WIDEVINE,Le.PLAYREADY,Le.CLEARKEY].filter(n=>!!e[n]):[];return!s[Le.WIDEVINE]&&t&&s.push(Le.WIDEVINE),s}const Cd=function(r){return sr!=null&&(r=sr.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Vm(r,e,t,s){let n;switch(r){case Le.FAIRPLAY:n=["cenc","sinf"];break;case Le.WIDEVINE:case Le.PLAYREADY:n=["cenc"];break;case Le.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return Km(n,e,t,s)}function Km(r,e,t,s){return[{initDataTypes:r,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(a=>({contentType:`audio/mp4; codecs=${a}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(a=>({contentType:`video/mp4; codecs=${a}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function Ym(r){var e;return!!r&&(r.sessionType==="persistent-license"||!!((e=r.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Pd(r){const e=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),h=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(h){const l=h.childNodes[0]?h.childNodes[0].nodeValue:h.getAttribute("VALUE");if(l){const u=Uo(l).subarray(0,16);return Ld(u),u}}return null}let mn={};class Ni{static clearKeyUriToKeyIdMap(){mn={}}static setKeyIdForUri(e,t){mn[e]=t}constructor(e,t,s,n=[1],a=null,h){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=s,this.keyFormatVersions=n,this.iv=a,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!hs(e),h!=null&&h.startsWith("0x")&&(this.keyId=new Uint8Array(rd(h)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&ir(e.keyFormatVersions,this.keyFormatVersions)&&ah(e.iv,this.iv)&&ah(e.keyId,this.keyId)}isSupported(){if(this.method){if(hs(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Ve.FAIRPLAY:case Ve.WIDEVINE:case Ve.PLAYREADY:case Ve.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(hs(this.method)){let a=this.iv;return a||(typeof e!="number"&&(_e.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),a=jm(e)),new Ni(this.method,this.uri,"identity",this.keyFormatVersions,a)}if(this.keyId){const a=mn[this.uri];if(a&&!ir(this.keyId,a)&&Ni.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=Rd(this.uri);if(s)switch(this.keyFormat){case Ve.WIDEVINE:if(this.pssh=s,!this.keyId){const a=Q0(s.buffer);if(a.length){var n;const h=a[0];this.keyId=(n=h.kids)!=null&&n.length?h.kids[0]:null}}this.keyId||(this.keyId=oh(t));break;case Ve.PLAYREADY:{const a=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=X0(a,null,s),this.keyId=Pd(s);break}default:{let a=s.subarray(0,16);if(a.length!==16){const h=new Uint8Array(16);h.set(a,16-a.length),a=h}this.keyId=a;break}}if(!this.keyId||this.keyId.byteLength!==16){let a;a=Wm(t),a||(a=oh(t),a||(a=mn[this.uri])),a&&(this.keyId=a,Ni.setKeyIdForUri(this.uri,a))}return this}}function Wm(r){const e=r==null?void 0:r[Ve.WIDEVINE];return e?e.keyId:null}function oh(r){const e=r==null?void 0:r[Ve.PLAYREADY];if(e){const t=Rd(e.uri);if(t)return Pd(t)}return null}function jm(r){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}const lh=/#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,hh=/#EXT-X-MEDIA:(.*)/g,qm=/^#EXT(?:INF|-X-TARGETDURATION):/m,oa=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Xm=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 Ut{static findGroup(e,t){for(let s=0;s<e.length;s++){const n=e[s];if(n.id===t)return n}}static resolve(e,t){return wo.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return qm.test(e)}static parseMasterPlaylist(e,t){const s=sh(e),n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},a=[];if(lh.lastIndex=0,!e.startsWith("#EXTM3U"))return n.playlistParsingError=new Error("no EXTM3U delimiter"),n;let h;for(;(h=lh.exec(e))!=null;)if(h[1]){var l;const d=new Ae(h[1],n),p=Ya(n,h[2]),g={attrs:d,bitrate:d.decimalInteger("BANDWIDTH")||d.decimalInteger("AVERAGE-BANDWIDTH"),name:d.NAME,url:Ut.resolve(p,t)},y=d.decimalResolution("RESOLUTION");y&&(g.width=y.width,g.height=y.height),uh(d.CODECS,g);const x=d["SUPPLEMENTAL-CODECS"];x&&(g.supplemental={},uh(x,g.supplemental)),(l=g.unknownCodecs)!=null&&l.length||a.push(g),n.levels.push(g)}else if(h[3]){const d=h[3],p=h[4];switch(d){case"SESSION-DATA":{const g=new Ae(p,n),y=g["DATA-ID"];y&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[y]=g);break}case"SESSION-KEY":{const g=ch(p,t,n);g.encrypted&&g.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(g)):_e.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${p}"`);break}case"DEFINE":{{const g=new Ae(p,n);nh(n,g,t)}break}case"CONTENT-STEERING":{const g=new Ae(p,n);n.contentSteering={uri:Ut.resolve(g["SERVER-URI"],t),pathwayId:g["PATHWAY-ID"]||"."};break}case"START":{n.startTimeOffset=dh(p);break}}}const u=a.length>0&&a.length<n.levels.length;return n.levels=u?a:n.levels,n.levels.length===0&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(e,t,s){let n;const a={},h=s.levels,l={AUDIO:h.map(d=>({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:h.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let u=0;for(hh.lastIndex=0;(n=hh.exec(e))!==null;){const d=new Ae(n[1],s),p=d.TYPE;if(p){const g=l[p],y=a[p]||[];a[p]=y;const x=d.LANGUAGE,v=d["ASSOC-LANGUAGE"],_=d.CHANNELS,o=d.CHARACTERISTICS,c=d["INSTREAM-ID"],f={attrs:d,bitrate:0,id:u++,groupId:d["GROUP-ID"]||"",name:d.NAME||x||"",type:p,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:x,url:d.URI?Ut.resolve(d.URI,t):""};if(v&&(f.assocLang=v),_&&(f.channels=_),o&&(f.characteristics=o),c&&(f.instreamId=c),g!=null&&g.length){const m=Ut.findGroup(g,f.groupId)||g[0];fh(f,m,"audioCodec"),fh(f,m,"textCodec")}y.push(f)}}return a}static parseLevelPlaylist(e,t,s,n,a,h){var l;const u={url:t},d=new zm(t),p=d.fragments,g=[];let y=null,x=0,v=0,_=0,o=0,c=0,f=null,m=new sa(n,u),S,T,b,A=-1,I=!1,L=null,w;if(oa.lastIndex=0,d.m3u8=e,d.hasVariableRefs=sh(e),((l=oa.exec(e))==null?void 0:l[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(S=oa.exec(e))!==null;){I&&(I=!1,m=new sa(n,u),m.playlistOffset=_,m.setStart(_),m.sn=x,m.cc=o,c&&(m.bitrate=c),m.level=s,y&&(m.initSegment=y,y.rawProgramDateTime&&(m.rawProgramDateTime=y.rawProgramDateTime,y.rawProgramDateTime=null),L&&(m.setByteRange(L),L=null)));const z=S[1];if(z){m.duration=parseFloat(z);const O=(" "+S[2]).slice(1);m.title=O||null,m.tagList.push(O?["INF",z,O]:["INF",z])}else if(S[3]){if(q(m.duration)){m.playlistOffset=_,m.setStart(_),b&&gh(m,b,d),m.sn=x,m.level=s,m.cc=o,p.push(m);const O=(" "+S[3]).slice(1);m.relurl=Ya(d,O),ja(m,f,g),f=m,_+=m.duration,x++,v=0,I=!0}}else{if(S=S[0].match(Xm),!S){_e.warn("No matches on slow regex match for level playlist!");continue}for(T=1;T<S.length&&S[T]===void 0;T++);const O=(" "+S[T]).slice(1),U=(" "+S[T+1]).slice(1),j=S[T+2]?(" "+S[T+2]).slice(1):null;switch(O){case"BYTERANGE":f?m.setByteRange(U,f):m.setByteRange(U);break;case"PROGRAM-DATE-TIME":m.rawProgramDateTime=U,m.tagList.push(["PROGRAM-DATE-TIME",U]),A===-1&&(A=p.length);break;case"PLAYLIST-TYPE":d.type&&Kt(d,O,S),d.type=U.toUpperCase();break;case"MEDIA-SEQUENCE":d.startSN!==0?Kt(d,O,S):p.length>0&&mh(d,O,S),x=d.startSN=parseInt(U);break;case"SKIP":{d.skippedSegments&&Kt(d,O,S);const H=new Ae(U,d),V=H.decimalInteger("SKIPPED-SEGMENTS");if(q(V)){d.skippedSegments+=V;for(let $=V;$--;)p.push(null);x+=V}const J=H.enumeratedString("RECENTLY-REMOVED-DATERANGES");J&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(J.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&Kt(d,O,S),d.targetduration=Math.max(parseInt(U),1);break;case"VERSION":d.version!==null&&Kt(d,O,S),d.version=parseInt(U);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||Kt(d,O,S),d.live=!1;break;case"#":(U||j)&&m.tagList.push(j?[U,j]:[U]);break;case"DISCONTINUITY":o++,m.tagList.push(["DIS"]);break;case"GAP":m.gap=!0,m.tagList.push([O]);break;case"BITRATE":m.tagList.push([O,U]),c=parseInt(U)*1e3,q(c)?m.bitrate=c:c=0;break;case"DATERANGE":{const H=new Ae(U,d),V=new wd(H,d.dateRanges[H.ID],d.dateRangeTagCount);d.dateRangeTagCount++,V.isValid||d.skippedSegments?d.dateRanges[V.id]=V:_e.warn(`Ignoring invalid DATERANGE tag: "${U}"`),m.tagList.push(["EXT-X-DATERANGE",U]);break}case"DEFINE":{{const H=new Ae(U,d);"IMPORT"in H?Um(d,H,h):nh(d,H,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?Kt(d,O,S):p.length>0&&mh(d,O,S),d.startCC=o=parseInt(U);break;case"KEY":{const H=ch(U,t,d);if(H.isSupported()){if(H.method==="NONE"){b=void 0;break}b||(b={});const V=b[H.keyFormat];V!=null&&V.matches(H)||(V&&(b=Ee({},b)),b[H.keyFormat]=H)}else _e.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${U}"`);break}case"START":d.startTimeOffset=dh(U);break;case"MAP":{const H=new Ae(U,d);if(m.duration){const V=new sa(n,u);ph(V,H,s,b),y=V,m.initSegment=y,y.rawProgramDateTime&&!m.rawProgramDateTime&&(m.rawProgramDateTime=y.rawProgramDateTime)}else{const V=m.byteRangeEndOffset;if(V){const J=m.byteRangeStartOffset;L=`${V-J}@${J}`}else L=null;ph(m,H,s,b),y=m,I=!0}y.cc=o;break}case"SERVER-CONTROL":{w&&Kt(d,O,S),w=new Ae(U),d.canBlockReload=w.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=w.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&w.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=w.optionalFloat("PART-HOLD-BACK",0),d.holdBack=w.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&Kt(d,O,S);const H=new Ae(U);d.partTarget=H.decimalFloatingPoint("PART-TARGET");break}case"PART":{let H=d.partList;H||(H=d.partList=[]);const V=v>0?H[H.length-1]:void 0,J=v++,$=new Ae(U,d),G=new U0($,m,u,J,V);H.push(G),m.duration+=G.duration;break}case"PRELOAD-HINT":{const H=new Ae(U,d);d.preloadHint=H;break}case"RENDITION-REPORT":{const H=new Ae(U,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(H);break}default:_e.warn(`line parsed but not handled: ${S}`);break}}}f&&!f.relurl?(p.pop(),_-=f.duration,d.partList&&(d.fragmentHint=f)):d.partList&&(ja(m,f,g),m.cc=o,d.fragmentHint=m,b&&gh(m,b,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const R=p.length,M=p[0],k=p[R-1];if(_+=d.skippedSegments*d.targetduration,_>0&&R&&k){d.averagetargetduration=_/R;const z=k.sn;d.endSN=z!=="initSegment"?z:0,d.live||(k.endList=!0),A>0&&(Zm(p,A),M&&g.unshift(M))}return d.fragmentHint&&(_+=d.fragmentHint.duration),d.totalduration=_,g.length&&d.dateRangeTagCount&&M&&Dd(g,d),d.endCC=o,d}}function Dd(r,e){let t=r.length;if(!t)if(e.hasProgramDateTime){const l=e.fragments[e.fragments.length-1];r.push(l),t++}else return;const s=r[t-1],n=e.live?1/0:e.totalduration,a=Object.keys(e.dateRanges);for(let l=a.length;l--;){const u=e.dateRanges[a[l]],d=u.startDate.getTime();u.tagAnchor=s.ref;for(let p=t;p--;){var h;if(((h=r[p])==null?void 0:h.sn)<e.startSN)break;const g=Qm(e,d,r,p,n);if(g!==-1){u.tagAnchor=e.fragments[g].ref;break}}}}function Qm(r,e,t,s,n){const a=t[s];if(a){const l=a.programDateTime;if(e>=l||s===0){var h;const u=(((h=t[s+1])==null?void 0:h.start)||n)-a.start;if(e<=l+u*1e3){const d=t[s].sn-r.startSN;if(d<0)return-1;const p=r.fragments;if(p.length>t.length){const y=(t[s+1]||p[p.length-1]).sn-r.startSN;for(let x=y;x>d;x--){const v=p[x].programDateTime;if(e>=v&&e<v+p[x].duration*1e3)return x}}return d}}}return-1}function ch(r,e,t){var s,n;const a=new Ae(r,t),h=(s=a.METHOD)!=null?s:"",l=a.URI,u=a.hexadecimalInteger("IV"),d=a.KEYFORMATVERSIONS,p=(n=a.KEYFORMAT)!=null?n:"identity";l&&a.IV&&!u&&_e.error(`Invalid IV: ${a.IV}`);const g=l?Ut.resolve(l,e):"",y=(d||"1").split("/").map(Number).filter(Number.isFinite);return new Ni(h,g,p,y,u,a.KEYID)}function dh(r){const t=new Ae(r).decimalFloatingPoint("TIME-OFFSET");return q(t)?t:null}function uh(r,e){let t=(r||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const n=t.filter(a=>Co(a,s));n.length&&(e[`${s}Codec`]=n.map(a=>a.split("/")[0]).join(","),t=t.filter(a=>n.indexOf(a)===-1))}),e.unknownCodecs=t}function fh(r,e,t){const s=e[t];s&&(r[t]=s)}function Zm(r,e){let t=r[e];for(let s=e;s--;){const n=r[s];if(!n)return;n.programDateTime=t.programDateTime-n.duration*1e3,t=n}}function ja(r,e,t){r.rawProgramDateTime?t.push(r):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime)}function ph(r,e,t,s){r.relurl=e.URI,e.BYTERANGE&&r.setByteRange(e.BYTERANGE),r.level=t,r.sn="initSegment",s&&(r.levelkeys=s),r.initSegment=null}function gh(r,e,t){r.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(n=>e[n].isCommonEncryption)&&s.push(r)}function Kt(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function mh(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function la(r,e){const t=e.startPTS;if(q(t)){let s=0,n;e.sn>r.sn?(s=t-r.start,n=r):(s=r.start-t,n=e),n.duration!==s&&n.setDuration(s)}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 kd(r,e,t,s,n,a,h){s-t<=0&&(h.warn("Fragment should have a positive duration",e),s=t+e.duration,a=n+e.duration);let u=t,d=s;const p=e.startPTS,g=e.endPTS;if(q(p)){const c=Math.abs(p-t);r&&c>r.totalduration?h.warn(`media timestamps and playlist times differ by ${c}s for level ${e.level} ${r.url}`):q(e.deltaPTS)?e.deltaPTS=Math.max(c,e.deltaPTS):e.deltaPTS=c,u=Math.max(t,p),t=Math.min(t,p),n=e.startDTS!==void 0?Math.min(n,e.startDTS):n,d=Math.min(s,g),s=Math.max(s,g),a=e.endDTS!==void 0?Math.max(a,e.endDTS):a}const y=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=u,e.startDTS=n,e.endPTS=s,e.minEndPTS=d,e.endDTS=a;const x=e.sn;if(!r||x<r.startSN||x>r.endSN)return 0;let v;const _=x-r.startSN,o=r.fragments;for(o[_]=e,v=_;v>0;v--)la(o[v],o[v-1]);for(v=_;v<o.length-1;v++)la(o[v],o[v+1]);return r.fragmentHint&&la(o[o.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,y}function Jm(r,e,t){if(r===e)return;let s=null;const n=r.fragments;for(let p=n.length-1;p>=0;p--){const g=n[p].initSegment;if(g){s=g;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let a;iy(r,e,(p,g,y,x)=>{if((!e.startCC||e.skippedSegments)&&g.cc!==p.cc){const v=p.cc-g.cc;for(let _=y;_<x.length;_++)x[_].cc+=v;e.endCC=x[x.length-1].cc}q(p.startPTS)&&q(p.endPTS)&&(g.setStart(g.startPTS=p.startPTS),g.startDTS=p.startDTS,g.maxStartPTS=p.maxStartPTS,g.endPTS=p.endPTS,g.endDTS=p.endDTS,g.minEndPTS=p.minEndPTS,g.setDuration(p.endPTS-p.startPTS),g.duration&&(a=g),e.PTSKnown=e.alignedSliding=!0),p.hasStreams&&(g.elementaryStreams=p.elementaryStreams),g.loader=p.loader,p.hasStats&&(g.stats=p.stats),p.initSegment&&(g.initSegment=p.initSegment,s=p.initSegment)});const h=e.fragments,l=e.fragmentHint?h.concat(e.fragmentHint):h;if(s&&l.forEach(p=>{var g;p&&(!p.initSegment||p.initSegment.relurl===((g=s)==null?void 0:g.relurl))&&(p.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=h.some(p=>!p),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let p=e.skippedSegments;p--;)h.shift();e.startSN=h[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=ey(r.dateRanges,e,t));const p=r.fragments.filter(g=>g.rawProgramDateTime);if(r.hasProgramDateTime&&!e.hasProgramDateTime)for(let g=1;g<l.length;g++)l[g].programDateTime===null&&ja(l[g],l[g-1],p);Dd(p,e)}e.endCC=h[h.length-1].cc}if(!e.startCC){var u;const p=Ud(r,e.startSN-1);e.startCC=(u=p==null?void 0:p.cc)!=null?u:h[0].cc}ty(r.partList,e.partList,(p,g)=>{g.elementaryStreams=p.elementaryStreams,g.stats=p.stats}),a?kd(e,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,t):Md(r,e),h.length&&(e.totalduration=e.edge-h[0].start),e.driftStartTime=r.driftStartTime,e.driftStart=r.driftStart;const d=e.advancedDateTime;if(e.advanced&&d){const p=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=p),e.driftEndTime=d,e.driftEnd=p}else e.driftEndTime=r.driftEndTime,e.driftEnd=r.driftEnd,e.advancedDateTime=r.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=r.requestScheduled)}function ey(r,e,t){const{dateRanges:s,recentlyRemovedDateranges:n}=e,a=Ee({},r);n&&n.forEach(u=>{delete a[u]});const l=Object.keys(a).length;return l?(Object.keys(s).forEach(u=>{const d=a[u],p=new wd(s[u].attr,d);p.isValid?(a[u]=p,d||(p.tagOrder+=l)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${be(s[u].attr)}"`)}),a):s}function ty(r,e,t){if(r&&e){let s=0;for(let n=0,a=r.length;n<=a;n++){const h=r[n],l=e[n+s];h&&l&&h.index===l.index&&h.fragment.sn===l.fragment.sn?t(h,l):s--}}}function iy(r,e,t){const s=e.skippedSegments,n=Math.max(r.startSN,e.startSN)-e.startSN,a=(r.fragmentHint?1:0)+(s?e.endSN:Math.min(r.endSN,e.endSN))-e.startSN,h=e.startSN-r.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,u=r.fragmentHint?r.fragments.concat(r.fragmentHint):r.fragments;for(let d=n;d<=a;d++){const p=u[h+d];let g=l[d];if(s&&!g&&p&&(g=e.fragments[d]=p),p&&g){t(p,g,d,l);const y=p.relurl,x=g.relurl;if(y&&sy(y,x)){e.playlistParsingError=yh(`media sequence mismatch ${g.sn}:`,r,e,p,g);return}else if(p.cc!==g.cc){e.playlistParsingError=yh(`discontinuity sequence mismatch (${p.cc}!=${g.cc})`,r,e,p,g);return}}}}function yh(r,e,t,s,n){return new Error(`${r} ${n.url}
|
|
116
116
|
Playlist starting @${e.startSN}
|
|
117
117
|
${e.m3u8}
|
|
118
118
|
|
|
119
119
|
Playlist starting @${t.startSN}
|
|
120
|
-
${t.m3u8}`)}function ud(r,e,t=!0){const s=e.startSN+e.skippedSegments-r.startSN,n=r.fragments,a=s>=0;let h=0;if(a&&s<n.length)h=n[s].start;else if(a&&e.startSN===r.endSN+1)h=r.fragmentEnd;else if(a&&t)h=r.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)h=r.fragmentStart;else return;Ua(e,h)}function Ua(r,e){if(e){const t=r.fragments;for(let s=r.skippedSegments;s<t.length;s++)t[s].addStart(e);r.fragmentHint&&r.fragmentHint.addStart(e)}}function fd(r,e=1/0){let t=1e3*r.targetduration;if(r.updated){const s=r.fragments;if(s.length&&t*4>e){const a=s[s.length-1].duration*1e3;a<t&&(t=a)}}else t/=2;return Math.round(t)}function pd(r,e,t){if(!r)return null;let s=r.fragments[e-r.startSN];return s||(s=r.fragmentHint,s&&s.sn===e)?s:e<r.startSN&&t&&t.sn===e?t:null}function th(r,e,t){return r?gd(r.partList,e,t):null}function gd(r,e,t){if(r)for(let s=r.length;s--;){const n=r[s];if(n.index===t&&n.fragment.sn===e)return n}return null}function md(r){r.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(n=>{n.level=t,n.initSegment&&(n.initSegment.level=t)})})}function bs(r,e){for(let s=0,n=r.length;s<n;s++){var t;if(((t=r[s])==null?void 0:t.cc)===e)return r[s]}return null}function Rm(r,e){return!!(r&&e.startCC<r.endCC&&e.endCC>r.startCC)}function ih(r,e){if(r){const t=r.start+e;r.start=r.startPTS=t,r.endPTS=t+r.duration}}function yd(r,e){const t=e.fragments;for(let s=0,n=t.length;s<n;s++)ih(t[s],r);e.fragmentHint&&ih(e.fragmentHint,r),e.alignedSliding=!0}function Cm(r,e){r&&(xd(e,r),!e.alignedSliding&&r&&Wn(e,r),!e.alignedSliding&&r&&!e.skippedSegments&&ud(r,e,!1))}function xd(r,e){if(!Rm(e,r))return;const t=Math.min(e.endCC,r.endCC),s=bs(e.fragments,t),n=bs(r.fragments,t);if(!s||!n)return;pe.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const a=s.start-n.start;yd(a,r)}function Wn(r,e){if(!r.hasProgramDateTime||!e.hasProgramDateTime)return;const t=r.fragments,s=e.fragments;if(!t.length||!s.length)return;let n,a;const h=Math.min(e.endCC,r.endCC);e.startCC<h&&r.startCC<h&&(n=bs(s,h),a=bs(t,h)),(!n||!a)&&(n=s[Math.floor(s.length/2)],a=bs(t,n.cc)||t[Math.floor(t.length/2)]);const l=n.programDateTime,u=a.programDateTime;if(!l||!u)return;const d=(u-l)/1e3-(a.start-n.start);yd(d,r)}const Dm={toString:function(r){let e="";const t=r.length;for(let s=0;s<t;s++)e+=`[${r.start(s).toFixed(3)}-${r.end(s).toFixed(3)}]`;return e}},M={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class To extends rd{constructor(e,t,s,n,a){super(n,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=M.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.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:h,fragCurrent:l,media:u,mediaBuffer:d,state:p}=this,g=u?u.currentTime:0,y=ce.bufferInfo(d||u,g,h.maxBufferHole);if(this.log(`media seeking to ${K(g)?g.toFixed(3):g}, state: ${p}`),this.state===M.ENDED)this.resetLoadingState();else if(l){const v=h.maxFragLookUpTolerance,x=l.start-v,E=l.start+l.duration+v;if(!y.len||E<y.start||x>y.end){const o=g>E;(g<x||o)&&(o&&l.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),l.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(u){this.fragmentTracker.removeFragmentsInRange(g,1/0,this.playlistType,!0);const v=this.lastCurrentTime;if(g>v&&(this.lastCurrentTime=g),!this.loadingParts){const x=Math.max(y.end,g),E=this.shouldLoadParts(this.getLevelDetails(),x);E&&(this.log(`LL-Part loading ON after seeking to ${g.toFixed(2)} with buffer @${x.toFixed(2)}`),this.loadingParts=E)}}!this.hls.hasEnoughToStart&&!y.len&&(this.log(`setting startPosition to ${g} because of seek before start`),this.nextLoadPosition=this.startPosition=g),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=a,this.hls=e,this.fragmentLoader=new rm(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new vo(e.config)}registerListeners(){const{hls:e}=this;e.on(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(_.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(_.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===M.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=M.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 s=e.end||0,n=this.config.timelineOffset||0;if(s<=n)return!1;const a=e.nextStart;if(a&&a>n&&a<t.edge||this.media.currentTime<e.start)return!1;const l=t.partList;if(l!=null&&l.length){const d=l[l.length-1];return ce.isBuffered(this.media,d.start+d.duration/2)}const u=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(u)}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 s=this.media=this.mediaBuffer=t.media;s.removeEventListener("seeking",this.onMediaSeeking),s.removeEventListener("ended",this.onMediaEnded),s.addEventListener("seeking",this.onMediaSeeking),s.addEventListener("ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===M.STOPPED&&this.startLoad(n.startPosition)}onMediaDetaching(e,t){const s=!!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&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){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=M.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const n=a=>{const h=a.frag;if(this.fragContextChanged(h)){this.warn(`${h.type} sn: ${h.sn}${a.part?" part: "+a.part.index:""} of ${this.fragInfo(h,!1,a.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(h);return}h.stats.chunkCount++,this._handleFragmentLoadProgress(a)};this._doFragLoad(e,t,s,n).then(a=>{if(!a)return;const h=this.state,l=a.frag;if(this.fragContextChanged(l)){(h===M.FRAG_LOADING||!this.fragCurrent&&h===M.PARSING)&&(this.fragmentTracker.removeFragment(l),this.state=M.IDLE);return}"payload"in a&&(this.log(`Loaded ${l.type} sn: ${l.sn} of ${this.playlistLabel()} ${l.level}`),this.hls.trigger(_.FRAG_LOADED,a)),this._handleFragmentLoadComplete(a)}).catch(a=>{this.state===M.STOPPED||this.state===M.ERROR||(this.warn(`Frag error: ${(a==null?void 0:a.message)||a}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===ke.APPENDING){const a=e.type,h=this.getFwdBufferInfo(this.mediaBuffer,a),l=Math.max(e.duration,h?h.len:this.config.maxBufferLength),u=this.backtrackFragment;((u?e.sn-u.sn:0)===1||this.reduceMaxBufferLength(l,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===ke.PARTIAL&&s.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,s=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:s};this.hls.trigger(_.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const n=s==null?void 0:s.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:n}=this,{frag:a,payload:h}=s,l=a.decryptdata;if(h&&h.byteLength>0&&l!=null&&l.key&&l.iv&&Zi(l.method)){const u=self.performance.now();return this.decrypter.decrypt(new Uint8Array(h),l.key.buffer,l.iv.buffer,_o(l.method)).catch(d=>{throw n.trigger(_.ERROR,{type:Q.MEDIA_ERROR,details:P.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:a}),d}).then(d=>{const p=self.performance.now();return n.trigger(_.FRAG_DECRYPTED,{frag:a,payload:d,stats:{tstart:u,tdecrypt:p}}),s.payload=d,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===M.STOPPED||this.state===M.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==M.STOPPED&&(this.state=M.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.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 s=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:${s?Dm.toString(ce.getBuffered(s)):"(detached)"})`),Ne(e)){var n;if(e.type!==X.SUBTITLE){const h=e.elementaryStreams;if(!Object.keys(h).some(l=>!!h[l])){this.state=M.IDLE;return}}const a=(n=this.levels)==null?void 0:n[e.level];a!=null&&a.fragmentError&&(this.log(`Resetting level fragment error count of ${a.fragmentError} on frag buffered`),a.fragmentError=0)}this.state=M.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:n,partsLoaded:a}=e,h=!a||a.length===0||a.some(u=>!u),l=new So(s.level,s.sn,s.stats.chunkCount+1,0,n?n.index:-1,!h);t.flush(l)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,n){var a;this.fragCurrent=e;const h=t==null?void 0:t.details;if(!this.levels||!h)throw new Error(`frag load aborted, missing level${h?"":" detail"}s`);let l=null;e.encrypted&&!((a=e.decryptdata)!=null&&a.key)?(this.log(`Loading key for ${e.sn} of [${h.startSN}-${h.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=M.KEY_LOADING,this.fragCurrent=e,l=this.keyLoader.load(e).then(g=>{if(!this.fragContextChanged(g.frag))return this.hls.trigger(_.KEY_LOADED,g),this.state===M.KEY_LOADING&&(this.state=M.IDLE),g}),this.hls.trigger(_.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(l=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&h.encryptedFragments.length&&this.keyLoader.loadClear(e,h.encryptedFragments);const u=this.fragPrevious;if(Ne(e)&&(!u||e.sn!==u.sn)){const g=this.shouldLoadParts(t.details,e.end);g!==this.loadingParts&&(this.log(`LL-Part loading ${g?"ON":"OFF"} loading sn ${u==null?void 0:u.sn}->${e.sn}`),this.loadingParts=g)}if(s=Math.max(e.start,s||0),this.loadingParts&&Ne(e)){const g=h.partList;if(g&&n){s>e.end&&h.fragmentHint&&(e=h.fragmentHint);const y=this.getNextPart(g,e,s);if(y>-1){const v=g[y];e=this.fragCurrent=v.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${v.index} (${y}/${g.length-1}) of ${this.fragInfo(e,!1,v)}) cc: ${e.cc} [${h.startSN}-${h.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=v.start+v.duration,this.state=M.FRAG_LOADING;let x;return l?x=l.then(E=>!E||this.fragContextChanged(E.frag)?null:this.doFragPartsLoad(e,v,t,n)).catch(E=>this.handleFragLoadError(E)):x=this.doFragPartsLoad(e,v,t,n).catch(E=>this.handleFragLoadError(E)),this.hls.trigger(_.FRAG_LOADING,{frag:e,part:v,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):x}else if(!e.url||this.loadedEndOfParts(g,s))return Promise.resolve(null)}}if(Ne(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.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} ${h?"["+h.startSN+"-"+h.endSN+"]":""}, target: ${parseFloat(s.toFixed(3))}`),K(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=M.FRAG_LOADING;const d=this.config.progressive;let p;return d&&l?p=l.then(g=>!g||this.fragContextChanged(g==null?void 0:g.frag)?null:this.fragmentLoader.load(e,n)).catch(g=>this.handleFragLoadError(g)):p=Promise.all([this.fragmentLoader.load(e,d?n:void 0),l]).then(([g])=>(!d&&g&&n&&n(g),g)).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(_.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):p}doFragPartsLoad(e,t,s,n){return new Promise((a,h)=>{var l;const u=[],d=(l=s.details)==null?void 0:l.partList,p=g=>{this.fragmentLoader.loadPart(e,g,n).then(y=>{u[g.index]=y;const v=y.part;this.hls.trigger(_.FRAG_LOADED,y);const x=th(s.details,e.sn,g.index+1)||gd(d,e.sn,g.index+1);if(x)p(x);else return a({frag:e,part:v,partsLoaded:u})}).catch(h)};p(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===P.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(_.ERROR,t)}else this.hls.trigger(_.ERROR,{type:Q.OTHER_ERROR,details:P.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==M.PARSING){!this.fragCurrent&&this.state!==M.STOPPED&&this.state!==M.ERROR&&(this.state=M.IDLE);return}const{frag:s,part:n,level:a}=t,h=self.performance.now();s.stats.parsing.end=h,n&&(n.stats.parsing.end=h);const l=this.getLevelDetails(),d=l&&s.sn>l.endSN||this.shouldLoadParts(l,s.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(s,n,a,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e!=null&&e.partList){var s;const a=e.partList[0],h=a.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=h){var n;if((this.hls.hasEnoughToStart?((n=this.media)==null?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>a.start-a.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:n,sn:a,part:h}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${a} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const l=t[n],u=l.details,d=h>-1?th(u,a,h):null,p=d?d.fragment:pd(u,a,s);return p?(s&&s!==p&&(p.stats=s.stats),{frag:p,part:d,level:l}):null}bufferFragmentData(e,t,s,n,a){var h;if(!e||this.state!==M.PARSING)return;const{data1:l,data2:u}=e;let d=l;if(l&&u&&(d=ct(l,u)),!((h=d)!=null&&h.length))return;const p={type:e.type,frag:t,part:s,chunkMeta:n,parent:t.type,data:d};if(this.hls.trigger(_.BUFFER_APPENDING,p),e.dropped&&e.independent&&!s){if(a)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!ce.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,n=ce.bufferInfo(t,s,0),a=e.duration,h=Math.min(this.config.maxFragLookUpTolerance*2,a*.25),l=Math.max(Math.min(e.start-h,n.end-h),s+h);e.start-l>h&&this.flushMainBuffer(l,e.start)}getFwdBufferInfo(e,t){var s;const n=this.getLoadPosition();if(!K(n))return null;const h=this.lastCurrentTime>n||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,h)}getFwdBufferInfoAtPos(e,t,s,n){const a=ce.bufferInfo(e,t,n);if(a.len===0&&a.nextStart!==void 0){const h=this.fragmentTracker.getBufferedFrag(t,s);if(h&&(a.nextStart<=h.end||h.gap)){const l=Math.max(Math.min(a.nextStart,h.end)-t,n);return ce.bufferInfo(e,t,l)}}return a}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,n=Math.max(Math.min(e-t,s.maxBufferLength),t),a=Math.max(e-t*3,s.maxMaxBufferLength/2,n);return a>=n?(s.maxMaxBufferLength=a,this.warn(`Reduce max buffer length to ${a}s`),!0):!1}getAppendedFrag(e,t=X.MAIN){var s;const n=(s=this.fragmentTracker)==null?void 0:s.getAppendedFrag(e,t);return n&&"fragment"in n?n.fragment:n}getNextFragment(e,t){const s=t.fragments,n=s.length;if(!n)return null;const{config:a}=this,h=s[0].start,l=a.lowLatencyMode&&!!t.partList;let u=null;if(t.live){const g=a.initialLiveManifestSize;if(n<g)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${g})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<h){var d;l&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),u=this.getInitialLiveFragment(t,s);const y=this.hls.startPosition,v=this.hls.liveSyncPosition,x=u?(y!==-1&&y>=h?y:v)||u.start:e;this.log(`Setting startPosition to ${x} to match start frag at live edge. mainStart: ${y} liveSyncPosition: ${v} frag.start: ${(d=u)==null?void 0:d.start}`),this.startPosition=this.nextLoadPosition=x}}else e<=h&&(u=s[0]);if(!u){const g=this.loadingParts?t.partEnd:t.fragmentEnd;u=this.getFragmentAtPosition(e,g,t)}let p=this.filterReplacedPrimary(u,t);if(!p&&u){const g=u.sn-t.startSN;p=this.filterReplacedPrimary(s[g+1]||null,t)}return this.mapToInitFragWhenRequired(p)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===ke.OK||s===ke.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,n,a){let h=null;if(e.gap&&(h=this.getNextFragment(this.nextLoadPosition,t),h&&!h.gap&&s.nextStart)){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,n,0);if(l!==null&&s.len+l.len>=a){const u=h.sn;return this.loopSn!==u&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${u}`),this.loopSn=u),null}}return this.loopSn=void 0,h}get primaryPrefetch(){if(sh(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(sh(this.hls.config)&&e.type!==X.SUBTITLE){const s=this.hls.interstitialsManager,n=s==null?void 0:s.bufferingItem;if(n){const h=n.event;if(h){if(h.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 a=s==null?void 0:s.playerQueue;if(a)for(let h=a.length;h--;){const l=a[h].interstitial;if(l.appendInPlace&&e.start>=l.startTime&&e.end<=l.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,s){let n=-1,a=!1,h=!0;for(let l=0,u=e.length;l<u;l++){const d=e[l];if(h=h&&!d.independent,n>-1&&s<d.start)break;const p=d.loaded;p?n=-1:(a||d.independent||h)&&d.fragment===t&&(n=l),a=p}return n}loadedEndOfParts(e,t){const s=e[e.length-1];return s&&t>s.start&&s.loaded}getInitialLiveFragment(e,t){const s=this.fragPrevious;let n=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),n=Y0(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const a=s.sn+1;if(a>=e.startSN&&a<=e.endSN){const h=t[a-e.startSN];s.cc===h.cc&&(n=h,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=nd(t,s.cc),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const a=this.hls.liveSyncPosition;a!==null&&(n=this.getFragmentAtPosition(a,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,s){const{config:n}=this;let{fragPrevious:a}=this,{fragments:h,endSN:l}=s;const{fragmentHint:u}=s,{maxFragLookUpTolerance:d}=n,p=s.partList,g=!!(this.loadingParts&&p!=null&&p.length&&u);g&&u&&!this.bitrateTest&&p[p.length-1].fragment.sn===u.sn&&(h=h.concat(u),l=u.sn);let y;if(e<t){var v;const E=e<this.lastCurrentTime||e>t-d||(v=this.media)!=null&&v.paused||!this.startFragRequested?0:d;y=ki(a,h,e,E)}else y=h[h.length-1];if(y){const x=y.sn-s.startSN,E=this.fragmentTracker.getState(y);if((E===ke.OK||E===ke.PARTIAL&&y.gap)&&(a=y),a&&y.sn===a.sn&&(!g||p[0].fragment.sn>y.sn||!s.live&&!g)&&a&&y.level===a.level){const c=h[x+1];y.sn<l&&this.fragmentTracker.getState(c)!==ke.OK?y=c:y=null}}return y}alignPlaylists(e,t,s){const n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const a=e.fragmentStart,h=!t,l=e.alignedSliding&&K(a);if(h||!l&&!a){Cm(s,e);const u=e.fragmentStart;return this.log(`Live playlist sliding: ${u.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${n}`),u}return a}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const n=this.timelineOffset;if(s===-1){const a=this.startTimeOffset!==null,h=a?this.startTimeOffset:e.startTimeOffset;h!==null&&K(h)?(s=t+h,h<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${h} found in ${a?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+n}this.nextLoadPosition=s+n}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ne(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!==M.FRAG_LOADING_WAITING_RETRY)&&(this.state=M.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const x=this.getCurrentContext(t.chunkMeta);x&&(t.frag=x.frag)}const s=t.frag;if(!s||s.type!==e||!this.levels)return;if(this.fragContextChanged(s)){var n;this.warn(`Frag load error must match current frag to retry ${s.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}const a=t.details===P.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(s,!0);const h=t.errorAction,{action:l,flags:u,retryCount:d=0,retryConfig:p}=h||{},g=!!h&&!!p,y=g&&l===Ve.RetryRequest,v=g&&!h.resolved&&u===gt.MoveAllAlternatesMatchingHost;if(!y&&v&&Ne(s)&&!s.endList)this.resetFragmentErrors(e),this.treatAsGap(s),h.resolved=!0;else if((y||v)&&d<p.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const x=xo(p,d);this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${d+1}/${p.maxNumRetry} in ${x}ms`),h.resolved=!0,this.retryDate=self.performance.now()+x,this.state=M.FRAG_LOADING_WAITING_RETRY}else if(p&&h)if(this.resetFragmentErrors(e),d<p.maxNumRetry)!a&&l!==Ve.RemoveAlternatePermanently&&(h.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${d})`);return}else l===Ve.SendAlternateToPenaltyBox?this.state=M.WAITING_LEVEL:this.state=M.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===M.PARSING||this.state===M.PARSED){const t=e.frag,s=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,s),a=n&&n.len>.5;a&&this.reduceMaxBufferLength(n.len,(t==null?void 0:t.duration)||10);const h=!a;return h&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),h}return!1}resetFragmentErrors(e){e===X.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==M.STOPPED&&(this.state=M.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const n=ce.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,s),this.state===M.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==M.STOPPED&&(this.state=M.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,s,n){const a=s.details;if(!a){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((u,d)=>{const p=e.elementaryStreams[d];if(p){const g=p.endPTS-p.startPTS;if(g<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${g})`),u||!1;const y=n?0:dd(a,e,p.startPTS,p.endPTS,p.startDTS,p.endDTS);return this.hls.trigger(_.LEVEL_PTS_UPDATED,{details:a,level:s,drift:y,type:d,frag:e,start:p.startPTS,end:p.endPTS}),!0}return u},!1)){var l;if(s.fragmentError===0&&this.treatAsGap(e,s),((l=this.transmuxer)==null?void 0:l.error)===null){const u=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(u.message),this.hls.trigger(_.ERROR,{type:Q.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!1,error:u,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=M.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(_.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===X.MAIN?"level":"track"}fragInfo(e,t=!0,s){var n,a;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((n=t&&!s?e.startPTS:(s||e).start)!=null?n:NaN).toFixed(3)}-${((a=t&&!s?e.endPTS:(s||e).end)!=null?a:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.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 sh(r){return!!r.interstitialsController&&r.enableInterstitialPlayback!==!1}class vd{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=Pm(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function Pm(r,e){const t=new Uint8Array(e);let s=0;for(let n=0;n<r.length;n++){const a=r[n];t.set(a,s),s+=a.length}return t}var ea={exports:{}},nh;function km(){return nh||(nh=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function n(u,d,p){this.fn=u,this.context=d,this.once=p||!1}function a(u,d,p,g,y){if(typeof p!="function")throw new TypeError("The listener must be a function");var v=new n(p,g||u,y),x=t?t+d:d;return u._events[x]?u._events[x].fn?u._events[x]=[u._events[x],v]:u._events[x].push(v):(u._events[x]=v,u._eventsCount++),u}function h(u,d){--u._eventsCount===0?u._events=new s:delete u._events[d]}function l(){this._events=new s,this._eventsCount=0}l.prototype.eventNames=function(){var d=[],p,g;if(this._eventsCount===0)return d;for(g in p=this._events)e.call(p,g)&&d.push(t?g.slice(1):g);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(p)):d},l.prototype.listeners=function(d){var p=t?t+d:d,g=this._events[p];if(!g)return[];if(g.fn)return[g.fn];for(var y=0,v=g.length,x=new Array(v);y<v;y++)x[y]=g[y].fn;return x},l.prototype.listenerCount=function(d){var p=t?t+d:d,g=this._events[p];return g?g.fn?1:g.length:0},l.prototype.emit=function(d,p,g,y,v,x){var E=t?t+d:d;if(!this._events[E])return!1;var o=this._events[E],c=arguments.length,f,m;if(o.fn){switch(o.once&&this.removeListener(d,o.fn,void 0,!0),c){case 1:return o.fn.call(o.context),!0;case 2:return o.fn.call(o.context,p),!0;case 3:return o.fn.call(o.context,p,g),!0;case 4:return o.fn.call(o.context,p,g,y),!0;case 5:return o.fn.call(o.context,p,g,y,v),!0;case 6:return o.fn.call(o.context,p,g,y,v,x),!0}for(m=1,f=new Array(c-1);m<c;m++)f[m-1]=arguments[m];o.fn.apply(o.context,f)}else{var S=o.length,T;for(m=0;m<S;m++)switch(o[m].once&&this.removeListener(d,o[m].fn,void 0,!0),c){case 1:o[m].fn.call(o[m].context);break;case 2:o[m].fn.call(o[m].context,p);break;case 3:o[m].fn.call(o[m].context,p,g);break;case 4:o[m].fn.call(o[m].context,p,g,y);break;default:if(!f)for(T=1,f=new Array(c-1);T<c;T++)f[T-1]=arguments[T];o[m].fn.apply(o[m].context,f)}}return!0},l.prototype.on=function(d,p,g){return a(this,d,p,g,!1)},l.prototype.once=function(d,p,g){return a(this,d,p,g,!0)},l.prototype.removeListener=function(d,p,g,y){var v=t?t+d:d;if(!this._events[v])return this;if(!p)return h(this,v),this;var x=this._events[v];if(x.fn)x.fn===p&&(!y||x.once)&&(!g||x.context===g)&&h(this,v);else{for(var E=0,o=[],c=x.length;E<c;E++)(x[E].fn!==p||y&&!x[E].once||g&&x[E].context!==g)&&o.push(x[E]);o.length?this._events[v]=o.length===1?o[0]:o:h(this,v)}return this},l.prototype.removeAllListeners=function(d){var p;return d?(p=t?t+d:d,this._events[p]&&h(this,p)):(this._events=new s,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=t,l.EventEmitter=l,r.exports=l}(ea)),ea.exports}var Mm=km(),bo=l0(Mm);const Fs="1.6.2",as={};function Fm(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Um(){const r=as[Fs];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 as[Fs]=n,n}function Om(r){const e=as[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 as[r]=n,n}function Bm(r){const e=as[r||Fs];if(e&&e.clientCount--===1){const{worker:s,objectURL:n}=e;delete as[r||Fs],n&&self.URL.revokeObjectURL(n),s.terminate()}}function Sd(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 Ao(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 xr(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 Us(r,e){const t=e;let s=0;for(;Ao(r,e);){s+=10;const n=xr(r,e+6);s+=n,Sd(r,e+10)&&(s+=10),e+=s}if(s>0)return r.subarray(t,t+s)}function Nm(r,e,t,s){const n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],a=e[t+2],h=a>>2&15;if(h>12){const v=new Error(`invalid ADTS sampling index:${h}`);r.emit(_.ERROR,_.ERROR,{type:Q.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!0,error:v,reason:v.message});return}const l=(a>>6&3)+1,u=e[t+3]>>6&3|(a&1)<<2,d="mp4a.40."+l,p=n[h];let g=h;(l===5||l===29)&&(g-=3);const y=[l<<3|(g&14)>>1,(g&1)<<7|u<<3];return pe.log(`manifest codec:${s}, parsed codec:${d}, channels:${u}, rate:${p} (ADTS object type:${l} sampling index:${h})`),{config:y,samplerate:p,channelCount:u,codec:d,parsedCodec:d,manifestCodec:s}}function _d(r,e){return r[e]===255&&(r[e+1]&246)===240}function Ed(r,e){return r[e+1]&1?7:9}function Io(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function $m(r,e){return e+5<r.length}function jn(r,e){return e+1<r.length&&_d(r,e)}function Gm(r,e){return $m(r,e)&&_d(r,e)&&Io(r,e)<=r.length-e}function zm(r,e){if(jn(r,e)){const t=Ed(r,e);if(e+t>=r.length)return!1;const s=Io(r,e);if(s<=t)return!1;const n=e+s;return n===r.length||jn(r,n)}return!1}function Td(r,e,t,s,n){if(!r.samplerate){const a=Nm(e,t,s,n);if(!a)return;Te(r,a)}}function bd(r){return 1024*9e4/r}function Hm(r,e){const t=Ed(r,e);if(e+t<=r.length){const s=Io(r,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function Ad(r,e,t,s,n){const a=bd(r.samplerate),h=s+n*a,l=Hm(e,t);let u;if(l){const{frameLength:g,headerLength:y}=l,v=y+g,x=Math.max(0,t+v-e.length);x?(u=new Uint8Array(v-y),u.set(e.subarray(t+y,e.length),0)):u=e.subarray(t+y,t+v);const E={unit:u,pts:h};return x||r.samples.push(E),{sample:E,length:v,missing:x}}const d=e.length-t;return u=new Uint8Array(d),u.set(e.subarray(t,e.length),0),{sample:{unit:u,pts:h},length:d,missing:-1}}function Vm(r,e){return Ao(r,e)&&xr(r,e+6)+10<=r.length-e}function Km(r){if(r.size<2)return;const e=st(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}}function Ym(r){if(r.size<2)return;if(r.type==="TXXX"){let t=1;const s=st(r.data.subarray(t),!0);t+=s.length+1;const n=st(r.data.subarray(t));return{key:r.type,info:s,data:n}}const e=st(r.data.subarray(1));return{key:r.type,info:"",data:e}}function Wm(r){if(r.type==="WXXX"){if(r.size<2)return;let t=1;const s=st(r.data.subarray(t),!0);t+=s.length+1;const n=st(r.data.subarray(t));return{key:r.type,info:s,data:n}}const e=st(r.data);return{key:r.type,info:"",data:e}}function jm(r){return btoa(String.fromCharCode(...r))}function Id(r,e){if(r<0)return-Id(-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 qm(r,e){const t=new URL(r),s=new URL(e);if(t.origin!==s.origin)return r;const n=t.pathname.split("/").slice(1),a=s.pathname.split("/").slice(1,-1);for(;n[0]===a[0];)n.shift(),a.shift();for(;a.length;)a.shift(),n.unshift("..");return n.join("/")}function Xm(){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 a=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(n=="x"?a:a&3|8).toString(16)})}}}function Qm(r){return r instanceof ArrayBuffer?r:r.byteOffset==0&&r.byteLength==r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer}function ta(r,e=0,t=1/0){return Zm(r,e,t,Uint8Array)}function Zm(r,e,t,s){const n=Jm(r);let a=1;"BYTES_PER_ELEMENT"in s&&(a=s.BYTES_PER_ELEMENT);const h=ey(r)?r.byteOffset:0,l=(h+r.byteLength)/a,u=(h+e)/a,d=Math.floor(Math.max(0,Math.min(u,l))),p=Math.floor(Math.min(d+Math.max(t,0),l));return new s(n,d,p-d)}function Jm(r){return r instanceof ArrayBuffer?r:r.buffer}function ey(r){return r&&r.buffer instanceof ArrayBuffer&&r.byteLength!==void 0&&r.byteOffset!==void 0}function ty(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 s=r.data.subarray(1).indexOf(0);if(s===-1)return;const n=st(ta(r.data,1,s)),a=r.data[2+s],h=r.data.subarray(3+s).indexOf(0);if(h===-1)return;const l=st(ta(r.data,3+s,h));let u;return n==="-->"?u=st(ta(r.data,4+s+h)):u=Qm(r.data.subarray(4+s+h)),e.mimeType=n,e.pictureType=a,e.description=l,e.data=u,e}function iy(r){return r.type==="PRIV"?Km(r):r.type[0]==="W"?Wm(r):r.type==="APIC"?ty(r):Ym(r)}function sy(r){const e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=xr(r,4),s=10;return{type:e,size:t,data:r.subarray(s,s+t)}}const cn=10,ny=10;function wd(r){let e=0;const t=[];for(;Ao(r,e);){const s=xr(r,e+6);r[e+5]>>6&1&&(e+=cn),e+=cn;const n=e+s;for(;e+ny<n;){const a=sy(r.subarray(e)),h=iy(a);h&&t.push(h),e+=a.size+cn}Sd(r,e)&&(e+=cn)}return t}function Ld(r){return r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp"}function ry(r){if(r.data.byteLength===8){const e=new Uint8Array(r.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function wo(r){const e=wd(r);for(let t=0;t<e.length;t++){const s=e[t];if(Ld(s))return ry(s)}}let it=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 Tt(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Lo{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,s,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,s){}demux(e,t){this.cachedData&&(e=ct(this.cachedData,e),this.cachedData=null);let s=Us(e,0),n=s?s.length:0,a;const h=this._audioTrack,l=this._id3Track,u=s?wo(s):void 0,d=e.length;for((this.basePTS===null||this.frameIndex===0&&K(u))&&(this.basePTS=ay(u,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&l.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:it.audioId3,duration:Number.POSITIVE_INFINITY});n<d;){if(this.canParse(e,n)){const p=this.appendFrame(h,e,n);p?(this.frameIndex++,this.lastPTS=p.sample.pts,n+=p.length,a=n):n=d}else Vm(e,n)?(s=Us(e,n),l.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:it.audioId3,duration:Number.POSITIVE_INFINITY}),n+=s.length,a=n):n++;if(n===d&&a!==d){const p=e.slice(a);this.cachedData?this.cachedData=ct(this.cachedData,p):this.cachedData=p}}return{audioTrack:h,videoTrack:Tt(),id3Track:l,textTrack:Tt()}}demuxSampleAes(e,t,s){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:Tt(),id3Track:this._id3Track,textTrack:Tt()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const ay=(r,e,t)=>{if(K(r))return r*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let dn=null;const oy=[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],ly=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],hy=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],cy=[0,1,1,4];function Rd(r,e,t,s,n){if(t+24>e.length)return;const a=Cd(e,t);if(a&&t+a.frameLength<=e.length){const h=a.samplesPerFrame*9e4/a.sampleRate,l=s+n*h,u={unit:e.subarray(t,t+a.frameLength),pts:l,dts:l};return r.config=[],r.channelCount=a.channelCount,r.samplerate=a.sampleRate,r.samples.push(u),{sample:u,length:a.frameLength,missing:0}}}function Cd(r,e){const t=r[e+1]>>3&3,s=r[e+1]>>1&3,n=r[e+2]>>4&15,a=r[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&a!==3){const h=r[e+2]>>1&1,l=r[e+3]>>6,u=t===3?3-s:s===3?3:4,d=oy[u*14+n-1]*1e3,g=ly[(t===3?0:t===2?1:2)*3+a],y=l===3?1:2,v=hy[t][s],x=cy[s],E=v*8*x,o=Math.floor(v*d/g+h)*x;if(dn===null){const m=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);dn=m?parseInt(m[1]):0}return!!dn&&dn<=87&&s===2&&d>=224e3&&l===0&&(r[e+3]=r[e+3]|128),{sampleRate:g,channelCount:y,frameLength:o,samplesPerFrame:E}}}function Ro(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function Dd(r,e){return e+1<r.length&&Ro(r,e)}function dy(r,e){return Ro(r,e)&&4<=r.length-e}function Pd(r,e){if(e+1<r.length&&Ro(r,e)){const s=Cd(r,e);let n=4;s!=null&&s.frameLength&&(n=s.frameLength);const a=e+n;return a===r.length||Dd(r,a)}return!1}class uy extends Lo{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,n){super.resetInitSegment(e,t,s,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 s=Us(e,0);let n=(s==null?void 0:s.length)||0;if(Pd(e,n))return!1;for(let a=e.length;n<a;n++)if(zm(e,n))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Gm(e,t)}appendFrame(e,t,s){Td(e,this.observer,t,s,e.manifestCodec);const n=Ad(e,t,s,this.basePTS,this.frameIndex);if(n&&n.missing===0)return n}}const kd=(r,e)=>{let t=0,s=5;e+=s;const n=new Uint32Array(1),a=new Uint32Array(1),h=new Uint8Array(1);for(;s>0;){h[0]=r[e];const l=Math.min(s,8),u=8-l;a[0]=4278190080>>>24+u<<u,n[0]=(h[0]&a[0])>>u,t=t?t<<l|n[0]:n[0],e+=1,s-=l}return t};class fy extends Lo{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,n){super.resetInitSegment(e,t,s,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,s){const n=Md(e,t,s,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=Us(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&wo(t)!==void 0&&kd(e,s)<16}}function Md(r,e,t,s,n){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const a=e[t+4]>>6;if(a>=3)return-1;const l=[48e3,44100,32e3][a],u=e[t+4]&63,p=[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][u*3+a]*2;if(t+p>e.length)return-1;const g=e[t+6]>>5;let y=0;g===2?y+=2:(g&1&&g!==1&&(y+=2),g&4&&(y+=2));const v=(e[t+6]<<8|e[t+7])>>12-y&1,E=[2,1,2,3,3,4,4,5][g]+v,o=e[t+5]>>3,c=e[t+5]&7,f=new Uint8Array([a<<6|o<<1|c>>2,(c&3)<<6|g<<3|v<<2|u>>4,u<<4&224]),m=1536/l*9e4,S=s+n*m,T=e.subarray(t,t+p);return r.config=f,r.channelCount=E,r.samplerate=l,r.samples.push({unit:T,pts:S}),p}class py extends Lo{resetInitSegment(e,t,s,n){super.resetInitSegment(e,t,s,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=Us(e,0);let s=(t==null?void 0:t.length)||0;if(t&&e[s]===11&&e[s+1]===119&&wo(t)!==void 0&&kd(e,s)<=16)return!1;for(let n=e.length;s<n;s++)if(Pd(e,s))return pe.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return dy(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return Rd(e,t,s,this.basePTS,this.frameIndex)}}const gy=/\/emsg[-/]ID3/i;class my{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,s,n){const a=this.videoTrack=Tt("video",1),h=this.audioTrack=Tt("audio",1),l=this.txtTrack=Tt("text",1);if(this.id3Track=Tt("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const u=Wc(e);if(u.video){const{id:d,timescale:p,codec:g,supplemental:y}=u.video;a.id=d,a.timescale=l.timescale=p,a.codec=g,a.supplemental=y}if(u.audio){const{id:d,timescale:p,codec:g}=u.audio;h.id=d,h.timescale=p,h.codec=g}l.id=Vc.text,a.sampleDuration=0,a.duration=h.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return f0(e)}demux(e,t){this.timeOffset=t;let s=e;const n=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=ct(this.remainderData,e));const l=_0(s);this.remainderData=l.remainder,n.samples=l.valid||new Uint8Array}else n.samples=s;const h=this.extractID3Track(n,t);return a.samples=Al(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:h,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);return s.samples=Al(e,t),{videoTrack:t,audioTrack:Tt(),id3Track:n,textTrack:Tt()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const n=oe(e.samples,["emsg"]);n&&n.forEach(a=>{const h=T0(a);if(gy.test(h.schemeIdUri)){const l=rh(h,t);let u=h.eventDuration===4294967295?Number.POSITIVE_INFINITY:h.eventDuration/h.timeScale;u<=.001&&(u=Number.POSITIVE_INFINITY);const d=h.payload;s.samples.push({data:d,len:d.byteLength,dts:l,pts:l,type:it.emsg,duration:u})}else if(this.config.enableEmsgKLVMetadata&&h.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const l=rh(h,t);s.samples.push({data:h.payload,len:h.payload.byteLength,dts:l,pts:l,type:it.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){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 rh(r,e){return K(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale}class yy{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new vo(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,gi.cbc)}decryptAacSample(e,t,s){const n=e[t].unit;if(n.length<=16)return;const a=n.subarray(16,n.length-n.length%16),h=a.buffer.slice(a.byteOffset,a.byteOffset+a.length);this.decryptBuffer(h).then(l=>{const u=new Uint8Array(l);n.set(u,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)})}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let n=0;for(let a=32;a<e.length-16;a+=160,n+=16)s.set(e.subarray(a,a+16),n);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let n=0;for(let a=32;a<e.length-16;a+=160,n+=16)e.set(s.subarray(n,n+16),a);return e}decryptAvcSample(e,t,s,n,a){const h=qc(a.data),l=this.getAvcEncryptedData(h);this.decryptBuffer(l.buffer).then(u=>{a.data=this.getAvcDecryptedUnit(h,u),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,n)})}decryptAvcSamples(e,t,s,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){n();return}const a=e[t].units;for(;!(s>=a.length);s++){const h=a[s];if(!(h.data.length<=48||h.type!==1&&h.type!==5)&&(this.decryptAvcSample(e,t,s,n,h),!this.decrypter.isSync()))return}}}}class Fd{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,n;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const a=s.units;n=a[a.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,n=s.length;if(n){const a=s[n-1];e.pts=a.pts,e.dts=a.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const n=t.byteLength;let a=e.naluState||0;const h=a,l=[];let u=0,d,p,g,y=-1,v=0;for(a===-1&&(y=0,v=this.getNALuType(t,0),a=0,u=1);u<n;){if(d=t[u++],!a){a=d?0:1;continue}if(a===1){a=d?0:2;continue}if(!d)a=3;else if(d===1){if(p=u-a-1,y>=0){const x={data:t.subarray(y,p),type:v};l.push(x)}else{const x=this.getLastNalUnit(e.samples);x&&(h&&u<=4-h&&x.state&&(x.data=x.data.subarray(0,x.data.byteLength-h)),p>0&&(x.data=ct(x.data,t.subarray(0,p)),x.state=0))}u<n?(g=this.getNALuType(t,u),y=u,v=g,a=0):a=-1}else a=0}if(y>=0&&a>=0){const x={data:t.subarray(y,n),type:v,state:a};l.push(x)}if(l.length===0){const x=this.getLastNalUnit(e.samples);x&&(x.data=ct(x.data,t))}return e.naluState=a,l}}class As{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,s=e.byteLength-t,n=new Uint8Array(4),a=Math.min(4,t);if(a===0)throw new Error("no bytes available");n.set(e.subarray(s,s+a)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=a*8,this.bytesAvailable-=a}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 s=this.word>>>32-t;if(e>32&&pe.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?s<<t|this.readBits(t):s}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 ah extends Fd{parsePES(e,t,s,n){const a=this.parseNALu(e,s.data,n);let h=this.VideoSample,l,u=!1;s.data=null,h&&a.length&&!e.audFound&&(this.pushAccessUnit(h,e),h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.forEach(d=>{var p,g;switch(d.type){case 1:{let E=!1;l=!0;const o=d.data;if(u&&o.length>4){const c=this.readSliceType(o);(c===2||c===4||c===7||c===9)&&(E=!0)}if(E){var y;(y=h)!=null&&y.frame&&!h.key&&(this.pushAccessUnit(h,e),h=this.VideoSample=null)}h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.frame=!0,h.key=E;break}case 5:l=!0,(p=h)!=null&&p.frame&&!h.key&&(this.pushAccessUnit(h,e),h=this.VideoSample=null),h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.key=!0,h.frame=!0;break;case 6:{l=!0,mo(d.data,1,s.pts,t.samples);break}case 7:{var v,x;l=!0,u=!0;const E=d.data,o=this.readSPS(E);if(!e.sps||e.width!==o.width||e.height!==o.height||((v=e.pixelRatio)==null?void 0:v[0])!==o.pixelRatio[0]||((x=e.pixelRatio)==null?void 0:x[1])!==o.pixelRatio[1]){e.width=o.width,e.height=o.height,e.pixelRatio=o.pixelRatio,e.sps=[E];const c=E.subarray(1,4);let f="avc1.";for(let m=0;m<3;m++){let S=c[m].toString(16);S.length<2&&(S="0"+S),f+=S}e.codec=f}break}case 8:l=!0,e.pps=[d.data];break;case 9:l=!0,e.audFound=!0,(g=h)!=null&&g.frame&&(this.pushAccessUnit(h,e),h=null),h||(h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:l=!0;break;default:l=!1;break}h&&l&&h.units.push(d)}),n&&h&&(this.pushAccessUnit(h,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new As(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,n=8,a;for(let h=0;h<e;h++)n!==0&&(a=t.readEG(),n=(s+a+256)%256),s=n===0?s:n}readSPS(e){const t=new As(e);let s=0,n=0,a=0,h=0,l,u,d;const p=t.readUByte.bind(t),g=t.readBits.bind(t),y=t.readUEG.bind(t),v=t.readBoolean.bind(t),x=t.skipBits.bind(t),E=t.skipEG.bind(t),o=t.skipUEG.bind(t),c=this.skipScalingList.bind(this);p();const f=p();if(g(5),x(3),p(),o(),f===100||f===110||f===122||f===244||f===44||f===83||f===86||f===118||f===128){const I=y();if(I===3&&x(1),o(),o(),x(1),v())for(u=I!==3?8:12,d=0;d<u;d++)v()&&(d<6?c(16,t):c(64,t))}o();const m=y();if(m===0)y();else if(m===1)for(x(1),E(),E(),l=y(),d=0;d<l;d++)E();o(),x(1);const S=y(),T=y(),b=g(1);b===0&&x(1),x(1),v()&&(s=y(),n=y(),a=y(),h=y());let A=[1,1];if(v()&&v())switch(p()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:{A=[p()<<8|p(),p()<<8|p()];break}}return{width:Math.ceil((S+1)*16-s*2-n*2),height:(2-b)*(T+1)*16-(b?2:4)*(a+h),pixelRatio:A}}}class oh extends Fd{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,n){const a=this.parseNALu(e,s.data,n);let h=this.VideoSample,l,u=!1;s.data=null,h&&a.length&&!e.audFound&&(this.pushAccessUnit(h,e),h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.forEach(d=>{var p,g;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:h||(h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),h.frame=!0,l=!0;break;case 16:case 17:case 18:case 21:if(l=!0,u){var y;(y=h)!=null&&y.frame&&!h.key&&(this.pushAccessUnit(h,e),h=this.VideoSample=null)}h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.key=!0,h.frame=!0;break;case 19:case 20:l=!0,(p=h)!=null&&p.frame&&!h.key&&(this.pushAccessUnit(h,e),h=this.VideoSample=null),h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.key=!0,h.frame=!0;break;case 39:l=!0,mo(d.data,2,s.pts,t.samples);break;case 32:l=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Te(e.params,this.readVPS(d.data)),this.initVPS=d.data),e.vps=[d.data];break;case 33:if(l=!0,u=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],d.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const v=this.readSPS(d.data);e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.codec=v.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const x in v.params)e.params[x]=v.params[x]}this.pushParameterSet(e.sps,d.data,e.vps),h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.key=!0;break;case 34:if(l=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const v=this.readPPS(d.data);for(const x in v)e.params[x]=v[x]}this.pushParameterSet(e.pps,d.data,e.vps)}break;case 35:l=!0,e.audFound=!0,(g=h)!=null&&g.frame&&(this.pushAccessUnit(h,e),h=null),h||(h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:l=!1;break}h&&l&&h.units.push(d)}),n&&h&&(this.pushAccessUnit(h,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let n=0;n<e.byteLength;n++)n>=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[s]=e[n],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new As(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:n}}readSPS(e){const t=new As(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const n=t.readBits(2),a=t.readBoolean(),h=t.readBits(5),l=t.readUByte(),u=t.readUByte(),d=t.readUByte(),p=t.readUByte(),g=t.readUByte(),y=t.readUByte(),v=t.readUByte(),x=t.readUByte(),E=t.readUByte(),o=t.readUByte(),c=t.readUByte(),f=[],m=[];for(let ge=0;ge<s;ge++)f.push(t.readBoolean()),m.push(t.readBoolean());if(s>0)for(let ge=s;ge<8;ge++)t.readBits(2);for(let ge=0;ge<s;ge++)f[ge]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),m[ge]&&t.readUByte();t.readUEG();const S=t.readUEG();S==3&&t.skipBits(1);const T=t.readUEG(),b=t.readUEG(),A=t.readBoolean();let I=0,L=0,w=0,C=0;A&&(I+=t.readUEG(),L+=t.readUEG(),w+=t.readUEG(),C+=t.readUEG());const k=t.readUEG(),U=t.readUEG(),G=t.readUEG(),$=t.readBoolean();for(let ge=$?0:s;ge<=s;ge++)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 He=0;He<4;He++)for(let at=0;at<(He===3?2:6);at++)if(!t.readBoolean())t.readUEG();else{const ut=Math.min(64,1<<4+(He<<1));He>1&&t.readEG();for(let Bi=0;Bi<ut;Bi++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const Y=t.readUEG();let F=0;for(let ge=0;ge<Y;ge++){let He=!1;if(ge!==0&&(He=t.readBoolean()),He){ge===Y&&t.readUEG(),t.readBoolean(),t.readUEG();let at=0;for(let Si=0;Si<=F;Si++){const ut=t.readBoolean();let Bi=!1;ut||(Bi=t.readBoolean()),(ut||Bi)&&at++}F=at}else{const at=t.readUEG(),Si=t.readUEG();F=at+Si;for(let ut=0;ut<at;ut++)t.readUEG(),t.readBoolean();for(let ut=0;ut<Si;ut++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const ge=t.readUEG();for(let He=0;He<ge;He++){for(let at=0;at<G+4;at++)t.readBits(1);t.readBits(1)}}let te=0,ee=1,se=1,he=!0,W=1,me=0;t.readBoolean(),t.readBoolean();let De=!1;if(t.readBoolean()){if(t.readBoolean()){const _i=t.readUByte(),Oo=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Xs=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];_i>0&&_i<16?(ee=Oo[_i-1],se=Xs[_i-1]):_i===255&&(ee=t.readBits(16),se=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(),De=t.readBoolean(),De&&(I+=t.readUEG(),L+=t.readUEG(),w+=t.readUEG(),C+=t.readUEG()),t.readBoolean()&&(W=t.readBits(32),me=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Xs=t.readBoolean(),Bo=t.readBoolean();let ps=!1;(Xs||Bo)&&(ps=t.readBoolean(),ps&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),ps&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let No=0;No<=s;No++){he=t.readBoolean();const xu=he||t.readBoolean();let $o=!1;xu?t.readEG():$o=t.readBoolean();const Go=$o?1:t.readUEG()+1;if(Xs)for(let gs=0;gs<Go;gs++)t.readUEG(),t.readUEG(),ps&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Bo)for(let gs=0;gs<Go;gs++)t.readUEG(),t.readUEG(),ps&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),te=t.readUEG())}let ei=T,Uo=b;if(A||De){let ge=1,He=1;S===1?ge=He=2:S==2&&(ge=2),ei=T-ge*L-ge*I,Uo=b-He*C-He*w}const mu=n?["A","B","C"][n]:"",yu=l<<24|u<<16|d<<8|p;let vr=0;for(let ge=0;ge<32;ge++)vr=(vr|(yu>>ge&1)<<31-ge)>>>0;let Sr=vr.toString(16);return h===1&&Sr==="2"&&(Sr="6"),{codecString:`hvc1.${mu}${h}.${Sr}.${a?"H":"L"}${c}.B0`,params:{general_tier_flag:a,general_profile_idc:h,general_profile_space:n,general_profile_compatibility_flags:[l,u,d,p],general_constraint_indicator_flags:[g,y,v,x,E,o],general_level_idc:c,bit_depth:k+8,bit_depth_luma_minus8:k,bit_depth_chroma_minus8:U,min_spatial_segmentation_idc:te,chroma_format_idc:S,frame_rate:{fixed:he,fps:me/W}},width:ei,height:Uo,pixelRatio:[ee,se]}}readPPS(e){const t=new As(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(),a=t.readBoolean();let h=1;return a&&n?h=0:a?h=3:n&&(h=2),{parallelismType:h}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Oe=188;class ri{constructor(e,t,s,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=s,this.logger=n,this.videoParser=null}static probe(e,t){const s=ri.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(Oe*5,t-Oe)+1,n=0;for(;n<s;){let a=!1,h=-1,l=0;for(let u=n;u<t;u+=Oe)if(e[u]===71&&(t-u===Oe||e[u+Oe]===71)){if(l++,h===-1&&(h=u,h!==0&&(s=Math.min(h+Oe*99,e.length-Oe)+1)),a||(a=Oa(e,u)===0),a&&l>1&&(h===0&&l>2||u+Oe>s))return h}else{if(l)return-1;break}n++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Vc[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=ri.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=ri.createTrack("audio",n),this._id3Track=ri.createTrack("id3"),this._txtTrack=ri.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,n=!1){s||(this.sampleAes=null);let a;const h=this._videoTrack,l=this._audioTrack,u=this._id3Track,d=this._txtTrack;let p=h.pid,g=h.pesData,y=l.pid,v=u.pid,x=l.pesData,E=u.pesData,o=null,c=this.pmtParsed,f=this._pmtId,m=e.length;if(this.remainderData&&(e=ct(this.remainderData,e),m=e.length,this.remainderData=null),m<Oe&&!n)return this.remainderData=e,{audioTrack:l,videoTrack:h,id3Track:u,textTrack:d};const S=Math.max(0,ri.syncOffset(e));m-=(m-S)%Oe,m<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,m,e.buffer.byteLength-m));let T=0;for(let A=S;A<m;A+=Oe)if(e[A]===71){const I=!!(e[A+1]&64),L=Oa(e,A),w=(e[A+3]&48)>>4;let C;if(w>1){if(C=A+5+e[A+4],C===A+Oe)continue}else C=A+4;switch(L){case p:if(I){if(g&&(a=Gi(g,this.logger))){if(this.videoParser===null)switch(h.segmentCodec){case"avc":this.videoParser=new ah;break;case"hevc":this.videoParser=new oh;break}this.videoParser!==null&&this.videoParser.parsePES(h,d,a,!1)}g={data:[],size:0}}g&&(g.data.push(e.subarray(C,A+Oe)),g.size+=A+Oe-C);break;case y:if(I){if(x&&(a=Gi(x,this.logger)))switch(l.segmentCodec){case"aac":this.parseAACPES(l,a);break;case"mp3":this.parseMPEGPES(l,a);break;case"ac3":this.parseAC3PES(l,a);break}x={data:[],size:0}}x&&(x.data.push(e.subarray(C,A+Oe)),x.size+=A+Oe-C);break;case v:I&&(E&&(a=Gi(E,this.logger))&&this.parseID3PES(u,a),E={data:[],size:0}),E&&(E.data.push(e.subarray(C,A+Oe)),E.size+=A+Oe-C);break;case 0:I&&(C+=e[C]+1),f=this._pmtId=xy(e,C);break;case f:{I&&(C+=e[C]+1);const k=vy(e,C,this.typeSupported,s,this.observer,this.logger);p=k.videoPid,p>0&&(h.pid=p,h.segmentCodec=k.segmentVideoCodec),y=k.audioPid,y>0&&(l.pid=y,l.segmentCodec=k.segmentAudioCodec),v=k.id3Pid,v>0&&(u.pid=v),o!==null&&!c&&(this.logger.warn(`MPEG-TS PMT found at ${A} after unknown PID '${o}'. Backtracking to sync byte @${S} to parse all TS packets.`),o=null,A=S-188),c=this.pmtParsed=!0;break}case 17:case 8191:break;default:o=L;break}}else T++;T>0&&Ba(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),h.pesData=g,l.pesData=x,u.pesData=E;const b={audioTrack:l,videoTrack:h,id3Track:u,textTrack:d};return n&&this.extractRemainingSamples(b),b}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:s,id3Track:n,textTrack:a}=e,h=s.pesData,l=t.pesData,u=n.pesData;let d;if(h&&(d=Gi(h,this.logger))){if(this.videoParser===null)switch(s.segmentCodec){case"avc":this.videoParser=new ah;break;case"hevc":this.videoParser=new oh;break}this.videoParser!==null&&(this.videoParser.parsePES(s,a,d,!0),s.pesData=null)}else s.pesData=h;if(l&&(d=Gi(l,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,d);break;case"mp3":this.parseMPEGPES(t,d);break;case"ac3":this.parseAC3PES(t,d);break}t.pesData=null}else l!=null&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=l;u&&(d=Gi(u,this.logger))?(this.parseID3PES(n,d),n.pesData=null):n.pesData=u}demuxSampleAes(e,t,s){const n=this.demux(e,s,!0,!this.config.progressive),a=this.sampleAes=new yy(this.observer,this.config,t);return this.decrypt(n,a)}decrypt(e,t){return new Promise(s=>{const{audioTrack:n,videoTrack:a}=e;n.samples&&n.segmentCodec==="aac"?t.decryptAacSamples(n.samples,0,()=>{a.samples?t.decryptAvcSamples(a.samples,0,0,()=>{s(e)}):s(e)}):a.samples&&t.decryptAvcSamples(a.samples,0,0,()=>{s(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 s=0;const n=this.aacOverFlow;let a=t.data;if(n){this.aacOverFlow=null;const g=n.missing,y=n.sample.unit.byteLength;if(g===-1)a=ct(n.sample.unit,a);else{const v=y-g;n.sample.unit.set(a.subarray(0,g),v),e.samples.push(n.sample),s=n.missing}}let h,l;for(h=s,l=a.length;h<l-1&&!jn(a,h);h++);if(h!==s){let g;const y=h<l-1;if(y?g=`AAC PES did not start with ADTS header,offset:${h}`:g="No ADTS header found in AAC PES",Ba(this.observer,new Error(g),y,this.logger),!y)return}Td(e,this.observer,a,h,this.audioCodec);let u;if(t.pts!==void 0)u=t.pts;else if(n){const g=bd(e.samplerate);u=n.sample.pts+g}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let d=0,p;for(;h<l;)if(p=Ad(e,a,h,u,d),h+=p.length,p.missing){this.aacOverFlow=p;break}else for(d++;h<l-1&&!jn(a,h);h++);}parseMPEGPES(e,t){const s=t.data,n=s.length;let a=0,h=0;const l=t.pts;if(l===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;h<n;)if(Dd(s,h)){const u=Rd(e,s,h,l,a);if(u)h+=u.length,a++;else break}else h++}parseAC3PES(e,t){{const s=t.data,n=t.pts;if(n===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const a=s.length;let h=0,l=0,u;for(;l<a&&(u=Md(e,s,l,n,h++))>0;)l+=u}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=Te({},t,{type:this._videoTrack?it.emsg:it.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Oa(r,e){return((r[e+1]&31)<<8)+r[e+2]}function xy(r,e){return(r[e+10]&31)<<8|r[e+11]}function vy(r,e,t,s,n,a){const h={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},l=(r[e+1]&15)<<8|r[e+2],u=e+3+l-4,d=(r[e+10]&15)<<8|r[e+11];for(e+=12+d;e<u;){const p=Oa(r,e),g=(r[e+3]&15)<<8|r[e+4];switch(r[e]){case 207:if(!s){ia("ADTS AAC",a);break}case 15:h.audioPid===-1&&(h.audioPid=p);break;case 21:h.id3Pid===-1&&(h.id3Pid=p);break;case 219:if(!s){ia("H.264",a);break}case 27:h.videoPid===-1&&(h.videoPid=p);break;case 3:case 4:!t.mpeg&&!t.mp3?a.log("MPEG audio found, not supported in this browser"):h.audioPid===-1&&(h.audioPid=p,h.segmentAudioCodec="mp3");break;case 193:if(!s){ia("AC-3",a);break}case 129:t.ac3?h.audioPid===-1&&(h.audioPid=p,h.segmentAudioCodec="ac3"):a.log("AC-3 audio found, not supported in this browser");break;case 6:if(h.audioPid===-1&&g>0){let y=e+5,v=g;for(;v>2;){switch(r[y]){case 106:t.ac3!==!0?a.log("AC-3 audio found, not supported in this browser for now"):(h.audioPid=p,h.segmentAudioCodec="ac3");break}const E=r[y+1]+2;y+=E,v-=E}}break;case 194:case 135:return Ba(n,new Error("Unsupported EC-3 in M2TS found"),void 0,a),h;case 36:h.videoPid===-1&&(h.videoPid=p,h.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"));break}e+=g+5}return h}function Ba(r,e,t,s){s.warn(`parsing error: ${e.message}`),r.emit(_.ERROR,_.ERROR,{type:Q.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function ia(r,e){e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function Gi(r,e){let t=0,s,n,a,h,l;const u=r.data;if(!r||r.size===0)return null;for(;u[0].length<19&&u.length>1;)u[0]=ct(u[0],u[1]),u.splice(1,1);if(s=u[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(n=(s[4]<<8)+s[5],n&&n>r.size-6)return null;const p=s[7];p&192&&(h=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,p&64?(l=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,h-l>60*9e4&&(e.warn(`${Math.round((h-l)/9e4)}s delta between PTS and DTS, align them`),h=l)):l=h),a=s[8];let g=a+9;if(r.size<=g)return null;r.size-=g;const y=new Uint8Array(r.size);for(let v=0,x=u.length;v<x;v++){s=u[v];let E=s.byteLength;if(g)if(g>E){g-=E;continue}else s=s.subarray(g),E-=g,g=0;y.set(s,t),t+=E}return n&&(n-=a+3),{data:y,pts:h,dts:l,len:n}}return null}class Sy{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 ti=Math.pow(2,32)-1;class D{static init(){D.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 D.types)D.types.hasOwnProperty(e)&&(D.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]),s=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]);D.HDLR_TYPES={video:t,audio:s};const n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),a=new Uint8Array([0,0,0,0,0,0,0,0]);D.STTS=D.STSC=D.STCO=a,D.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),D.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),D.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),D.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const h=new Uint8Array([105,115,111,109]),l=new Uint8Array([97,118,99,49]),u=new Uint8Array([0,0,0,1]);D.FTYP=D.box(D.types.ftyp,h,u,h,l),D.DINF=D.box(D.types.dinf,D.box(D.types.dref,n))}static box(e,...t){let s=8,n=t.length;const a=n;for(;n--;)s+=t[n].byteLength;const h=new Uint8Array(s);for(h[0]=s>>24&255,h[1]=s>>16&255,h[2]=s>>8&255,h[3]=s&255,h.set(e,4),n=0,s=8;n<a;n++)h.set(t[n],s),s+=t[n].byteLength;return h}static hdlr(e){return D.box(D.types.hdlr,D.HDLR_TYPES[e])}static mdat(e){return D.box(D.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(ti+1)),n=Math.floor(t%(ti+1));return D.box(D.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,s>>24,s>>16&255,s>>8&255,s&255,n>>24,n>>16&255,n>>8&255,n&255,85,196,0,0]))}static mdia(e){return D.box(D.types.mdia,D.mdhd(e.timescale||0,e.duration||0),D.hdlr(e.type),D.minf(e))}static mfhd(e){return D.box(D.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"?D.box(D.types.minf,D.box(D.types.smhd,D.SMHD),D.DINF,D.stbl(e)):D.box(D.types.minf,D.box(D.types.vmhd,D.VMHD),D.DINF,D.stbl(e))}static moof(e,t,s){return D.box(D.types.moof,D.mfhd(e),D.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=D.trak(e[t]);return D.box.apply(null,[D.types.moov,D.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(D.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=D.trex(e[t]);return D.box.apply(null,[D.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(ti+1)),n=Math.floor(t%(ti+1)),a=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,s>>24,s>>16&255,s>>8&255,s&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 D.box(D.types.mvhd,a)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let n,a;for(n=0;n<t.length;n++)a=t[n].flags,s[n+4]=a.dependsOn<<4|a.isDependedOn<<2|a.hasRedundancy;return D.box(D.types.sdtp,s)}static stbl(e){return D.box(D.types.stbl,D.stsd(e),D.box(D.types.stts,D.STTS),D.box(D.types.stsc,D.STSC),D.box(D.types.stsz,D.STSZ),D.box(D.types.stco,D.STCO))}static avc1(e){let t=[],s=[],n,a,h;for(n=0;n<e.sps.length;n++)a=e.sps[n],h=a.byteLength,t.push(h>>>8&255),t.push(h&255),t=t.concat(Array.prototype.slice.call(a));for(n=0;n<e.pps.length;n++)a=e.pps[n],h=a.byteLength,s.push(h>>>8&255),s.push(h&255),s=s.concat(Array.prototype.slice.call(a));const l=D.box(D.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),u=e.width,d=e.height,p=e.pixelRatio[0],g=e.pixelRatio[1];return D.box(D.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,u>>8&255,u&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,D.box(D.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),D.box(D.types.pasp,new Uint8Array([p>>24,p>>16&255,p>>8&255,p&255,g>>24,g>>16&255,g>>8&255,g&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 D.box(D.types.mp4a,D.audioStsd(e),D.box(D.types.esds,D.esds(e)))}static mp3(e){return D.box(D.types[".mp3"],D.audioStsd(e))}static ac3(e){return D.box(D.types["ac-3"],D.audioStsd(e),D.box(D.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return D.box(D.types.stsd,D.STSD,D.mp4a(e));if(t==="ac3"&&e.config)return D.box(D.types.stsd,D.STSD,D.ac3(e));if(t==="mp3"&&e.codec==="mp3")return D.box(D.types.stsd,D.STSD,D.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return D.box(D.types.stsd,D.STSD,D.avc1(e));if(t==="hevc"&&e.vps)return D.box(D.types.stsd,D.STSD,D.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,s=(e.duration||0)*(e.timescale||0),n=e.width||0,a=e.height||0,h=Math.floor(s/(ti+1)),l=Math.floor(s%(ti+1));return D.box(D.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,h>>24,h>>16&255,h>>8&255,h&255,l>>24,l>>16&255,l>>8&255,l&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,a>>8&255,a&255,0,0]))}static traf(e,t){const s=D.sdtp(e),n=e.id,a=Math.floor(t/(ti+1)),h=Math.floor(t%(ti+1));return D.box(D.types.traf,D.box(D.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),D.box(D.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,h>>24,h>>16&255,h>>8&255,h&255])),D.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,D.box(D.types.trak,D.tkhd(e),D.mdia(e))}static trex(e){const t=e.id;return D.box(D.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 s=e.samples||[],n=s.length,a=12+16*n,h=new Uint8Array(a);let l,u,d,p,g,y;for(t+=8+a,h.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),l=0;l<n;l++)u=s[l],d=u.duration,p=u.size,g=u.flags,y=u.cts,h.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,p>>>24&255,p>>>16&255,p>>>8&255,p&255,g.isLeading<<2|g.dependsOn,g.isDependedOn<<6|g.hasRedundancy<<4|g.paddingValue<<1|g.isNonSync,g.degradPrio&61440,g.degradPrio&15,y>>>24&255,y>>>16&255,y>>>8&255,y&255],12+16*l);return D.box(D.types.trun,h)}static initSegment(e){D.types||D.init();const t=D.moov(e);return ct(D.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],n=4,a=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),s.length]);let h=a.length;for(let x=0;x<s.length;x+=1){h+=3;for(let E=0;E<s[x].length;E+=1)h+=2+s[x][E].length}const l=new Uint8Array(h);l.set(a,0),h=a.length;const u=s.length-1;for(let x=0;x<s.length;x+=1){l.set(new Uint8Array([32+x|(x===u?128:0),0,s[x].length]),h),h+=3;for(let E=0;E<s[x].length;E+=1)l.set(new Uint8Array([s[x][E].length>>8,s[x][E].length&255]),h),h+=2,l.set(s[x][E],h),h+=s[x][E].length}const d=D.box(D.types.hvcC,l),p=e.width,g=e.height,y=e.pixelRatio[0],v=e.pixelRatio[1];return D.box(D.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,p>>8&255,p&255,g>>8&255,g&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,D.box(D.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),D.box(D.types.pasp,new Uint8Array([y>>24,y>>16&255,y>>8&255,y&255,v>>24,v>>16&255,v>>8&255,v&255])))}}D.types=void 0;D.HDLR_TYPES=void 0;D.STTS=void 0;D.STSC=void 0;D.STCO=void 0;D.STSZ=void 0;D.VMHD=void 0;D.SMHD=void 0;D.STSD=void 0;D.FTYP=void 0;D.DINF=void 0;const Ud=9e4;function Co(r,e,t=1,s=!1){const n=r*e*t;return s?Math.round(n):n}function _y(r,e,t=1,s=!1){return Co(r,e,1/t,s)}function ys(r,e=!1){return Co(r,1e3,1/Ud,e)}function Ey(r,e=1){return Co(r,Ud,1/e)}const Ty=10*1e3,by=1024,Ay=1152,Iy=1536;let zi=null,sa=null;function lh(r,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:r?2:1,isNonSync:r?0:1}}}class In{constructor(e,t,s,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=s,this.logger=n,this.ISGenerated=!1,zi===null){const h=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);zi=h?parseInt(h[1]):0}if(sa===null){const a=navigator.userAgent.match(/Safari\/(\d+)/i);sa=a?parseInt(a[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 s=e[0].pts,n=e.reduce((a,h)=>{let l=h.pts,u=l-a;return u<-4294967296&&(t=!0,l=lt(l,s),u=l-a),u>0?a:l},s);return t&&this.logger.debug("PTS rollover detected"),n}remux(e,t,s,n,a,h,l,u){let d,p,g,y,v,x,E=a,o=a;const c=e.pid>-1,f=t.pid>-1,m=t.samples.length,S=e.samples.length>0,T=l&&m>0||m>1;if((!c||S)&&(!f||T)||this.ISGenerated||l){if(this.ISGenerated){var A,I,L,w;const G=this.videoTrackConfig;(G&&(t.width!==G.width||t.height!==G.height||((A=t.pixelRatio)==null?void 0:A[0])!==((I=G.pixelRatio)==null?void 0:I[0])||((L=t.pixelRatio)==null?void 0:L[1])!==((w=G.pixelRatio)==null?void 0:w[1]))||!G&&T||this.nextAudioPts===null&&S)&&this.resetInitSegment()}this.ISGenerated||(g=this.generateIS(e,t,a,h));const C=this.isVideoContiguous;let k=-1,U;if(T&&(k=wy(t.samples),!C&&this.config.forceKeyFrameOnDiscontinuity))if(x=!0,k>0){this.logger.warn(`[mp4-remuxer]: Dropped ${k} out of ${m} video samples due to a missing keyframe`);const G=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(k),t.dropped+=k,o+=(t.samples[0].pts-G)/t.inputTimeScale,U=o}else k===-1&&(this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${m} video samples`),x=!1);if(this.ISGenerated){if(S&&T){const G=this.getVideoStartPts(t.samples),z=(lt(e.samples[0].pts,G)-G)/t.inputTimeScale;E+=Math.max(0,z),o+=Math.max(0,-z)}if(S){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),g=this.generateIS(e,t,a,h)),p=this.remuxAudio(e,E,this.isAudioContiguous,h,f||T||u===X.AUDIO?o:void 0),T){const G=p?p.endPTS-p.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),g=this.generateIS(e,t,a,h)),d=this.remuxVideo(t,o,C,G)}}else T&&(d=this.remuxVideo(t,o,C,0));d&&(d.firstKeyFrame=k,d.independent=k!==-1,d.firstKeyFramePTS=U)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(v=Od(s,a,this._initPTS,this._initDTS)),n.samples.length&&(y=Bd(n,a,this._initPTS))),{audio:p,video:d,initSegment:g,independent:x,text:y,id3:v}}generateIS(e,t,s,n){const a=e.samples,h=t.samples,l=this.typeSupported,u={},d=this._initPTS;let p=!d||n,g="audio/mp4",y,v,x;if(p&&(y=v=1/0),e.config&&a.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":l.mpeg?(g="audio/mpeg",e.codec=""):l.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}u.audio={id:"audio",container:g,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&l.mpeg?new Uint8Array(0):D.initSegment([e]),metadata:{channelCount:e.channelCount}},p&&(x=e.inputTimeScale,!d||x!==d.timescale?y=v=a[0].pts-Math.round(x*s):p=!1)}if(t.sps&&t.pps&&h.length){if(t.timescale=t.inputTimeScale,u.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:D.initSegment([t]),metadata:{width:t.width,height:t.height}},p)if(x=t.inputTimeScale,!d||x!==d.timescale){const E=this.getVideoStartPts(h),o=Math.round(x*s);v=Math.min(v,lt(h[0].dts,E)-o),y=Math.min(y,E-o)}else p=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(u).length)return this.ISGenerated=!0,p?(this._initPTS={baseTime:y,timescale:x},this._initDTS={baseTime:v,timescale:x}):y=x=void 0,{tracks:u,initPTS:y,timescale:x}}remuxVideo(e,t,s,n){const a=e.inputTimeScale,h=e.samples,l=[],u=h.length,d=this._initPTS;let p=this.nextAvcDts,g=8,y=this.videoSampleDuration,v,x,E=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY,c=!1;if(!s||p===null){const F=t*a,O=h[0].pts-lt(h[0].dts,h[0].pts);zi&&p!==null&&Math.abs(F-O-p)<15e3?s=!0:p=F-O}const f=d.baseTime*a/d.timescale;for(let F=0;F<u;F++){const O=h[F];O.pts=lt(O.pts-f,p),O.dts=lt(O.dts-f,p),O.dts<h[F>0?F-1:F].dts&&(c=!0)}c&&h.sort(function(F,O){const te=F.dts-O.dts,ee=F.pts-O.pts;return te||ee}),v=h[0].dts,x=h[h.length-1].dts;const m=x-v,S=m?Math.round(m/(u-1)):y||e.inputTimeScale/30;if(s){const F=v-p,O=F>S,te=F<-1;if((O||te)&&(O?this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ys(F,!0)} ms (${F}dts) hole between fragments detected at ${t.toFixed(3)}`):this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ys(-F,!0)} ms (${F}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!te||p>=h[0].pts||zi)){v=p;const ee=h[0].pts-F;if(O)h[0].dts=v,h[0].pts=ee;else{let se=!0;for(let he=0;he<h.length&&!(h[he].dts>ee&&se);he++){const W=h[he].pts;if(h[he].dts-=F,h[he].pts-=F,he<h.length-1){const me=h[he+1].pts,De=h[he].pts,qe=me<=De,ei=me<=W;se=qe==ei}}}this.logger.log(`Video: Initial PTS/DTS adjusted: ${ys(ee,!0)}/${ys(v,!0)}, delta: ${ys(F,!0)} ms`)}}v=Math.max(0,v);let T=0,b=0,A=v;for(let F=0;F<u;F++){const O=h[F],te=O.units,ee=te.length;let se=0;for(let he=0;he<ee;he++)se+=te[he].data.length;b+=se,T+=ee,O.length=se,O.dts<A?(O.dts=A,A+=S/4|0||1):A=O.dts,E=Math.min(O.pts,E),o=Math.max(O.pts,o)}x=h[u-1].dts;const I=b+4*T+8;let L;try{L=new Uint8Array(I)}catch(F){this.observer.emit(_.ERROR,_.ERROR,{type:Q.MUX_ERROR,details:P.REMUX_ALLOC_ERROR,fatal:!1,error:F,bytes:I,reason:`fail allocating video mdat ${I}`});return}const w=new DataView(L.buffer);w.setUint32(0,I),L.set(D.types.mdat,4);let C=!1,k=Number.POSITIVE_INFINITY,U=Number.POSITIVE_INFINITY,G=Number.NEGATIVE_INFINITY,$=Number.NEGATIVE_INFINITY;for(let F=0;F<u;F++){const O=h[F],te=O.units;let ee=0;for(let W=0,me=te.length;W<me;W++){const De=te[W],qe=De.data,ei=De.data.byteLength;w.setUint32(g,ei),g+=4,L.set(qe,g),g+=ei,ee+=4+ei}let se;if(F<u-1)y=h[F+1].dts-O.dts,se=h[F+1].pts-O.pts;else{const W=this.config,me=F>0?O.dts-h[F-1].dts:S;if(se=F>0?O.pts-h[F-1].pts:S,W.stretchShortVideoTrack&&this.nextAudioPts!==null){const De=Math.floor(W.maxBufferHole*a),qe=(n?E+n*a:this.nextAudioPts)-O.pts;qe>De?(y=qe-me,y<0?y=me:C=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${qe/90} ms to the next segment; using duration ${y/90} ms for the last video frame.`)):y=me}else y=me}const he=Math.round(O.pts-O.dts);k=Math.min(k,y),G=Math.max(G,y),U=Math.min(U,se),$=Math.max($,se),l.push(lh(O.key,y,ee,he))}if(l.length){if(zi){if(zi<70){const F=l[0].flags;F.dependsOn=2,F.isNonSync=0}}else if(sa&&$-U<G-k&&S/G<.025&&l[0].cts===0){this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let F=v;for(let O=0,te=l.length;O<te;O++){const ee=F+l[O].duration,se=F+l[O].cts;if(O<te-1){const he=ee+l[O+1].cts;l[O].duration=he-se}else l[O].duration=O?l[O-1].duration:S;l[O].cts=0,F=ee}}}y=C||!y?S:y,this.nextAvcDts=p=x+y,this.videoSampleDuration=y,this.isVideoContiguous=!0;const Y={data1:D.moof(e.sequenceNumber++,v,Te(e,{samples:l})),data2:L,startPTS:E/a,endPTS:(o+y)/a,startDTS:v/a,endDTS:p/a,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Y}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Ay;case"ac3":return Iy;default:return by}}remuxAudio(e,t,s,n,a){const h=e.inputTimeScale,l=e.samplerate?e.samplerate:h,u=h/l,d=this.getSamplesPerFrame(e),p=d*u,g=this._initPTS,y=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,v=[],x=a!==void 0;let E=e.samples,o=y?0:8,c=this.nextAudioPts||-1;const f=t*h,m=g.baseTime*h/g.timescale;if(this.isAudioContiguous=s=s||E.length&&c>0&&(n&&Math.abs(f-c)<9e3||Math.abs(lt(E[0].pts-m,f)-c)<20*p),E.forEach(function(z){z.pts=lt(z.pts-m,f)}),!s||c<0){if(E=E.filter(z=>z.pts>=0),!E.length)return;a===0?c=0:n&&!x?c=Math.max(0,f):c=E[0].pts}if(e.segmentCodec==="aac"){const z=this.config.maxAudioFramesDrift;for(let j=0,Y=c;j<E.length;j++){const F=E[j],O=F.pts,te=O-Y,ee=Math.abs(1e3*te/h);if(te<=-z*p&&x)j===0&&(this.logger.warn(`Audio frame @ ${(O/h).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*te/h)} ms.`),this.nextAudioPts=c=Y=O);else if(te>=z*p&&ee<Ty&&x){let se=Math.round(te/p);Y=O-se*p,Y<0&&(se--,Y+=p),j===0&&(this.nextAudioPts=c=Y),this.logger.warn(`[mp4-remuxer]: Injecting ${se} audio frame @ ${(Y/h).toFixed(3)}s due to ${Math.round(1e3*te/h)} ms gap.`);for(let he=0;he<se;he++){const W=Math.max(Y,0);let me=Sy.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);me||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),me=F.unit.subarray()),E.splice(j,0,{unit:me,pts:W}),Y+=p,j++}}F.pts=Y,Y+=p}}let S=null,T=null,b,A=0,I=E.length;for(;I--;)A+=E[I].unit.byteLength;for(let z=0,j=E.length;z<j;z++){const Y=E[z],F=Y.unit;let O=Y.pts;if(T!==null){const ee=v[z-1];ee.duration=Math.round((O-T)/u)}else if(s&&e.segmentCodec==="aac"&&(O=c),S=O,A>0){A+=o;try{b=new Uint8Array(A)}catch(ee){this.observer.emit(_.ERROR,_.ERROR,{type:Q.MUX_ERROR,details:P.REMUX_ALLOC_ERROR,fatal:!1,error:ee,bytes:A,reason:`fail allocating audio mdat ${A}`});return}y||(new DataView(b.buffer).setUint32(0,A),b.set(D.types.mdat,4))}else return;b.set(F,o);const te=F.byteLength;o+=te,v.push(lh(!0,d,te,0)),T=O}const L=v.length;if(!L)return;const w=v[v.length-1];this.nextAudioPts=c=T+u*w.duration;const C=y?new Uint8Array(0):D.moof(e.sequenceNumber++,S/u,Te({},e,{samples:v}));e.samples=[];const k=S/h,U=c/h,$={data1:C,data2:b,startPTS:k,endPTS:U,startDTS:k,endDTS:U,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,$}}function lt(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 wy(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function Od(r,e,t,s){const n=r.samples.length;if(!n)return;const a=r.inputTimeScale;for(let l=0;l<n;l++){const u=r.samples[l];u.pts=lt(u.pts-t.baseTime*a/t.timescale,e*a)/a,u.dts=lt(u.dts-s.baseTime*a/s.timescale,e*a)/a}const h=r.samples;return r.samples=[],{samples:h}}function Bd(r,e,t){const s=r.samples.length;if(!s)return;const n=r.inputTimeScale;for(let h=0;h<s;h++){const l=r.samples[h];l.pts=lt(l.pts-t.baseTime*n/t.timescale,e*n)/n}r.samples.sort((h,l)=>h.pts-l.pts);const a=r.samples;return r.samples=[],{samples:a}}class Ly{constructor(e,t,s,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,s,n){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(m0(e,n)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:s}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const n=this.initData=Wc(e);n.audio&&(t=hh(n.audio,Ee.AUDIO)),n.video&&(s=hh(n.video,Ee.VIDEO));const a={};n.audio&&n.video?a.audiovideo={container:"video/mp4",codec:t+","+s,supplemental:n.video.supplemental,initSegment:e,id:"main"}:n.audio?a.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:n.video?a.video={container:"video/mp4",codec:s,supplemental:n.video.supplemental,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,s,n,a,h){var l,u;let{initPTS:d,lastEndTime:p}=this;const g={audio:void 0,video:void 0,text:n,id3:s,initSegment:void 0};K(p)||(p=this.lastEndTime=a||0);const y=t.samples;if(!(y!=null&&y.length))return g;const v={initPTS:void 0,timescale:1};let x=this.initData;if((l=x)!=null&&l.length||(this.generateInitSegment(y),x=this.initData),!((u=x)!=null&&u.length))return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),g;this.emitInitSegment&&(v.tracks=this.initTracks,this.emitInitSegment=!1);const E=x0(y,x),o=y0(x,y),c=o===null?a:o;(h||!d)&&(Ry(d,c,a,E)||v.timescale!==d.timescale)&&(v.initPTS=c-a,d&&d.timescale===1&&this.logger.warn(`Adjusting initPTS @${a} from ${d.baseTime/d.timescale} to ${v.initPTS}`),this.initPTS=d={baseTime:v.initPTS,timescale:1});const f=e?c-d.baseTime/d.timescale:p,m=f+E;S0(x,y,d.baseTime/d.timescale),E>0?this.lastEndTime=m:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const S=!!x.audio,T=!!x.video;let b="";S&&(b+="audio"),T&&(b+="video");const A={data1:y,startPTS:f,startDTS:f,endPTS:m,endDTS:m,type:b,hasAudio:S,hasVideo:T,nb:1,dropped:0};return g.audio=A.type==="audio"?A:void 0,g.video=A.type!=="audio"?A:void 0,g.initSegment=v,g.id3=Od(s,a,d,d),n.samples.length&&(g.text=Bd(n,a,d)),g}}function Ry(r,e,t,s){if(r===null)return!0;const n=Math.max(s,1),a=e-r.baseTime/r.timescale;return Math.abs(a-t)>n}function hh(r,e){const t=r==null?void 0:r.codec;return t&&t.length>4?t:e===Ee.AUDIO?t==="ec-3"||t==="ac-3"||t==="alac"?t:t==="fLaC"||t==="Opus"?Gn(t,!1):(pe.warn(`Unhandled audio codec "${t}" in mp4 MAP`),t||"mp4a"):(pe.warn(`Unhandled video codec "${t}" in mp4 MAP`),t||"avc1")}let zt;try{zt=self.performance.now.bind(self.performance)}catch{zt=Date.now}const wn=[{demux:my,remux:Ly},{demux:ri,remux:In},{demux:uy,remux:In},{demux:py,remux:In}];wn.splice(2,0,{demux:fy,remux:In});class ch{constructor(e,t,s,n,a,h){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=s,this.id=a,this.logger=h}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,n){const a=s.transmuxing;a.executeStart=zt();let h=new Uint8Array(e);const{currentTransmuxState:l,transmuxConfig:u}=this;n&&(this.currentTransmuxState=n);const{contiguous:d,discontinuity:p,trackSwitch:g,accurateTimeOffset:y,timeOffset:v,initSegmentChange:x}=n||l,{audioCodec:E,videoCodec:o,defaultInitPts:c,duration:f,initSegmentData:m}=u,S=Cy(h,t);if(S&&Zi(S.method)){const I=this.getDecrypter(),L=_o(S.method);if(I.isSync()){let w=I.softwareDecrypt(h,S.key.buffer,S.iv.buffer,L);if(s.part>-1){const k=I.flush();w=k&&k.buffer}if(!w)return a.executeEnd=zt(),na(s);h=new Uint8Array(w)}else return this.asyncResult=!0,this.decryptionPromise=I.webCryptoDecrypt(h,S.key.buffer,S.iv.buffer,L).then(w=>{const C=this.push(w,null,s);return this.decryptionPromise=null,C}),this.decryptionPromise}const T=this.needsProbing(p,g);if(T){const I=this.configureTransmuxer(h);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(_.ERROR,_.ERROR,{type:Q.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),a.executeEnd=zt(),na(s)}(p||g||x||T)&&this.resetInitSegment(m,E,o,f,t),(p||x||T)&&this.resetInitialTimestamp(c),d||this.resetContiguity();const b=this.transmux(h,S,v,y,s);this.asyncResult=Os(b);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,a.executeEnd=zt(),b}flush(e){const t=e.transmuxing;t.executeStart=zt();const{decrypter:s,currentTransmuxState:n,decryptionPromise:a}=this;if(a)return this.asyncResult=!0,a.then(()=>this.flush(e));const h=[],{timeOffset:l}=n;if(s){const g=s.flush();g&&h.push(this.push(g.buffer,null,e))}const{demuxer:u,remuxer:d}=this;if(!u||!d){t.executeEnd=zt();const g=[na(e)];return this.asyncResult?Promise.resolve(g):g}const p=u.flush(l);return Os(p)?(this.asyncResult=!0,p.then(g=>(this.flushRemux(h,g,e),h))):(this.flushRemux(h,p,e),this.asyncResult?Promise.resolve(h):h)}flushRemux(e,t,s){const{audioTrack:n,videoTrack:a,id3Track:h,textTrack:l}=t,{accurateTimeOffset:u,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===X.MAIN?"level":"track"} ${s.level}`);const p=this.remuxer.remux(n,a,h,l,d,u,!0,this.id);e.push({remuxResult:p,chunkMeta:s}),s.transmuxing.executeEnd=zt()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,n,a){const{demuxer:h,remuxer:l}=this;!h||!l||(h.resetInitSegment(e,t,s,n),l.resetInitSegment(e,t,s,a))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,n,a){let h;return t&&t.method==="SAMPLE-AES"?h=this.transmuxSampleAes(e,t,s,n,a):h=this.transmuxUnencrypted(e,s,n,a),h}transmuxUnencrypted(e,t,s,n){const{audioTrack:a,videoTrack:h,id3Track:l,textTrack:u}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(a,h,l,u,t,s,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,s,n,a){return this.demuxer.demuxSampleAes(e,t,s).then(h=>({remuxResult:this.remuxer.remux(h.audioTrack,h.videoTrack,h.id3Track,h.textTrack,s,n,!1,this.id),chunkMeta:a}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:n}=this;let a;for(let g=0,y=wn.length;g<y;g++){var h;if((h=wn[g].demux)!=null&&h.probe(e,this.logger)){a=wn[g];break}}if(!a)return new Error("Failed to find demuxer by probing fragment data");const l=this.demuxer,u=this.remuxer,d=a.remux,p=a.demux;(!u||!(u instanceof d))&&(this.remuxer=new d(s,t,n,this.logger)),(!l||!(l instanceof p))&&(this.demuxer=new p(s,t,n,this.logger),this.probe=p.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new vo(this.config)),e}}function Cy(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 na=r=>({remuxResult:{},chunkMeta:r});function Os(r){return"then"in r&&r.then instanceof Function}class Dy{constructor(e,t,s,n,a){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=s,this.duration=n,this.defaultInitPts=a||null}}class Py{constructor(e,t,s,n,a,h){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=s,this.trackSwitch=n,this.timeOffset=a,this.initSegmentChange=h}}let dh=0;class Nd{constructor(e,t,s,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=dh++,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=u=>{const d=u.data,p=this.hls;if(!(!p||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var g;const y=(g=this.workerContext)==null?void 0:g.objectURL;y&&self.URL.revokeObjectURL(y);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{p.logger[d.data.logType]&&p.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,p.trigger(d.event,d.data);break}}},this.onWorkerError=u=>{if(!this.hls)return;const d=new Error(`${u.message} (${u.filename}:${u.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(_.ERROR,{type:Q.OTHER_ERROR,details:P.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};const a=e.config;this.hls=e,this.id=t,this.useWorker=!!a.enableWorker,this.onTransmuxComplete=s,this.onFlush=n;const h=(u,d)=>{d=d||{},d.frag=this.frag||void 0,u===_.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(u,d)};this.observer=new bo,this.observer.on(_.FRAG_DECRYPTED,h),this.observer.on(_.ERROR,h);const l=wl(a.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const u=this.hls.logger;if(a.workerPath||Fm()){try{a.workerPath?(u.log(`loading Web Worker ${a.workerPath} for "${t}"`),this.workerContext=Om(a.workerPath)):(u.log(`injecting Web Worker for "${t}"`),this.workerContext=Um());const{worker:p}=this.workerContext;p.addEventListener("message",this.onWorkerMessage),p.addEventListener("error",this.onWorkerError),p.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:l,id:t,config:Ae(a)})}catch(p){u.warn(`Error setting up "${t}" Web Worker, fallback to inline`,p),this.terminateWorker(),this.error=null,this.transmuxer=new ch(this.observer,l,a,"",t,e.logger)}return}}this.transmuxer=new ch(this.observer,l,a,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=dh++;const t=this.hls.config,s=wl(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:Ae(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),Bm(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,s,n,a,h,l,u,d,p){var g,y;d.transmuxing.start=self.performance.now();const{instanceNo:v,transmuxer:x}=this,E=h?h.start:a.start,o=a.decryptdata,c=this.frag,f=!(c&&a.cc===c.cc),m=!(c&&d.level===c.level),S=c?d.sn-c.sn:-1,T=this.part?d.part-this.part.index:-1,b=S===0&&d.id>1&&d.id===(c==null?void 0:c.stats.chunkCount),A=!m&&(S===1||S===0&&(T===1||b&&T<=0)),I=self.performance.now();(m||S||a.stats.parsing.start===0)&&(a.stats.parsing.start=I),h&&(T||!A)&&(h.stats.parsing.start=I);const L=!(c&&((g=a.initSegment)==null?void 0:g.url)===((y=c.initSegment)==null?void 0:y.url)),w=new Py(f,A,u,m,E,L);if(!A||f||L){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${a.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===X.MAIN?"level":"track"}: ${d.level} id: ${d.id}
|
|
120
|
+
${t.m3u8}`)}function Md(r,e,t=!0){const s=e.startSN+e.skippedSegments-r.startSN,n=r.fragments,a=s>=0;let h=0;if(a&&s<n.length)h=n[s].start;else if(a&&e.startSN===r.endSN+1)h=r.fragmentEnd;else if(a&&t)h=r.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)h=r.fragmentStart;else return;qa(e,h)}function qa(r,e){if(e){const t=r.fragments;for(let s=r.skippedSegments;s<t.length;s++)t[s].addStart(e);r.fragmentHint&&r.fragmentHint.addStart(e)}}function Fd(r,e=1/0){let t=1e3*r.targetduration;if(r.updated){const s=r.fragments;if(s.length&&t*4>e){const a=s[s.length-1].duration*1e3;a<t&&(t=a)}}else t/=2;return Math.round(t)}function Ud(r,e,t){if(!r)return null;let s=r.fragments[e-r.startSN];return s||(s=r.fragmentHint,s&&s.sn===e)?s:e<r.startSN&&t&&t.sn===e?t:null}function vh(r,e,t){return r?Od(r.partList,e,t):null}function Od(r,e,t){if(r)for(let s=r.length;s--;){const n=r[s];if(n.index===t&&n.fragment.sn===e)return n}return null}function Bd(r){r.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(n=>{n.level=t,n.initSegment&&(n.initSegment.level=t)})})}function sy(r,e){return r!==e&&e?xh(r)!==xh(e):!1}function xh(r){return r.replace(/\?[^?]*$/,"")}function Ms(r,e){for(let s=0,n=r.length;s<n;s++){var t;if(((t=r[s])==null?void 0:t.cc)===e)return r[s]}return null}function ny(r,e){return!!(r&&e.startCC<r.endCC&&e.endCC>r.startCC)}function Sh(r,e){const t=r.start+e;r.startPTS=t,r.setStart(t),r.endPTS=t+r.duration}function Nd(r,e){const t=e.fragments;for(let s=0,n=t.length;s<n;s++)Sh(t[s],r);e.fragmentHint&&Sh(e.fragmentHint,r),e.alignedSliding=!0}function ry(r,e){r&&($d(e,r),e.alignedSliding||nr(e,r),!e.alignedSliding&&!e.skippedSegments&&Md(r,e,!1))}function $d(r,e){if(!ny(e,r))return;const t=Math.min(e.endCC,r.endCC),s=Ms(e.fragments,t),n=Ms(r.fragments,t);if(!s||!n)return;_e.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const a=s.start-n.start;Nd(a,r)}function nr(r,e){if(!r.hasProgramDateTime||!e.hasProgramDateTime)return;const t=r.fragments,s=e.fragments;if(!t.length||!s.length)return;let n,a;const h=Math.min(e.endCC,r.endCC);e.startCC<h&&r.startCC<h&&(n=Ms(s,h),a=Ms(t,h)),(!n||!a)&&(n=s[Math.floor(s.length/2)],a=Ms(t,n.cc)||t[Math.floor(t.length/2)]);const l=n.programDateTime,u=a.programDateTime;if(!l||!u)return;const d=(u-l)/1e3-(a.start-n.start);Nd(d,r)}function Je(r,e,t){it(r,e,t),r.addEventListener(e,t)}function it(r,e,t){r.removeEventListener(e,t)}const ay={toString:function(r){let e="";const t=r.length;for(let s=0;s<t;s++)e+=`[${r.start(s).toFixed(3)}-${r.end(s).toFixed(3)}]`;return e}},F={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 Oo extends Ad{constructor(e,t,s,n,a){super(n,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=F.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:h,fragCurrent:l,media:u,mediaBuffer:d,state:p}=this,g=u?u.currentTime:0,y=ae.bufferInfo(d||u,g,h.maxBufferHole),x=!y.len;if(this.log(`Media seeking to ${q(g)?g.toFixed(3):g}, state: ${p}, ${x?"out of":"in"} buffer`),this.state===F.ENDED)this.resetLoadingState();else if(l){const v=h.maxFragLookUpTolerance,_=l.start-v,o=l.start+l.duration+v;if(x||o<y.start||_>y.end){const c=g>o;(g<_||c)&&(c&&l.loader&&(this.log(`Cancelling fragment load for seek (sn: ${l.sn})`),l.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(u){this.fragmentTracker.removeFragmentsInRange(g,1/0,this.playlistType,!0);const v=this.lastCurrentTime;if(g>v&&(this.lastCurrentTime=g),!this.loadingParts){const _=Math.max(y.end,g),o=this.shouldLoadParts(this.getLevelDetails(),_);o&&(this.log(`LL-Part loading ON after seeking to ${g.toFixed(2)} with buffer @${_.toFixed(2)}`),this.loadingParts=o)}}this.hls.hasEnoughToStart||(this.log(`Setting ${x?"startPosition":"nextLoadPosition"} to ${g} for seek without enough to start`),this.nextLoadPosition=g,x&&(this.startPosition=g)),x&&this.state===F.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=a,this.hls=e,this.fragmentLoader=new Mm(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new ko(e.config)}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===F.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=F.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 s=e.end||0,n=this.config.timelineOffset||0;if(s<=n)return!1;const a=e.buffered;this.config.maxBufferHole&&a&&a.length>1&&(e=ae.bufferedInfo(a,e.start,0));const h=e.nextStart;if(h&&h>n&&h<t.edge||this.media.currentTime<e.start)return!1;const u=t.partList;if(u!=null&&u.length){const p=u[u.length-1];return ae.isBuffered(this.media,p.start+p.duration/2)}const d=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(d)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){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 s=this.media=this.mediaBuffer=t.media;Je(s,"seeking",this.onMediaSeeking),Je(s,"ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===F.STOPPED&&this.startLoad(n.startPosition)}onMediaDetaching(e,t){const s=!!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),it(n,"seeking",this.onMediaSeeking),it(n,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){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=F.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,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const n=a=>{const h=a.frag;if(this.fragContextChanged(h)){this.warn(`${h.type} sn: ${h.sn}${a.part?" part: "+a.part.index:""} of ${this.fragInfo(h,!1,a.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(h);return}h.stats.chunkCount++,this._handleFragmentLoadProgress(a)};this._doFragLoad(e,t,s,n).then(a=>{if(!a)return;const h=this.state,l=a.frag;if(this.fragContextChanged(l)){(h===F.FRAG_LOADING||!this.fragCurrent&&h===F.PARSING)&&(this.fragmentTracker.removeFragment(l),this.state=F.IDLE);return}"payload"in a&&(this.log(`Loaded ${l.type} sn: ${l.sn} of ${this.playlistLabel()} ${l.level}`),this.hls.trigger(E.FRAG_LOADED,a)),this._handleFragmentLoadComplete(a)}).catch(a=>{this.state===F.STOPPED||this.state===F.ERROR||(this.warn(`Frag error: ${(a==null?void 0:a.message)||a}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===Fe.APPENDING){const a=e.type,h=this.getFwdBufferInfo(this.mediaBuffer,a),l=Math.max(e.duration,h?h.len:this.config.maxBufferLength),u=this.backtrackFragment;((u?e.sn-u.sn:0)===1||this.reduceMaxBufferLength(l,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===Fe.PARTIAL&&s.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,s=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:s};this.hls.trigger(E.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const n=s==null?void 0:s.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:n}=this,{frag:a,payload:h}=s,l=a.decryptdata;if(h&&h.byteLength>0&&l!=null&&l.key&&l.iv&&hs(l.method)){const u=self.performance.now();return this.decrypter.decrypt(new Uint8Array(h),l.key.buffer,l.iv.buffer,Fo(l.method)).catch(d=>{throw n.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:a}),d}).then(d=>{const p=self.performance.now();return n.trigger(E.FRAG_DECRYPTED,{frag:a,payload:d,stats:{tstart:u,tdecrypt:p}}),s.payload=d,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===F.STOPPED||this.state===F.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==F.STOPPED&&(this.state=F.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,n;const a=e.tracks;if(a&&!t.encrypted&&((s=a.audio)!=null&&s.encrypted||(n=a.video)!=null&&n.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const h=this.media,l=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${h?"attached mediaKeys: "+h.mediaKeys:"detached"})`);return this.warn(l.message),!h||h.mediaKeys?!1:(this.hls.trigger(E.ERROR,{type:Z.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_KEYS,fatal:!1,error:l,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=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:${s?ay.toString(ae.getBuffered(s)):"(detached)"})`),Pe(e)){var n;if(e.type!==X.SUBTITLE){const h=e.elementaryStreams;if(!Object.keys(h).some(l=>!!h[l])){this.state=F.IDLE;return}}const a=(n=this.levels)==null?void 0:n[e.level];a!=null&&a.fragmentError&&(this.log(`Resetting level fragment error count of ${a.fragmentError} on frag buffered`),a.fragmentError=0)}this.state=F.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:n,partsLoaded:a}=e,h=!a||a.length===0||a.some(u=>!u),l=new Mo(s.level,s.sn,s.stats.chunkCount+1,0,n?n.index:-1,!h);t.flush(l)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,n){var a;this.fragCurrent=e;const h=t.details;if(!this.levels||!h)throw new Error(`frag load aborted, missing level${h?"":" detail"}s`);let l=null;if(e.encrypted&&!((a=e.decryptdata)!=null&&a.key)){if(this.log(`Loading key for ${e.sn} of [${h.startSN}-${h.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=F.KEY_LOADING,this.fragCurrent=e,l=this.keyLoader.load(e).then(y=>{if(!this.fragContextChanged(y.frag))return this.hls.trigger(E.KEY_LOADED,y),this.state===F.KEY_LOADING&&(this.state=F.IDLE),y}),this.hls.trigger(E.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(l=this.keyLoader.loadClear(e,h.encryptedFragments,this.startFragRequested),l&&this.log("[eme] blocking frag load until media-keys acquired"));const u=this.fragPrevious;if(Pe(e)&&(!u||e.sn!==u.sn)){const y=this.shouldLoadParts(t.details,e.end);y!==this.loadingParts&&(this.log(`LL-Part loading ${y?"ON":"OFF"} loading sn ${u==null?void 0:u.sn}->${e.sn}`),this.loadingParts=y)}if(s=Math.max(e.start,s||0),this.loadingParts&&Pe(e)){const y=h.partList;if(y&&n){s>h.fragmentEnd&&h.fragmentHint&&(e=h.fragmentHint);const x=this.getNextPart(y,e,s);if(x>-1){const v=y[x];e=this.fragCurrent=v.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${v.index} (${x}/${y.length-1}) of ${this.fragInfo(e,!1,v)}) cc: ${e.cc} [${h.startSN}-${h.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=v.start+v.duration,this.state=F.FRAG_LOADING;let _;return l?_=l.then(o=>!o||this.fragContextChanged(o.frag)?null:this.doFragPartsLoad(e,v,t,n)).catch(o=>this.handleFragLoadError(o)):_=this.doFragPartsLoad(e,v,t,n).catch(o=>this.handleFragLoadError(o)),this.hls.trigger(E.FRAG_LOADING,{frag:e,part:v,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):_}else if(!e.url||this.loadedEndOfParts(y,s))return Promise.resolve(null)}}if(Pe(e)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(d=h.partList)==null?void 0:d.filter(y=>y.loaded).map(y=>`[${y.start}-${y.end}]`)}`),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} ${"["+h.startSN+"-"+h.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),q(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=F.FRAG_LOADING;const p=this.config.progressive;let g;return p&&l?g=l.then(y=>!y||this.fragContextChanged(y.frag)?null:this.fragmentLoader.load(e,n)).catch(y=>this.handleFragLoadError(y)):g=Promise.all([this.fragmentLoader.load(e,p?n:void 0),l]).then(([y])=>(!p&&n&&n(y),y)).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(E.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):g}doFragPartsLoad(e,t,s,n){return new Promise((a,h)=>{var l;const u=[],d=(l=s.details)==null?void 0:l.partList,p=g=>{this.fragmentLoader.loadPart(e,g,n).then(y=>{u[g.index]=y;const x=y.part;this.hls.trigger(E.FRAG_LOADED,y);const v=vh(s.details,e.sn,g.index+1)||Od(d,e.sn,g.index+1);if(v)p(v);else return a({frag:e,part:x,partsLoaded:u})}).catch(h)};p(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===D.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Z.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(E.ERROR,t)}else this.hls.trigger(E.ERROR,{type:Z.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==F.PARSING){!this.fragCurrent&&this.state!==F.STOPPED&&this.state!==F.ERROR&&(this.state=F.IDLE);return}const{frag:s,part:n,level:a}=t,h=self.performance.now();s.stats.parsing.end=h,n&&(n.stats.parsing.end=h);const l=this.getLevelDetails(),d=l&&s.sn>l.endSN||this.shouldLoadParts(l,s.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(s,n,a,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const a=e.partList[0];if(a.fragment.type===X.SUBTITLE)return!1;const h=a.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=h){var n;if((this.hls.hasEnoughToStart?((n=this.media)==null?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>a.start-a.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:n,sn:a,part:h}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${a} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const l=t[n],u=l.details,d=h>-1?vh(u,a,h):null,p=d?d.fragment:Ud(u,a,s);return p?(s&&s!==p&&(p.stats=s.stats),{frag:p,part:d,level:l}):null}bufferFragmentData(e,t,s,n,a){if(this.state!==F.PARSING)return;const{data1:h,data2:l}=e;let u=h;if(l&&(u=yt(h,l)),!u.length)return;const d=this.initPTS[t.cc],p=d?-d.baseTime/d.timescale:void 0,g={type:e.type,frag:t,part:s,chunkMeta:n,offset:p,parent:t.type,data:u};if(this.hls.trigger(E.BUFFER_APPENDING,g),e.dropped&&e.independent&&!s){if(a)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!ae.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,n=ae.bufferInfo(t,s,0),a=e.duration,h=Math.min(this.config.maxFragLookUpTolerance*2,a*.25),l=Math.max(Math.min(e.start-h,n.end-h),s+h);e.start-l>h&&this.flushMainBuffer(l,e.start)}getFwdBufferInfo(e,t){var s;const n=this.getLoadPosition();if(!q(n))return null;const h=this.lastCurrentTime>n||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,h)}getFwdBufferInfoAtPos(e,t,s,n){const a=ae.bufferInfo(e,t,n);if(a.len===0&&a.nextStart!==void 0){const h=this.fragmentTracker.getBufferedFrag(t,s);if(h&&(a.nextStart<=h.end||h.gap)){const l=Math.max(Math.min(a.nextStart,h.end)-t,n);return ae.bufferInfo(e,t,l)}}return a}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,n=Math.max(Math.min(e-t,s.maxBufferLength),t),a=Math.max(e-t*3,s.maxMaxBufferLength/2,n);return a>=n?(s.maxMaxBufferLength=a,this.warn(`Reduce max buffer length to ${a}s`),!0):!1}getAppendedFrag(e,t=X.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,n=s.length;if(!n)return null;const{config:a}=this,h=s[0].start,l=a.lowLatencyMode&&!!t.partList;let u=null;if(t.live){const g=a.initialLiveManifestSize;if(n<g)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${g})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<h){var d;l&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),u=this.getInitialLiveFragment(t);const y=this.hls.startPosition,x=this.hls.liveSyncPosition,v=u?(y!==-1&&y>=h?y:x)||u.start:e;this.log(`Setting startPosition to ${v} to match start frag at live edge. mainStart: ${y} liveSyncPosition: ${x} frag.start: ${(d=u)==null?void 0:d.start}`),this.startPosition=this.nextLoadPosition=v}}else e<=h&&(u=s[0]);if(!u){const g=this.loadingParts?t.partEnd:t.fragmentEnd;u=this.getFragmentAtPosition(e,g,t)}let p=this.filterReplacedPrimary(u,t);if(!p&&u){const g=u.sn-t.startSN;p=this.filterReplacedPrimary(s[g+1]||null,t)}return this.mapToInitFragWhenRequired(p)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===Fe.OK||s===Fe.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,n,a){let h=null;if(e.gap&&(h=this.getNextFragment(this.nextLoadPosition,t),h&&!h.gap&&s.nextStart)){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,n,0);if(l!==null&&s.len+l.len>=a){const u=h.sn;return this.loopSn!==u&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${u}`),this.loopSn=u),null}}return this.loopSn=void 0,h}get primaryPrefetch(){if(_h(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(_h(this.config)&&e.type!==X.SUBTITLE){const s=this.hls.interstitialsManager,n=s==null?void 0:s.bufferingItem;if(n){const h=n.event;if(h){if(h.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 a=s==null?void 0:s.playerQueue;if(a)for(let h=a.length;h--;){const l=a[h].interstitial;if(l.appendInPlace&&e.start>=l.startTime&&e.end<=l.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let n=-1,a=!1,h=!0;for(let l=0,u=e.length;l<u;l++){const d=e[l];if(h=h&&!d.independent,n>-1&&s<d.start)break;const p=d.loaded;p?n=-1:(a||(d.independent||h)&&d.fragment===t)&&(d.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${d.start}`),n=l),a=p}return n}loadedEndOfParts(e,t){let s;for(let n=e.length;n--;){if(s=e[n],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let n=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),n=Em(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const a=s.sn+1;if(a>=e.startSN&&a<=e.endSN){const h=t[a-e.startSN];s.cc===h.cc&&(n=h,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=Ed(e,s.cc,s.end),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const a=this.hls.liveSyncPosition;a!==null&&(n=this.getFragmentAtPosition(a,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,s){const{config:n}=this;let{fragPrevious:a}=this,{fragments:h,endSN:l}=s;const{fragmentHint:u}=s,{maxFragLookUpTolerance:d}=n,p=s.partList,g=!!(this.loadingParts&&p!=null&&p.length&&u);g&&!this.bitrateTest&&p[p.length-1].fragment.sn===u.sn&&(h=h.concat(u),l=u.sn);let y;if(e<t){var x;const _=e<this.lastCurrentTime||e>t-d||(x=this.media)!=null&&x.paused||!this.startFragRequested?0:d;y=zi(a,h,e,_)}else y=h[h.length-1];if(y){const v=y.sn-s.startSN,_=this.fragmentTracker.getState(y);if((_===Fe.OK||_===Fe.PARTIAL&&y.gap)&&(a=y),a&&y.sn===a.sn&&(!g||p[0].fragment.sn>y.sn||!s.live)&&y.level===a.level){const c=h[v+1];y.sn<l&&this.fragmentTracker.getState(c)!==Fe.OK?y=c:y=null}}return y}alignPlaylists(e,t,s){const n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const a=e.fragmentStart,h=!t,l=e.alignedSliding&&q(a);if(h||!l&&!a){ry(s,e);const u=e.fragmentStart;return this.log(`Live playlist sliding: ${u.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${n}`),u}return a}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const n=this.timelineOffset;if(s===-1){const a=this.startTimeOffset!==null,h=a?this.startTimeOffset:e.startTimeOffset;h!==null&&q(h)?(s=t+h,h<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${h} found in ${a?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+n}this.nextLoadPosition=s+n}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Pe(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==F.FRAG_LOADING_WAITING_RETRY)&&(this.state=F.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const c=this.getCurrentContext(t.chunkMeta);c&&(t.frag=c.frag)}const n=t.frag;if(!n||n.type!==e||!this.levels)return;if(this.fragContextChanged(n)){var a;this.warn(`Frag load error must match current frag to retry ${n.url} > ${(a=this.fragCurrent)==null?void 0:a.url}`);return}const h=t.details===D.FRAG_GAP;h&&this.fragmentTracker.fragBuffered(n,!0);const l=t.errorAction;if(!l){this.state=F.ERROR;return}const{action:u,flags:d,retryCount:p=0,retryConfig:g}=l,y=!!g,x=y&&u===He.RetryRequest,v=y&&!l.resolved&&d===ot.MoveAllAlternatesMatchingHost,_=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!x&&v&&Pe(n)&&!n.endList&&_&&!bd(t))this.resetFragmentErrors(e),this.treatAsGap(n),l.resolved=!0;else if((x||v)&&p<g.maxNumRetry){var o;const c=Ka((o=t.response)==null?void 0:o.code),f=Do(g,p);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+f,this.state=F.FRAG_LOADING_WAITING_RETRY,l.resolved=!0,c){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${p+1}/${g.maxNumRetry} in ${f}ms`)}else if(g)if(this.resetFragmentErrors(e),p<g.maxNumRetry)!h&&u!==He.RemoveAlternatePermanently&&(l.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${p})`);return}else u===He.SendAlternateToPenaltyBox?this.state=F.WAITING_LEVEL:this.state=F.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Ka(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=F.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===F.PARSING||this.state===F.PARSED){const t=e.frag,s=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,s),a=n&&n.len>.5;a&&this.reduceMaxBufferLength(n.len,(t==null?void 0:t.duration)||10);const h=!a;return h&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),h}return!1}resetFragmentErrors(e){e===X.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==F.STOPPED&&(this.state=F.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const n=ae.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,s),this.state===F.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==F.STOPPED&&(this.state=F.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,n){const a=s.details;if(!a){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((u,d)=>{const p=e.elementaryStreams[d];if(p){const g=p.endPTS-p.startPTS;if(g<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${g})`),u||!1;const y=n?0:kd(a,e,p.startPTS,p.endPTS,p.startDTS,p.endDTS,this);return this.hls.trigger(E.LEVEL_PTS_UPDATED,{details:a,level:s,drift:y,type:d,frag:e,start:p.startPTS,end:p.endPTS}),!0}return u},!1)){var l;if(s.fragmentError===0&&this.treatAsGap(e,s),((l=this.transmuxer)==null?void 0:l.error)===null){const u=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(u.message),this.hls.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:u,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=F.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(E.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===X.MAIN?"level":"track"}fragInfo(e,t=!0,s){var n,a;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((n=t&&!s?e.startPTS:(s||e).start)!=null?n:NaN).toFixed(3)}-${((a=t&&!s?e.endPTS:(s||e).end)!=null?a:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.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.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function _h(r){return!!r.interstitialsController&&r.enableInterstitialPlayback!==!1}class Gd{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=oy(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function oy(r,e){const t=new Uint8Array(e);let s=0;for(let n=0;n<r.length;n++){const a=r[n];t.set(a,s),s+=a.length}return t}var ha={exports:{}},Eh;function ly(){return Eh||(Eh=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function n(u,d,p){this.fn=u,this.context=d,this.once=p||!1}function a(u,d,p,g,y){if(typeof p!="function")throw new TypeError("The listener must be a function");var x=new n(p,g||u,y),v=t?t+d:d;return u._events[v]?u._events[v].fn?u._events[v]=[u._events[v],x]:u._events[v].push(x):(u._events[v]=x,u._eventsCount++),u}function h(u,d){--u._eventsCount===0?u._events=new s:delete u._events[d]}function l(){this._events=new s,this._eventsCount=0}l.prototype.eventNames=function(){var d=[],p,g;if(this._eventsCount===0)return d;for(g in p=this._events)e.call(p,g)&&d.push(t?g.slice(1):g);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(p)):d},l.prototype.listeners=function(d){var p=t?t+d:d,g=this._events[p];if(!g)return[];if(g.fn)return[g.fn];for(var y=0,x=g.length,v=new Array(x);y<x;y++)v[y]=g[y].fn;return v},l.prototype.listenerCount=function(d){var p=t?t+d:d,g=this._events[p];return g?g.fn?1:g.length:0},l.prototype.emit=function(d,p,g,y,x,v){var _=t?t+d:d;if(!this._events[_])return!1;var o=this._events[_],c=arguments.length,f,m;if(o.fn){switch(o.once&&this.removeListener(d,o.fn,void 0,!0),c){case 1:return o.fn.call(o.context),!0;case 2:return o.fn.call(o.context,p),!0;case 3:return o.fn.call(o.context,p,g),!0;case 4:return o.fn.call(o.context,p,g,y),!0;case 5:return o.fn.call(o.context,p,g,y,x),!0;case 6:return o.fn.call(o.context,p,g,y,x,v),!0}for(m=1,f=new Array(c-1);m<c;m++)f[m-1]=arguments[m];o.fn.apply(o.context,f)}else{var S=o.length,T;for(m=0;m<S;m++)switch(o[m].once&&this.removeListener(d,o[m].fn,void 0,!0),c){case 1:o[m].fn.call(o[m].context);break;case 2:o[m].fn.call(o[m].context,p);break;case 3:o[m].fn.call(o[m].context,p,g);break;case 4:o[m].fn.call(o[m].context,p,g,y);break;default:if(!f)for(T=1,f=new Array(c-1);T<c;T++)f[T-1]=arguments[T];o[m].fn.apply(o[m].context,f)}}return!0},l.prototype.on=function(d,p,g){return a(this,d,p,g,!1)},l.prototype.once=function(d,p,g){return a(this,d,p,g,!0)},l.prototype.removeListener=function(d,p,g,y){var x=t?t+d:d;if(!this._events[x])return this;if(!p)return h(this,x),this;var v=this._events[x];if(v.fn)v.fn===p&&(!y||v.once)&&(!g||v.context===g)&&h(this,x);else{for(var _=0,o=[],c=v.length;_<c;_++)(v[_].fn!==p||y&&!v[_].once||g&&v[_].context!==g)&&o.push(v[_]);o.length?this._events[x]=o.length===1?o[0]:o:h(this,x)}return this},l.prototype.removeAllListeners=function(d){var p;return d?(p=t?t+d:d,this._events[p]&&h(this,p)):(this._events=new s,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=t,l.EventEmitter=l,r.exports=l}(ha)),ha.exports}var hy=ly(),Bo=M0(hy);const Vs="1.6.13",ys={};function cy(){return typeof __HLS_WORKER_BUNDLE__=="function"}function dy(){const r=ys[Vs];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 ys[Vs]=n,n}function uy(r){const e=ys[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 ys[r]=n,n}function fy(r){const e=ys[r||Vs];if(e&&e.clientCount--===1){const{worker:s,objectURL:n}=e;delete ys[r||Vs],n&&self.URL.revokeObjectURL(n),s.terminate()}}function zd(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 No(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 Rr(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 Ks(r,e){const t=e;let s=0;for(;No(r,e);){s+=10;const n=Rr(r,e+6);s+=n,zd(r,e+10)&&(s+=10),e+=s}if(s>0)return r.subarray(t,t+s)}function py(r,e,t,s){const n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],a=e[t+2],h=a>>2&15;if(h>12){const x=new Error(`invalid ADTS sampling index:${h}`);r.emit(E.ERROR,E.ERROR,{type:Z.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!0,error:x,reason:x.message});return}const l=(a>>6&3)+1,u=e[t+3]>>6&3|(a&1)<<2,d="mp4a.40."+l,p=n[h];let g=h;(l===5||l===29)&&(g-=3);const y=[l<<3|(g&14)>>1,(g&1)<<7|u<<3];return _e.log(`manifest codec:${s}, parsed codec:${d}, channels:${u}, rate:${p} (ADTS object type:${l} sampling index:${h})`),{config:y,samplerate:p,channelCount:u,codec:d,parsedCodec:d,manifestCodec:s}}function Hd(r,e){return r[e]===255&&(r[e+1]&246)===240}function Vd(r,e){return r[e+1]&1?7:9}function $o(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function gy(r,e){return e+5<r.length}function rr(r,e){return e+1<r.length&&Hd(r,e)}function my(r,e){return gy(r,e)&&Hd(r,e)&&$o(r,e)<=r.length-e}function yy(r,e){if(rr(r,e)){const t=Vd(r,e);if(e+t>=r.length)return!1;const s=$o(r,e);if(s<=t)return!1;const n=e+s;return n===r.length||rr(r,n)}return!1}function Kd(r,e,t,s,n){if(!r.samplerate){const a=py(e,t,s,n);if(!a)return;Ee(r,a)}}function Yd(r){return 1024*9e4/r}function vy(r,e){const t=Vd(r,e);if(e+t<=r.length){const s=$o(r,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function Wd(r,e,t,s,n){const a=Yd(r.samplerate),h=s+n*a,l=vy(e,t);let u;if(l){const{frameLength:g,headerLength:y}=l,x=y+g,v=Math.max(0,t+x-e.length);v?(u=new Uint8Array(x-y),u.set(e.subarray(t+y,e.length),0)):u=e.subarray(t+y,t+x);const _={unit:u,pts:h};return v||r.samples.push(_),{sample:_,length:x,missing:v}}const d=e.length-t;return u=new Uint8Array(d),u.set(e.subarray(t,e.length),0),{sample:{unit:u,pts:h},length:d,missing:-1}}function xy(r,e){return No(r,e)&&Rr(r,e+6)+10<=r.length-e}function Sy(r){return r instanceof ArrayBuffer?r:r.byteOffset==0&&r.byteLength==r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer}function ca(r,e=0,t=1/0){return _y(r,e,t,Uint8Array)}function _y(r,e,t,s){const n=Ey(r);let a=1;"BYTES_PER_ELEMENT"in s&&(a=s.BYTES_PER_ELEMENT);const h=Ty(r)?r.byteOffset:0,l=(h+r.byteLength)/a,u=(h+e)/a,d=Math.floor(Math.max(0,Math.min(u,l))),p=Math.floor(Math.min(d+Math.max(t,0),l));return new s(n,d,p-d)}function Ey(r){return r instanceof ArrayBuffer?r:r.buffer}function Ty(r){return r&&r.buffer instanceof ArrayBuffer&&r.byteLength!==void 0&&r.byteOffset!==void 0}function by(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 s=r.data.subarray(1).indexOf(0);if(s===-1)return;const n=dt(ca(r.data,1,s)),a=r.data[2+s],h=r.data.subarray(3+s).indexOf(0);if(h===-1)return;const l=dt(ca(r.data,3+s,h));let u;return n==="-->"?u=dt(ca(r.data,4+s+h)):u=Sy(r.data.subarray(4+s+h)),e.mimeType=n,e.pictureType=a,e.description=l,e.data=u,e}function Ay(r){if(r.size<2)return;const e=dt(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}}function Iy(r){if(r.size<2)return;if(r.type==="TXXX"){let t=1;const s=dt(r.data.subarray(t),!0);t+=s.length+1;const n=dt(r.data.subarray(t));return{key:r.type,info:s,data:n}}const e=dt(r.data.subarray(1));return{key:r.type,info:"",data:e}}function wy(r){if(r.type==="WXXX"){if(r.size<2)return;let t=1;const s=dt(r.data.subarray(t),!0);t+=s.length+1;const n=dt(r.data.subarray(t));return{key:r.type,info:s,data:n}}const e=dt(r.data);return{key:r.type,info:"",data:e}}function Ly(r){return r.type==="PRIV"?Ay(r):r.type[0]==="W"?wy(r):r.type==="APIC"?by(r):Iy(r)}function Ry(r){const e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=Rr(r,4),s=10;return{type:e,size:t,data:r.subarray(s,s+t)}}const yn=10,Cy=10;function jd(r){let e=0;const t=[];for(;No(r,e);){const s=Rr(r,e+6);r[e+5]>>6&1&&(e+=yn),e+=yn;const n=e+s;for(;e+Cy<n;){const a=Ry(r.subarray(e)),h=Ly(a);h&&t.push(h),e+=a.size+yn}zd(r,e)&&(e+=yn)}return t}function qd(r){return r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp"}function Py(r){if(r.data.byteLength===8){const e=new Uint8Array(r.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function Go(r){const e=jd(r);for(let t=0;t<e.length;t++){const s=e[t];if(qd(s))return Py(s)}}let ct=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 Pt(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class zo{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,s,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,s){}demux(e,t){this.cachedData&&(e=yt(this.cachedData,e),this.cachedData=null);let s=Ks(e,0),n=s?s.length:0,a;const h=this._audioTrack,l=this._id3Track,u=s?Go(s):void 0,d=e.length;for((this.basePTS===null||this.frameIndex===0&&q(u))&&(this.basePTS=Dy(u,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&l.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:ct.audioId3,duration:Number.POSITIVE_INFINITY});n<d;){if(this.canParse(e,n)){const p=this.appendFrame(h,e,n);p?(this.frameIndex++,this.lastPTS=p.sample.pts,n+=p.length,a=n):n=d}else xy(e,n)?(s=Ks(e,n),l.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:ct.audioId3,duration:Number.POSITIVE_INFINITY}),n+=s.length,a=n):n++;if(n===d&&a!==d){const p=e.slice(a);this.cachedData?this.cachedData=yt(this.cachedData,p):this.cachedData=p}}return{audioTrack:h,videoTrack:Pt(),id3Track:l,textTrack:Pt()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Pt(),id3Track:this._id3Track,textTrack:Pt()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Dy=(r,e,t)=>{if(q(r))return r*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let vn=null;const ky=[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],My=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Fy=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Uy=[0,1,1,4];function Xd(r,e,t,s,n){if(t+24>e.length)return;const a=Qd(e,t);if(a&&t+a.frameLength<=e.length){const h=a.samplesPerFrame*9e4/a.sampleRate,l=s+n*h,u={unit:e.subarray(t,t+a.frameLength),pts:l,dts:l};return r.config=[],r.channelCount=a.channelCount,r.samplerate=a.sampleRate,r.samples.push(u),{sample:u,length:a.frameLength,missing:0}}}function Qd(r,e){const t=r[e+1]>>3&3,s=r[e+1]>>1&3,n=r[e+2]>>4&15,a=r[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&a!==3){const h=r[e+2]>>1&1,l=r[e+3]>>6,u=t===3?3-s:s===3?3:4,d=ky[u*14+n-1]*1e3,g=My[(t===3?0:t===2?1:2)*3+a],y=l===3?1:2,x=Fy[t][s],v=Uy[s],_=x*8*v,o=Math.floor(x*d/g+h)*v;if(vn===null){const m=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);vn=m?parseInt(m[1]):0}return!!vn&&vn<=87&&s===2&&d>=224e3&&l===0&&(r[e+3]=r[e+3]|128),{sampleRate:g,channelCount:y,frameLength:o,samplesPerFrame:_}}}function Ho(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function Zd(r,e){return e+1<r.length&&Ho(r,e)}function Oy(r,e){return Ho(r,e)&&4<=r.length-e}function Jd(r,e){if(e+1<r.length&&Ho(r,e)){const s=Qd(r,e);let n=4;s!=null&&s.frameLength&&(n=s.frameLength);const a=e+n;return a===r.length||Zd(r,a)}return!1}class By extends zo{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,n){super.resetInitSegment(e,t,s,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 s=Ks(e,0);let n=(s==null?void 0:s.length)||0;if(Jd(e,n))return!1;for(let a=e.length;n<a;n++)if(yy(e,n))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return my(e,t)}appendFrame(e,t,s){Kd(e,this.observer,t,s,e.manifestCodec);const n=Wd(e,t,s,this.basePTS,this.frameIndex);if(n&&n.missing===0)return n}}const eu=(r,e)=>{let t=0,s=5;e+=s;const n=new Uint32Array(1),a=new Uint32Array(1),h=new Uint8Array(1);for(;s>0;){h[0]=r[e];const l=Math.min(s,8),u=8-l;a[0]=4278190080>>>24+u<<u,n[0]=(h[0]&a[0])>>u,t=t?t<<l|n[0]:n[0],e+=1,s-=l}return t};class Ny extends zo{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,n){super.resetInitSegment(e,t,s,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,s){const n=tu(e,t,s,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=Ks(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&Go(t)!==void 0&&eu(e,s)<16}}function tu(r,e,t,s,n){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const a=e[t+4]>>6;if(a>=3)return-1;const l=[48e3,44100,32e3][a],u=e[t+4]&63,p=[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][u*3+a]*2;if(t+p>e.length)return-1;const g=e[t+6]>>5;let y=0;g===2?y+=2:(g&1&&g!==1&&(y+=2),g&4&&(y+=2));const x=(e[t+6]<<8|e[t+7])>>12-y&1,_=[2,1,2,3,3,4,4,5][g]+x,o=e[t+5]>>3,c=e[t+5]&7,f=new Uint8Array([a<<6|o<<1|c>>2,(c&3)<<6|g<<3|x<<2|u>>4,u<<4&224]),m=1536/l*9e4,S=s+n*m,T=e.subarray(t,t+p);return r.config=f,r.channelCount=_,r.samplerate=l,r.samples.push({unit:T,pts:S}),p}class $y extends zo{resetInitSegment(e,t,s,n){super.resetInitSegment(e,t,s,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=Ks(e,0);let s=(t==null?void 0:t.length)||0;if(t&&e[s]===11&&e[s+1]===119&&Go(t)!==void 0&&eu(e,s)<=16)return!1;for(let n=e.length;s<n;s++)if(Jd(e,s))return _e.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Oy(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return Xd(e,t,s,this.basePTS,this.frameIndex)}}const Gy=/\/emsg[-/]ID3/i;class zy{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,s,n){const a=this.videoTrack=Pt("video",1),h=this.audioTrack=Pt("audio",1),l=this.txtTrack=Pt("text",1);if(this.id3Track=Pt("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const u=dd(e);if(u.video){const{id:d,timescale:p,codec:g,supplemental:y}=u.video;a.id=d,a.timescale=l.timescale=p,a.codec=g,a.supplemental=y}if(u.audio){const{id:d,timescale:p,codec:g}=u.audio;h.id=d,h.timescale=p,h.codec=g}l.id=ld.text,a.sampleDuration=0,a.duration=h.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return N0(e)}demux(e,t){this.timeOffset=t;let s=e;const n=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=yt(this.remainderData,e));const l=Y0(s);this.remainderData=l.remainder,n.samples=l.valid||new Uint8Array}else n.samples=s;const h=this.extractID3Track(n,t);return a.samples=$l(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:h,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);return s.samples=$l(e,t),{videoTrack:t,audioTrack:Pt(),id3Track:n,textTrack:Pt()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const n=de(e.samples,["emsg"]);n&&n.forEach(a=>{const h=j0(a);if(Gy.test(h.schemeIdUri)){const l=Th(h,t);let u=h.eventDuration===4294967295?Number.POSITIVE_INFINITY:h.eventDuration/h.timeScale;u<=.001&&(u=Number.POSITIVE_INFINITY);const d=h.payload;s.samples.push({data:d,len:d.byteLength,dts:l,pts:l,type:ct.emsg,duration:u})}else if(this.config.enableEmsgKLVMetadata&&h.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const l=Th(h,t);s.samples.push({data:h.payload,len:h.payload.byteLength,dts:l,pts:l,type:ct.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){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 Th(r,e){return q(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale}class Hy{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new ko(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,_i.cbc)}decryptAacSample(e,t,s){const n=e[t].unit;if(n.length<=16)return;const a=n.subarray(16,n.length-n.length%16),h=a.buffer.slice(a.byteOffset,a.byteOffset+a.length);this.decryptBuffer(h).then(l=>{const u=new Uint8Array(l);n.set(u,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let n=0;for(let a=32;a<e.length-16;a+=160,n+=16)s.set(e.subarray(a,a+16),n);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let n=0;for(let a=32;a<e.length-16;a+=160,n+=16)e.set(s.subarray(n,n+16),a);return e}decryptAvcSample(e,t,s,n,a){const h=pd(a.data),l=this.getAvcEncryptedData(h);this.decryptBuffer(l.buffer).then(u=>{a.data=this.getAvcDecryptedUnit(h,u),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,n)}).catch(n)}decryptAvcSamples(e,t,s,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){n();return}const a=e[t].units;for(;!(s>=a.length);s++){const h=a[s];if(!(h.data.length<=48||h.type!==1&&h.type!==5)&&(this.decryptAvcSample(e,t,s,n,h),!this.decrypter.isSync()))return}}}}class iu{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,n;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const a=s.units;n=a[a.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,n=s.length;if(n){const a=s[n-1];e.pts=a.pts,e.dts=a.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const n=t.byteLength;let a=e.naluState||0;const h=a,l=[];let u=0,d,p,g,y=-1,x=0;for(a===-1&&(y=0,x=this.getNALuType(t,0),a=0,u=1);u<n;){if(d=t[u++],!a){a=d?0:1;continue}if(a===1){a=d?0:2;continue}if(!d)a=3;else if(d===1){if(p=u-a-1,y>=0){const v={data:t.subarray(y,p),type:x};l.push(v)}else{const v=this.getLastNalUnit(e.samples);v&&(h&&u<=4-h&&v.state&&(v.data=v.data.subarray(0,v.data.byteLength-h)),p>0&&(v.data=yt(v.data,t.subarray(0,p)),v.state=0))}u<n?(g=this.getNALuType(t,u),y=u,x=g,a=0):a=-1}else a=0}if(y>=0&&a>=0){const v={data:t.subarray(y,n),type:x,state:a};l.push(v)}if(l.length===0){const v=this.getLastNalUnit(e.samples);v&&(v.data=yt(v.data,t))}return e.naluState=a,l}}class Fs{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,s=e.byteLength-t,n=new Uint8Array(4),a=Math.min(4,t);if(a===0)throw new Error("no bytes available");n.set(e.subarray(s,s+a)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=a*8,this.bytesAvailable-=a}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 s=this.word>>>32-t;if(e>32&&_e.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?s<<t|this.readBits(t):s}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 Vy extends iu{parsePES(e,t,s,n){const a=this.parseNALu(e,s.data,n);let h=this.VideoSample,l,u=!1;s.data=null,h&&a.length&&!e.audFound&&(this.pushAccessUnit(h,e),h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.forEach(d=>{var p,g;switch(d.type){case 1:{let _=!1;l=!0;const o=d.data;if(u&&o.length>4){const c=this.readSliceType(o);(c===2||c===4||c===7||c===9)&&(_=!0)}if(_){var y;(y=h)!=null&&y.frame&&!h.key&&(this.pushAccessUnit(h,e),h=this.VideoSample=null)}h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.frame=!0,h.key=_;break}case 5:l=!0,(p=h)!=null&&p.frame&&!h.key&&(this.pushAccessUnit(h,e),h=this.VideoSample=null),h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.key=!0,h.frame=!0;break;case 6:{l=!0,Ro(d.data,1,s.pts,t.samples);break}case 7:{var x,v;l=!0,u=!0;const _=d.data,o=this.readSPS(_);if(!e.sps||e.width!==o.width||e.height!==o.height||((x=e.pixelRatio)==null?void 0:x[0])!==o.pixelRatio[0]||((v=e.pixelRatio)==null?void 0:v[1])!==o.pixelRatio[1]){e.width=o.width,e.height=o.height,e.pixelRatio=o.pixelRatio,e.sps=[_];const c=_.subarray(1,4);let f="avc1.";for(let m=0;m<3;m++){let S=c[m].toString(16);S.length<2&&(S="0"+S),f+=S}e.codec=f}break}case 8:l=!0,e.pps=[d.data];break;case 9:l=!0,e.audFound=!0,(g=h)!=null&&g.frame&&(this.pushAccessUnit(h,e),h=null),h||(h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:l=!0;break;default:l=!1;break}h&&l&&h.units.push(d)}),n&&h&&(this.pushAccessUnit(h,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Fs(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,n=8,a;for(let h=0;h<e;h++)n!==0&&(a=t.readEG(),n=(s+a+256)%256),s=n===0?s:n}readSPS(e){const t=new Fs(e);let s=0,n=0,a=0,h=0,l,u,d;const p=t.readUByte.bind(t),g=t.readBits.bind(t),y=t.readUEG.bind(t),x=t.readBoolean.bind(t),v=t.skipBits.bind(t),_=t.skipEG.bind(t),o=t.skipUEG.bind(t),c=this.skipScalingList.bind(this);p();const f=p();if(g(5),v(3),p(),o(),f===100||f===110||f===122||f===244||f===44||f===83||f===86||f===118||f===128){const I=y();if(I===3&&v(1),o(),o(),v(1),x())for(u=I!==3?8:12,d=0;d<u;d++)x()&&(d<6?c(16,t):c(64,t))}o();const m=y();if(m===0)y();else if(m===1)for(v(1),_(),_(),l=y(),d=0;d<l;d++)_();o(),v(1);const S=y(),T=y(),b=g(1);b===0&&v(1),v(1),x()&&(s=y(),n=y(),a=y(),h=y());let A=[1,1];if(x()&&x())switch(p()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:{A=[p()<<8|p(),p()<<8|p()];break}}return{width:Math.ceil((S+1)*16-s*2-n*2),height:(2-b)*(T+1)*16-(b?2:4)*(a+h),pixelRatio:A}}}class Ky extends iu{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,n){const a=this.parseNALu(e,s.data,n);let h=this.VideoSample,l,u=!1;s.data=null,h&&a.length&&!e.audFound&&(this.pushAccessUnit(h,e),h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.forEach(d=>{var p,g;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:h||(h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),h.frame=!0,l=!0;break;case 16:case 17:case 18:case 21:if(l=!0,u){var y;(y=h)!=null&&y.frame&&!h.key&&(this.pushAccessUnit(h,e),h=this.VideoSample=null)}h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.key=!0,h.frame=!0;break;case 19:case 20:l=!0,(p=h)!=null&&p.frame&&!h.key&&(this.pushAccessUnit(h,e),h=this.VideoSample=null),h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.key=!0,h.frame=!0;break;case 39:l=!0,Ro(d.data,2,s.pts,t.samples);break;case 32:l=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Ee(e.params,this.readVPS(d.data)),this.initVPS=d.data),e.vps=[d.data];break;case 33:if(l=!0,u=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],d.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const x=this.readSPS(d.data);e.width=x.width,e.height=x.height,e.pixelRatio=x.pixelRatio,e.codec=x.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const v in x.params)e.params[v]=x.params[v]}this.pushParameterSet(e.sps,d.data,e.vps),h||(h=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),h.key=!0;break;case 34:if(l=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const x=this.readPPS(d.data);for(const v in x)e.params[v]=x[v]}this.pushParameterSet(e.pps,d.data,e.vps)}break;case 35:l=!0,e.audFound=!0,(g=h)!=null&&g.frame&&(this.pushAccessUnit(h,e),h=null),h||(h=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:l=!1;break}h&&l&&h.units.push(d)}),n&&h&&(this.pushAccessUnit(h,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let n=0;n<e.byteLength;n++)n>=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[s]=e[n],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Fs(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:n}}readSPS(e){const t=new Fs(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const n=t.readBits(2),a=t.readBoolean(),h=t.readBits(5),l=t.readUByte(),u=t.readUByte(),d=t.readUByte(),p=t.readUByte(),g=t.readUByte(),y=t.readUByte(),x=t.readUByte(),v=t.readUByte(),_=t.readUByte(),o=t.readUByte(),c=t.readUByte(),f=[],m=[];for(let ge=0;ge<s;ge++)f.push(t.readBoolean()),m.push(t.readBoolean());if(s>0)for(let ge=s;ge<8;ge++)t.readBits(2);for(let ge=0;ge<s;ge++)f[ge]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),m[ge]&&t.readUByte();t.readUEG();const S=t.readUEG();S==3&&t.skipBits(1);const T=t.readUEG(),b=t.readUEG(),A=t.readBoolean();let I=0,L=0,w=0,R=0;A&&(I+=t.readUEG(),L+=t.readUEG(),w+=t.readUEG(),R+=t.readUEG());const M=t.readUEG(),k=t.readUEG(),z=t.readUEG(),O=t.readBoolean();for(let ge=O?0:s;ge<=s;ge++)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 We=0;We<4;We++)for(let gt=0;gt<(We===3?2:6);gt++)if(!t.readBoolean())t.readUEG();else{const St=Math.min(64,1<<4+(We<<1));We>1&&t.readEG();for(let Wi=0;Wi<St;Wi++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const H=t.readUEG();let V=0;for(let ge=0;ge<H;ge++){let We=!1;if(ge!==0&&(We=t.readBoolean()),We){ge===H&&t.readUEG(),t.readBoolean(),t.readUEG();let gt=0;for(let wi=0;wi<=V;wi++){const St=t.readBoolean();let Wi=!1;St||(Wi=t.readBoolean()),(St||Wi)&>++}V=gt}else{const gt=t.readUEG(),wi=t.readUEG();V=gt+wi;for(let St=0;St<gt;St++)t.readUEG(),t.readBoolean();for(let St=0;St<wi;St++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const ge=t.readUEG();for(let We=0;We<ge;We++){for(let gt=0;gt<z+4;gt++)t.readBits(1);t.readBits(1)}}let $=0,G=1,ie=1,ce=!0,K=1,ue=0;t.readBoolean(),t.readBoolean();let Ce=!1;if(t.readBoolean()){if(t.readBoolean()){const Li=t.readUByte(),Qo=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],an=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Li>0&&Li<16?(G=Qo[Li-1],ie=an[Li-1]):Li===255&&(G=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(),Ce=t.readBoolean(),Ce&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(K=t.readBits(32),ue=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const an=t.readBoolean(),Zo=t.readBoolean();let bs=!1;(an||Zo)&&(bs=t.readBoolean(),bs&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),bs&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Jo=0;Jo<=s;Jo++){ce=t.readBoolean();const Vu=ce||t.readBoolean();let el=!1;Vu?t.readEG():el=t.readBoolean();const tl=el?1:t.readUEG()+1;if(an)for(let As=0;As<tl;As++)t.readUEG(),t.readUEG(),bs&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Zo)for(let As=0;As<tl;As++)t.readUEG(),t.readUEG(),bs&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),$=t.readUEG())}let pt=T,wt=b;if(A){let ge=1,We=1;S===1?ge=We=2:S==2&&(ge=2),pt=T-ge*L-ge*I,wt=b-We*R-We*w}const Ii=n?["A","B","C"][n]:"",Hu=l<<24|u<<16|d<<8|p;let Pr=0;for(let ge=0;ge<32;ge++)Pr=(Pr|(Hu>>ge&1)<<31-ge)>>>0;let Dr=Pr.toString(16);return h===1&&Dr==="2"&&(Dr="6"),{codecString:`hvc1.${Ii}${h}.${Dr}.${a?"H":"L"}${c}.B0`,params:{general_tier_flag:a,general_profile_idc:h,general_profile_space:n,general_profile_compatibility_flags:[l,u,d,p],general_constraint_indicator_flags:[g,y,x,v,_,o],general_level_idc:c,bit_depth:M+8,bit_depth_luma_minus8:M,bit_depth_chroma_minus8:k,min_spatial_segmentation_idc:$,chroma_format_idc:S,frame_rate:{fixed:ce,fps:ue/K}},width:pt,height:wt,pixelRatio:[G,ie]}}readPPS(e){const t=new Fs(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(),a=t.readBoolean();let h=1;return a&&n?h=0:a?h=3:n&&(h=2),{parallelismType:h}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Ne=188;class ui{constructor(e,t,s,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=s,this.logger=n,this.videoParser=null}static probe(e,t){const s=ui.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(Ne*5,t-Ne)+1,n=0;for(;n<s;){let a=!1,h=-1,l=0;for(let u=n;u<t;u+=Ne)if(e[u]===71&&(t-u===Ne||e[u+Ne]===71)){if(l++,h===-1&&(h=u,h!==0&&(s=Math.min(h+Ne*99,e.length-Ne)+1)),a||(a=Xa(e,u)===0),a&&l>1&&(h===0&&l>2||u+Ne>s))return h}else{if(l)return-1;break}n++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:ld[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=ui.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=ui.createTrack("audio",n),this._id3Track=ui.createTrack("id3"),this._txtTrack=ui.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,n=!1){s||(this.sampleAes=null);let a;const h=this._videoTrack,l=this._audioTrack,u=this._id3Track,d=this._txtTrack;let p=h.pid,g=h.pesData,y=l.pid,x=u.pid,v=l.pesData,_=u.pesData,o=null,c=this.pmtParsed,f=this._pmtId,m=e.length;if(this.remainderData&&(e=yt(this.remainderData,e),m=e.length,this.remainderData=null),m<Ne&&!n)return this.remainderData=e,{audioTrack:l,videoTrack:h,id3Track:u,textTrack:d};const S=Math.max(0,ui.syncOffset(e));m-=(m-S)%Ne,m<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,m,e.buffer.byteLength-m));let T=0;for(let A=S;A<m;A+=Ne)if(e[A]===71){const I=!!(e[A+1]&64),L=Xa(e,A),w=(e[A+3]&48)>>4;let R;if(w>1){if(R=A+5+e[A+4],R===A+Ne)continue}else R=A+4;switch(L){case p:I&&(g&&(a=Xi(g,this.logger))&&(this.readyVideoParser(h.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(h,d,a,!1)),g={data:[],size:0}),g&&(g.data.push(e.subarray(R,A+Ne)),g.size+=A+Ne-R);break;case y:if(I){if(v&&(a=Xi(v,this.logger)))switch(l.segmentCodec){case"aac":this.parseAACPES(l,a);break;case"mp3":this.parseMPEGPES(l,a);break;case"ac3":this.parseAC3PES(l,a);break}v={data:[],size:0}}v&&(v.data.push(e.subarray(R,A+Ne)),v.size+=A+Ne-R);break;case x:I&&(_&&(a=Xi(_,this.logger))&&this.parseID3PES(u,a),_={data:[],size:0}),_&&(_.data.push(e.subarray(R,A+Ne)),_.size+=A+Ne-R);break;case 0:I&&(R+=e[R]+1),f=this._pmtId=Yy(e,R);break;case f:{I&&(R+=e[R]+1);const M=Wy(e,R,this.typeSupported,s,this.observer,this.logger);p=M.videoPid,p>0&&(h.pid=p,h.segmentCodec=M.segmentVideoCodec),y=M.audioPid,y>0&&(l.pid=y,l.segmentCodec=M.segmentAudioCodec),x=M.id3Pid,x>0&&(u.pid=x),o!==null&&!c&&(this.logger.warn(`MPEG-TS PMT found at ${A} after unknown PID '${o}'. Backtracking to sync byte @${S} to parse all TS packets.`),o=null,A=S-188),c=this.pmtParsed=!0;break}case 17:case 8191:break;default:o=L;break}}else T++;T>0&&Qa(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),h.pesData=g,l.pesData=v,u.pesData=_;const b={audioTrack:l,videoTrack:h,id3Track:u,textTrack:d};return n&&this.extractRemainingSamples(b),b}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:s,id3Track:n,textTrack:a}=e,h=s.pesData,l=t.pesData,u=n.pesData;let d;if(h&&(d=Xi(h,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,a,d,!0),s.pesData=null)):s.pesData=h,l&&(d=Xi(l,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,d);break;case"mp3":this.parseMPEGPES(t,d);break;case"ac3":this.parseAC3PES(t,d);break}t.pesData=null}else l!=null&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=l;u&&(d=Xi(u,this.logger))?(this.parseID3PES(n,d),n.pesData=null):n.pesData=u}demuxSampleAes(e,t,s){const n=this.demux(e,s,!0,!this.config.progressive),a=this.sampleAes=new Hy(this.observer,this.config,t);return this.decrypt(n,a)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Vy:e==="hevc"&&(this.videoParser=new Ky))}decrypt(e,t){return new Promise(s=>{const{audioTrack:n,videoTrack:a}=e;n.samples&&n.segmentCodec==="aac"?t.decryptAacSamples(n.samples,0,()=>{a.samples?t.decryptAvcSamples(a.samples,0,0,()=>{s(e)}):s(e)}):a.samples&&t.decryptAvcSamples(a.samples,0,0,()=>{s(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 s=0;const n=this.aacOverFlow;let a=t.data;if(n){this.aacOverFlow=null;const g=n.missing,y=n.sample.unit.byteLength;if(g===-1)a=yt(n.sample.unit,a);else{const x=y-g;n.sample.unit.set(a.subarray(0,g),x),e.samples.push(n.sample),s=n.missing}}let h,l;for(h=s,l=a.length;h<l-1&&!rr(a,h);h++);if(h!==s){let g;const y=h<l-1;if(y?g=`AAC PES did not start with ADTS header,offset:${h}`:g="No ADTS header found in AAC PES",Qa(this.observer,new Error(g),y,this.logger),!y)return}Kd(e,this.observer,a,h,this.audioCodec);let u;if(t.pts!==void 0)u=t.pts;else if(n){const g=Yd(e.samplerate);u=n.sample.pts+g}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let d=0,p;for(;h<l;)if(p=Wd(e,a,h,u,d),h+=p.length,p.missing){this.aacOverFlow=p;break}else for(d++;h<l-1&&!rr(a,h);h++);}parseMPEGPES(e,t){const s=t.data,n=s.length;let a=0,h=0;const l=t.pts;if(l===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;h<n;)if(Zd(s,h)){const u=Xd(e,s,h,l,a);if(u)h+=u.length,a++;else break}else h++}parseAC3PES(e,t){{const s=t.data,n=t.pts;if(n===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const a=s.length;let h=0,l=0,u;for(;l<a&&(u=tu(e,s,l,n,h++))>0;)l+=u}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=Ee({},t,{type:this._videoTrack?ct.emsg:ct.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Xa(r,e){return((r[e+1]&31)<<8)+r[e+2]}function Yy(r,e){return(r[e+10]&31)<<8|r[e+11]}function Wy(r,e,t,s,n,a){const h={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},l=(r[e+1]&15)<<8|r[e+2],u=e+3+l-4,d=(r[e+10]&15)<<8|r[e+11];for(e+=12+d;e<u;){const p=Xa(r,e),g=(r[e+3]&15)<<8|r[e+4];switch(r[e]){case 207:if(!s){da("ADTS AAC",a);break}case 15:h.audioPid===-1&&(h.audioPid=p);break;case 21:h.id3Pid===-1&&(h.id3Pid=p);break;case 219:if(!s){da("H.264",a);break}case 27:h.videoPid===-1&&(h.videoPid=p);break;case 3:case 4:!t.mpeg&&!t.mp3?a.log("MPEG audio found, not supported in this browser"):h.audioPid===-1&&(h.audioPid=p,h.segmentAudioCodec="mp3");break;case 193:if(!s){da("AC-3",a);break}case 129:t.ac3?h.audioPid===-1&&(h.audioPid=p,h.segmentAudioCodec="ac3"):a.log("AC-3 audio found, not supported in this browser");break;case 6:if(h.audioPid===-1&&g>0){let y=e+5,x=g;for(;x>2;){switch(r[y]){case 106:t.ac3!==!0?a.log("AC-3 audio found, not supported in this browser for now"):(h.audioPid=p,h.segmentAudioCodec="ac3");break}const _=r[y+1]+2;y+=_,x-=_}}break;case 194:case 135:return Qa(n,new Error("Unsupported EC-3 in M2TS found"),void 0,a),h;case 36:h.videoPid===-1&&(h.videoPid=p,h.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"));break}e+=g+5}return h}function Qa(r,e,t,s){s.warn(`parsing error: ${e.message}`),r.emit(E.ERROR,E.ERROR,{type:Z.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function da(r,e){e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function Xi(r,e){let t=0,s,n,a,h,l;const u=r.data;if(!r||r.size===0)return null;for(;u[0].length<19&&u.length>1;)u[0]=yt(u[0],u[1]),u.splice(1,1);if(s=u[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(n=(s[4]<<8)+s[5],n&&n>r.size-6)return null;const p=s[7];p&192&&(h=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,p&64?(l=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,h-l>60*9e4&&(e.warn(`${Math.round((h-l)/9e4)}s delta between PTS and DTS, align them`),h=l)):l=h),a=s[8];let g=a+9;if(r.size<=g)return null;r.size-=g;const y=new Uint8Array(r.size);for(let x=0,v=u.length;x<v;x++){s=u[x];let _=s.byteLength;if(g)if(g>_){g-=_;continue}else s=s.subarray(g),_-=g,g=0;y.set(s,t),t+=_}return n&&(n-=a+3),{data:y,pts:h,dts:l,len:n}}return null}class jy{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 oi=Math.pow(2,32)-1;class P{static init(){P.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 P.types)P.types.hasOwnProperty(e)&&(P.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]),s=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]);P.HDLR_TYPES={video:t,audio:s};const n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),a=new Uint8Array([0,0,0,0,0,0,0,0]);P.STTS=P.STSC=P.STCO=a,P.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),P.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),P.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),P.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const h=new Uint8Array([105,115,111,109]),l=new Uint8Array([97,118,99,49]),u=new Uint8Array([0,0,0,1]);P.FTYP=P.box(P.types.ftyp,h,u,h,l),P.DINF=P.box(P.types.dinf,P.box(P.types.dref,n))}static box(e,...t){let s=8,n=t.length;const a=n;for(;n--;)s+=t[n].byteLength;const h=new Uint8Array(s);for(h[0]=s>>24&255,h[1]=s>>16&255,h[2]=s>>8&255,h[3]=s&255,h.set(e,4),n=0,s=8;n<a;n++)h.set(t[n],s),s+=t[n].byteLength;return h}static hdlr(e){return P.box(P.types.hdlr,P.HDLR_TYPES[e])}static mdat(e){return P.box(P.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(oi+1)),n=Math.floor(t%(oi+1));return P.box(P.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,s>>24,s>>16&255,s>>8&255,s&255,n>>24,n>>16&255,n>>8&255,n&255,85,196,0,0]))}static mdia(e){return P.box(P.types.mdia,P.mdhd(e.timescale||0,e.duration||0),P.hdlr(e.type),P.minf(e))}static mfhd(e){return P.box(P.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"?P.box(P.types.minf,P.box(P.types.smhd,P.SMHD),P.DINF,P.stbl(e)):P.box(P.types.minf,P.box(P.types.vmhd,P.VMHD),P.DINF,P.stbl(e))}static moof(e,t,s){return P.box(P.types.moof,P.mfhd(e),P.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=P.trak(e[t]);return P.box.apply(null,[P.types.moov,P.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(P.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=P.trex(e[t]);return P.box.apply(null,[P.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(oi+1)),n=Math.floor(t%(oi+1)),a=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,s>>24,s>>16&255,s>>8&255,s&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 P.box(P.types.mvhd,a)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let n,a;for(n=0;n<t.length;n++)a=t[n].flags,s[n+4]=a.dependsOn<<4|a.isDependedOn<<2|a.hasRedundancy;return P.box(P.types.sdtp,s)}static stbl(e){return P.box(P.types.stbl,P.stsd(e),P.box(P.types.stts,P.STTS),P.box(P.types.stsc,P.STSC),P.box(P.types.stsz,P.STSZ),P.box(P.types.stco,P.STCO))}static avc1(e){let t=[],s=[],n,a,h;for(n=0;n<e.sps.length;n++)a=e.sps[n],h=a.byteLength,t.push(h>>>8&255),t.push(h&255),t=t.concat(Array.prototype.slice.call(a));for(n=0;n<e.pps.length;n++)a=e.pps[n],h=a.byteLength,s.push(h>>>8&255),s.push(h&255),s=s.concat(Array.prototype.slice.call(a));const l=P.box(P.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),u=e.width,d=e.height,p=e.pixelRatio[0],g=e.pixelRatio[1];return P.box(P.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,u>>8&255,u&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,P.box(P.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),P.box(P.types.pasp,new Uint8Array([p>>24,p>>16&255,p>>8&255,p&255,g>>24,g>>16&255,g>>8&255,g&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 P.box(P.types.mp4a,P.audioStsd(e),P.box(P.types.esds,P.esds(e)))}static mp3(e){return P.box(P.types[".mp3"],P.audioStsd(e))}static ac3(e){return P.box(P.types["ac-3"],P.audioStsd(e),P.box(P.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return P.box(P.types.stsd,P.STSD,P.mp4a(e));if(t==="ac3"&&e.config)return P.box(P.types.stsd,P.STSD,P.ac3(e));if(t==="mp3"&&e.codec==="mp3")return P.box(P.types.stsd,P.STSD,P.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return P.box(P.types.stsd,P.STSD,P.avc1(e));if(t==="hevc"&&e.vps)return P.box(P.types.stsd,P.STSD,P.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,s=(e.duration||0)*(e.timescale||0),n=e.width||0,a=e.height||0,h=Math.floor(s/(oi+1)),l=Math.floor(s%(oi+1));return P.box(P.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,h>>24,h>>16&255,h>>8&255,h&255,l>>24,l>>16&255,l>>8&255,l&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,a>>8&255,a&255,0,0]))}static traf(e,t){const s=P.sdtp(e),n=e.id,a=Math.floor(t/(oi+1)),h=Math.floor(t%(oi+1));return P.box(P.types.traf,P.box(P.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),P.box(P.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,h>>24,h>>16&255,h>>8&255,h&255])),P.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,P.box(P.types.trak,P.tkhd(e),P.mdia(e))}static trex(e){const t=e.id;return P.box(P.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 s=e.samples||[],n=s.length,a=12+16*n,h=new Uint8Array(a);let l,u,d,p,g,y;for(t+=8+a,h.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),l=0;l<n;l++)u=s[l],d=u.duration,p=u.size,g=u.flags,y=u.cts,h.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,p>>>24&255,p>>>16&255,p>>>8&255,p&255,g.isLeading<<2|g.dependsOn,g.isDependedOn<<6|g.hasRedundancy<<4|g.paddingValue<<1|g.isNonSync,g.degradPrio&61440,g.degradPrio&15,y>>>24&255,y>>>16&255,y>>>8&255,y&255],12+16*l);return P.box(P.types.trun,h)}static initSegment(e){P.types||P.init();const t=P.moov(e);return yt(P.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],n=4,a=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),s.length]);let h=a.length;for(let v=0;v<s.length;v+=1){h+=3;for(let _=0;_<s[v].length;_+=1)h+=2+s[v][_].length}const l=new Uint8Array(h);l.set(a,0),h=a.length;const u=s.length-1;for(let v=0;v<s.length;v+=1){l.set(new Uint8Array([32+v|(v===u?128:0),0,s[v].length]),h),h+=3;for(let _=0;_<s[v].length;_+=1)l.set(new Uint8Array([s[v][_].length>>8,s[v][_].length&255]),h),h+=2,l.set(s[v][_],h),h+=s[v][_].length}const d=P.box(P.types.hvcC,l),p=e.width,g=e.height,y=e.pixelRatio[0],x=e.pixelRatio[1];return P.box(P.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,p>>8&255,p&255,g>>8&255,g&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,P.box(P.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),P.box(P.types.pasp,new Uint8Array([y>>24,y>>16&255,y>>8&255,y&255,x>>24,x>>16&255,x>>8&255,x&255])))}}P.types=void 0;P.HDLR_TYPES=void 0;P.STTS=void 0;P.STSC=void 0;P.STCO=void 0;P.STSZ=void 0;P.VMHD=void 0;P.SMHD=void 0;P.STSD=void 0;P.FTYP=void 0;P.DINF=void 0;const su=9e4;function Vo(r,e,t=1,s=!1){const n=r*e*t;return s?Math.round(n):n}function qy(r,e,t=1,s=!1){return Vo(r,e,1/t,s)}function ws(r,e=!1){return Vo(r,1e3,1/su,e)}function Xy(r,e=1){return Vo(r,su,1/e)}function bh(r){const{baseTime:e,timescale:t,trackId:s}=r;return`${e/t} (${e}/${t}) trackId: ${s}`}const Qy=10*1e3,Zy=1024,Jy=1152,ev=1536;let Qi=null,ua=null;function Ah(r,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:r?2:1,isNonSync:r?0:1}}}class On extends xt{constructor(e,t,s,n){if(super("mp4-remuxer",n),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,Qi===null){const h=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Qi=h?parseInt(h[1]):0}if(ua===null){const a=navigator.userAgent.match(/Safari\/(\d+)/i);ua=a?parseInt(a[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&bh(t)} > ${e&&bh(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,n=e.reduce((a,h)=>{let l=h.pts,u=l-a;return u<-4294967296&&(t=!0,l=lt(l,s),u=l-a),u>0?a:l},s);return t&&this.debug("PTS rollover detected"),n}remux(e,t,s,n,a,h,l,u){let d,p,g,y,x,v,_=a,o=a;const c=e.pid>-1,f=t.pid>-1,m=t.samples.length,S=e.samples.length>0,T=l&&m>0||m>1;if((!c||S)&&(!f||T)||this.ISGenerated||l){if(this.ISGenerated){var A,I,L,w;const z=this.videoTrackConfig;(z&&(t.width!==z.width||t.height!==z.height||((A=t.pixelRatio)==null?void 0:A[0])!==((I=z.pixelRatio)==null?void 0:I[0])||((L=t.pixelRatio)==null?void 0:L[1])!==((w=z.pixelRatio)==null?void 0:w[1]))||!z&&T||this.nextAudioTs===null&&S)&&this.resetInitSegment()}this.ISGenerated||(g=this.generateIS(e,t,a,h));const R=this.isVideoContiguous;let M=-1,k;if(T&&(M=tv(t.samples),!R&&this.config.forceKeyFrameOnDiscontinuity))if(v=!0,M>0){this.warn(`Dropped ${M} out of ${m} video samples due to a missing keyframe`);const z=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(M),t.dropped+=M,o+=(t.samples[0].pts-z)/t.inputTimeScale,k=o}else M===-1&&(this.warn(`No keyframe found out of ${m} video samples`),v=!1);if(this.ISGenerated){if(S&&T){const z=this.getVideoStartPts(t.samples),U=(lt(e.samples[0].pts,z)-z)/t.inputTimeScale;_+=Math.max(0,U),o+=Math.max(0,-U)}if(S){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),g=this.generateIS(e,t,a,h)),p=this.remuxAudio(e,_,this.isAudioContiguous,h,f||T||u===X.AUDIO?o:void 0),T){const z=p?p.endPTS-p.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),g=this.generateIS(e,t,a,h)),d=this.remuxVideo(t,o,R,z)}}else T&&(d=this.remuxVideo(t,o,R,0));d&&(d.firstKeyFrame=M,d.independent=M!==-1,d.firstKeyFramePTS=k)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(x=nu(s,a,this._initPTS,this._initDTS)),n.samples.length&&(y=ru(n,a,this._initPTS))),{audio:p,video:d,initSegment:g,independent:v,text:y,id3:x}}computeInitPts(e,t,s,n){const a=Math.round(s*t);let h=lt(e,a);if(h<a+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(a-h)/t} ${n}`);h<a+t;)h+=8589934592;return h-a}generateIS(e,t,s,n){const a=e.samples,h=t.samples,l=this.typeSupported,u={},d=this._initPTS;let p=!d||n,g="audio/mp4",y,x,v,_=-1;if(p&&(y=x=1/0),e.config&&a.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":l.mpeg?(g="audio/mpeg",e.codec=""):l.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}u.audio={id:"audio",container:g,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&l.mpeg?new Uint8Array(0):P.initSegment([e]),metadata:{channelCount:e.channelCount}},p&&(_=e.id,v=e.inputTimeScale,!d||v!==d.timescale?y=x=this.computeInitPts(a[0].pts,v,s,"audio"):p=!1)}if(t.sps&&t.pps&&h.length){if(t.timescale=t.inputTimeScale,u.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:P.initSegment([t]),metadata:{width:t.width,height:t.height}},p)if(_=t.id,v=t.inputTimeScale,!d||v!==d.timescale){const o=this.getVideoStartPts(h),c=lt(h[0].dts,o),f=this.computeInitPts(c,v,s,"video"),m=this.computeInitPts(o,v,s,"video");x=Math.min(x,f),y=Math.min(y,m)}else p=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(u).length)return this.ISGenerated=!0,p?(d&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${s} ${y/v} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${y/v} (${y}/${v}) trackId: ${_}`),this._initPTS={baseTime:y,timescale:v,trackId:_},this._initDTS={baseTime:x,timescale:v,trackId:_}):y=v=void 0,{tracks:u,initPTS:y,timescale:v,trackId:_}}remuxVideo(e,t,s,n){const a=e.inputTimeScale,h=e.samples,l=[],u=h.length,d=this._initPTS,p=d.baseTime*a/d.timescale;let g=this.nextVideoTs,y=8,x=this.videoSampleDuration,v,_,o=Number.POSITIVE_INFINITY,c=Number.NEGATIVE_INFINITY,f=!1;if(!s||g===null){const $=p+t*a,G=h[0].pts-lt(h[0].dts,h[0].pts);Qi&&g!==null&&Math.abs($-G-(g+p))<15e3?s=!0:g=$-G-p}const m=g+p;for(let $=0;$<u;$++){const G=h[$];G.pts=lt(G.pts,m),G.dts=lt(G.dts,m),G.dts<h[$>0?$-1:$].dts&&(f=!0)}f&&h.sort(function($,G){const ie=$.dts-G.dts,ce=$.pts-G.pts;return ie||ce}),v=h[0].dts,_=h[h.length-1].dts;const S=_-v,T=S?Math.round(S/(u-1)):x||e.inputTimeScale/30;if(s){const $=v-m,G=$>T,ie=$<-1;if((G||ie)&&(G?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ws($,!0)} ms (${$}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ws(-$,!0)} ms (${$}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!ie||m>=h[0].pts||Qi)){v=m;const ce=h[0].pts-$;if(G)h[0].dts=v,h[0].pts=ce;else{let K=!0;for(let ue=0;ue<h.length&&!(h[ue].dts>ce&&K);ue++){const Ce=h[ue].pts;if(h[ue].dts-=$,h[ue].pts-=$,ue<h.length-1){const Ge=h[ue+1].pts,pt=h[ue].pts,wt=Ge<=pt,Ii=Ge<=Ce;K=wt==Ii}}}this.log(`Video: Initial PTS/DTS adjusted: ${ws(ce,!0)}/${ws(v,!0)}, delta: ${ws($,!0)} ms`)}}v=Math.max(0,v);let b=0,A=0,I=v;for(let $=0;$<u;$++){const G=h[$],ie=G.units,ce=ie.length;let K=0;for(let ue=0;ue<ce;ue++)K+=ie[ue].data.length;A+=K,b+=ce,G.length=K,G.dts<I?(G.dts=I,I+=T/4|0||1):I=G.dts,o=Math.min(G.pts,o),c=Math.max(G.pts,c)}_=h[u-1].dts;const L=A+4*b+8;let w;try{w=new Uint8Array(L)}catch($){this.observer.emit(E.ERROR,E.ERROR,{type:Z.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,error:$,bytes:L,reason:`fail allocating video mdat ${L}`});return}const R=new DataView(w.buffer);R.setUint32(0,L),w.set(P.types.mdat,4);let M=!1,k=Number.POSITIVE_INFINITY,z=Number.POSITIVE_INFINITY,O=Number.NEGATIVE_INFINITY,U=Number.NEGATIVE_INFINITY;for(let $=0;$<u;$++){const G=h[$],ie=G.units;let ce=0;for(let Ce=0,Ge=ie.length;Ce<Ge;Ce++){const pt=ie[Ce],wt=pt.data,Ii=pt.data.byteLength;R.setUint32(y,Ii),y+=4,w.set(wt,y),y+=Ii,ce+=4+Ii}let K;if($<u-1)x=h[$+1].dts-G.dts,K=h[$+1].pts-G.pts;else{const Ce=this.config,Ge=$>0?G.dts-h[$-1].dts:T;if(K=$>0?G.pts-h[$-1].pts:T,Ce.stretchShortVideoTrack&&this.nextAudioTs!==null){const pt=Math.floor(Ce.maxBufferHole*a),wt=(n?o+n*a:this.nextAudioTs+p)-G.pts;wt>pt?(x=wt-Ge,x<0?x=Ge:M=!0,this.log(`It is approximately ${wt/90} ms to the next segment; using duration ${x/90} ms for the last video frame.`)):x=Ge}else x=Ge}const ue=Math.round(G.pts-G.dts);k=Math.min(k,x),O=Math.max(O,x),z=Math.min(z,K),U=Math.max(U,K),l.push(Ah(G.key,x,ce,ue))}if(l.length){if(Qi){if(Qi<70){const $=l[0].flags;$.dependsOn=2,$.isNonSync=0}}else if(ua&&U-z<O-k&&T/O<.025&&l[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let $=v;for(let G=0,ie=l.length;G<ie;G++){const ce=$+l[G].duration,K=$+l[G].cts;if(G<ie-1){const ue=ce+l[G+1].cts;l[G].duration=ue-K}else l[G].duration=G?l[G-1].duration:T;l[G].cts=0,$=ce}}}x=M||!x?T:x;const j=_+x;this.nextVideoTs=g=j-p,this.videoSampleDuration=x,this.isVideoContiguous=!0;const J={data1:P.moof(e.sequenceNumber++,v,Ee(e,{samples:l})),data2:w,startPTS:(o-p)/a,endPTS:(c+x-p)/a,startDTS:(v-p)/a,endDTS:g/a,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,J}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Jy;case"ac3":return ev;default:return Zy}}remuxAudio(e,t,s,n,a){const h=e.inputTimeScale,l=e.samplerate?e.samplerate:h,u=h/l,d=this.getSamplesPerFrame(e),p=d*u,g=this._initPTS,y=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,x=[],v=a!==void 0;let _=e.samples,o=y?0:8,c=this.nextAudioTs||-1;const f=g.baseTime*h/g.timescale,m=f+t*h;if(this.isAudioContiguous=s=s||_.length&&c>0&&(n&&Math.abs(m-(c+f))<9e3||Math.abs(lt(_[0].pts,m)-(c+f))<20*p),_.forEach(function(U){U.pts=lt(U.pts,m)}),!s||c<0){const U=_.length;if(_=_.filter(j=>j.pts>=0),U!==_.length&&this.warn(`Removed ${_.length-U} of ${U} samples (initPTS ${f} / ${h})`),!_.length)return;a===0?c=0:n&&!v?c=Math.max(0,m-f):c=_[0].pts-f}if(e.segmentCodec==="aac"){const U=this.config.maxAudioFramesDrift;for(let j=0,H=c+f;j<_.length;j++){const V=_[j],J=V.pts,$=J-H,G=Math.abs(1e3*$/h);if($<=-U*p&&v)j===0&&(this.warn(`Audio frame @ ${(J/h).toFixed(3)}s overlaps marker by ${Math.round(1e3*$/h)} ms.`),this.nextAudioTs=c=J-f,H=J);else if($>=U*p&&G<Qy&&v){let ie=Math.round($/p);for(H=J-ie*p;H<0&&ie&&p;)ie--,H+=p;j===0&&(this.nextAudioTs=c=H-f),this.warn(`Injecting ${ie} audio frames @ ${((H-f)/h).toFixed(3)}s due to ${Math.round(1e3*$/h)} ms gap.`);for(let ce=0;ce<ie;ce++){let K=jy.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);K||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),K=V.unit.subarray()),_.splice(j,0,{unit:K,pts:H}),H+=p,j++}}V.pts=H,H+=p}}let S=null,T=null,b,A=0,I=_.length;for(;I--;)A+=_[I].unit.byteLength;for(let U=0,j=_.length;U<j;U++){const H=_[U],V=H.unit;let J=H.pts;if(T!==null){const G=x[U-1];G.duration=Math.round((J-T)/u)}else if(s&&e.segmentCodec==="aac"&&(J=c+f),S=J,A>0){A+=o;try{b=new Uint8Array(A)}catch(G){this.observer.emit(E.ERROR,E.ERROR,{type:Z.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,error:G,bytes:A,reason:`fail allocating audio mdat ${A}`});return}y||(new DataView(b.buffer).setUint32(0,A),b.set(P.types.mdat,4))}else return;b.set(V,o);const $=V.byteLength;o+=$,x.push(Ah(!0,d,$,0)),T=J}const L=x.length;if(!L)return;const w=x[x.length-1];c=T-f,this.nextAudioTs=c+u*w.duration;const R=y?new Uint8Array(0):P.moof(e.sequenceNumber++,S/u,Ee({},e,{samples:x}));e.samples=[];const M=(S-f)/h,k=c/h,O={data1:R,data2:b,startPTS:M,endPTS:k,startDTS:M,endDTS:k,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,O}}function lt(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 tv(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function nu(r,e,t,s){const n=r.samples.length;if(!n)return;const a=r.inputTimeScale;for(let l=0;l<n;l++){const u=r.samples[l];u.pts=lt(u.pts-t.baseTime*a/t.timescale,e*a)/a,u.dts=lt(u.dts-s.baseTime*a/s.timescale,e*a)/a}const h=r.samples;return r.samples=[],{samples:h}}function ru(r,e,t){const s=r.samples.length;if(!s)return;const n=r.inputTimeScale;for(let h=0;h<s;h++){const l=r.samples[h];l.pts=lt(l.pts-t.baseTime*n/t.timescale,e*n)/n}r.samples.sort((h,l)=>h.pts-l.pts);const a=r.samples;return r.samples=[],{samples:a}}class iv extends xt{constructor(e,t,s,n){super("passthrough-remuxer",n),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.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,n){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,n),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:a,video:h}=this.initData=dd(e);if(t)H0(e,t);else{const u=a||h;u!=null&&u.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${u.codec}")!`)}a&&(s=Ih(a,Te.AUDIO,this)),h&&(n=Ih(h,Te.VIDEO,this));const l={};a&&h?l.audiovideo={container:"video/mp4",codec:s+","+n,supplemental:h.supplemental,encrypted:h.encrypted,initSegment:e,id:"main"}:a?l.audio={container:"audio/mp4",codec:s,encrypted:a.encrypted,initSegment:e,id:"audio"}:h?l.video={container:"video/mp4",codec:n,supplemental:h.supplemental,encrypted:h.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l}remux(e,t,s,n,a,h){var l,u;let{initPTS:d,lastEndTime:p}=this;const g={audio:void 0,video:void 0,text:n,id3:s,initSegment:void 0};q(p)||(p=this.lastEndTime=a||0);const y=t.samples;if(!y.length)return g;const x={initPTS:void 0,timescale:void 0,trackId:void 0};let v=this.initData;if((l=v)!=null&&l.length||(this.generateInitSegment(y),v=this.initData),!((u=v)!=null&&u.length))return this.warn("Failed to generate initSegment."),g;this.emitInitSegment&&(x.tracks=this.initTracks,this.emitInitSegment=!1);const _=K0(y,v,this),o=v.audio?_[v.audio.id]:null,c=v.video?_[v.video.id]:null,f=xn(c,1/0),m=xn(o,1/0),S=xn(c,0,!0),T=xn(o,0,!0);let b=a,A=0;const I=o&&(!c||!d&&m<f||d&&d.trackId===v.audio.id),L=I?o:c;if(L){const H=L.timescale,V=L.start-a*H,J=I?v.audio.id:v.video.id;b=L.start/H,A=I?T-m:S-f,(h||!d)&&(sv(d,b,a,A)||H!==d.timescale)&&(d&&this.warn(`Timestamps at playlist time: ${h?"":"~"}${a} ${V/H} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${a} offset: ${b-a} (${V}/${H}) trackId: ${J}`),d=null,x.initPTS=V,x.timescale=H,x.trackId=J)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${a}`);d?(x.initPTS=d.baseTime,x.timescale=d.timescale,x.trackId=d.trackId):((!x.timescale||x.trackId===void 0||x.initPTS===void 0)&&(this.warn("Could not set initPTS"),x.initPTS=b,x.timescale=1,x.trackId=-1),this.initPTS=d={baseTime:x.initPTS,timescale:x.timescale,trackId:x.trackId});const w=b-d.baseTime/d.timescale,R=w+A;A>0?this.lastEndTime=R:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const M=!!v.audio,k=!!v.video;let z="";M&&(z+="audio"),k&&(z+="video");const O=(v.audio?v.audio.encrypted:!1)||(v.video?v.video.encrypted:!1),U={data1:y,startPTS:w,startDTS:w,endPTS:R,endDTS:R,type:z,hasAudio:M,hasVideo:k,nb:1,dropped:0,encrypted:O};g.audio=M&&!k?U:void 0,g.video=k?U:void 0;const j=c==null?void 0:c.sampleCount;if(j){const H=c.keyFrameIndex,V=H!==-1;U.nb=j,U.dropped=H===0||this.isVideoContiguous?0:V?H:j,U.independent=V,U.firstKeyFrame=H,V&&c.keyFrameStart&&(U.firstKeyFramePTS=(c.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(g.independent=V),this.isVideoContiguous||(this.isVideoContiguous=V),U.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${H}/${j} dropped: ${U.dropped} start: ${U.firstKeyFramePTS||"NA"}`)}return g.initSegment=x,g.id3=nu(s,a,d,d),n.samples.length&&(g.text=ru(n,a,d)),g}}function xn(r,e,t=!1){return(r==null?void 0:r.start)!==void 0?(r.start+(t?r.duration:0))/r.timescale:e}function sv(r,e,t,s){if(r===null)return!0;const n=Math.max(s,1),a=e-r.baseTime/r.timescale;return Math.abs(a-t)>n}function Ih(r,e,t){const s=r.codec;return s&&s.length>4?s:e===Te.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?Qn(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let Xt;try{Xt=self.performance.now.bind(self.performance)}catch{Xt=Date.now}const Bn=[{demux:zy,remux:iv},{demux:ui,remux:On},{demux:By,remux:On},{demux:$y,remux:On}];Bn.splice(2,0,{demux:Ny,remux:On});class wh{constructor(e,t,s,n,a,h){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=s,this.id=a,this.logger=h}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,n){const a=s.transmuxing;a.executeStart=Xt();let h=new Uint8Array(e);const{currentTransmuxState:l,transmuxConfig:u}=this;n&&(this.currentTransmuxState=n);const{contiguous:d,discontinuity:p,trackSwitch:g,accurateTimeOffset:y,timeOffset:x,initSegmentChange:v}=n||l,{audioCodec:_,videoCodec:o,defaultInitPts:c,duration:f,initSegmentData:m}=u,S=nv(h,t);if(S&&hs(S.method)){const I=this.getDecrypter(),L=Fo(S.method);if(I.isSync()){let w=I.softwareDecrypt(h,S.key.buffer,S.iv.buffer,L);if(s.part>-1){const M=I.flush();w=M&&M.buffer}if(!w)return a.executeEnd=Xt(),fa(s);h=new Uint8Array(w)}else return this.asyncResult=!0,this.decryptionPromise=I.webCryptoDecrypt(h,S.key.buffer,S.iv.buffer,L).then(w=>{const R=this.push(w,null,s);return this.decryptionPromise=null,R}),this.decryptionPromise}const T=this.needsProbing(p,g);if(T){const I=this.configureTransmuxer(h);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(E.ERROR,E.ERROR,{type:Z.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),a.executeEnd=Xt(),fa(s)}(p||g||v||T)&&this.resetInitSegment(m,_,o,f,t),(p||v||T)&&this.resetInitialTimestamp(c),d||this.resetContiguity();const b=this.transmux(h,S,x,y,s);this.asyncResult=Ys(b);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,a.executeEnd=Xt(),b}flush(e){const t=e.transmuxing;t.executeStart=Xt();const{decrypter:s,currentTransmuxState:n,decryptionPromise:a}=this;if(a)return this.asyncResult=!0,a.then(()=>this.flush(e));const h=[],{timeOffset:l}=n;if(s){const g=s.flush();g&&h.push(this.push(g.buffer,null,e))}const{demuxer:u,remuxer:d}=this;if(!u||!d){t.executeEnd=Xt();const g=[fa(e)];return this.asyncResult?Promise.resolve(g):g}const p=u.flush(l);return Ys(p)?(this.asyncResult=!0,p.then(g=>(this.flushRemux(h,g,e),h))):(this.flushRemux(h,p,e),this.asyncResult?Promise.resolve(h):h)}flushRemux(e,t,s){const{audioTrack:n,videoTrack:a,id3Track:h,textTrack:l}=t,{accurateTimeOffset:u,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===X.MAIN?"level":"track"} ${s.level}`);const p=this.remuxer.remux(n,a,h,l,d,u,!0,this.id);e.push({remuxResult:p,chunkMeta:s}),s.transmuxing.executeEnd=Xt()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,n,a){const{demuxer:h,remuxer:l}=this;!h||!l||(h.resetInitSegment(e,t,s,n),l.resetInitSegment(e,t,s,a))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,n,a){let h;return t&&t.method==="SAMPLE-AES"?h=this.transmuxSampleAes(e,t,s,n,a):h=this.transmuxUnencrypted(e,s,n,a),h}transmuxUnencrypted(e,t,s,n){const{audioTrack:a,videoTrack:h,id3Track:l,textTrack:u}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(a,h,l,u,t,s,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,s,n,a){return this.demuxer.demuxSampleAes(e,t,s).then(h=>({remuxResult:this.remuxer.remux(h.audioTrack,h.videoTrack,h.id3Track,h.textTrack,s,n,!1,this.id),chunkMeta:a}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:n}=this;let a;for(let g=0,y=Bn.length;g<y;g++){var h;if((h=Bn[g].demux)!=null&&h.probe(e,this.logger)){a=Bn[g];break}}if(!a)return new Error("Failed to find demuxer by probing fragment data");const l=this.demuxer,u=this.remuxer,d=a.remux,p=a.demux;(!u||!(u instanceof d))&&(this.remuxer=new d(s,t,n,this.logger)),(!l||!(l instanceof p))&&(this.demuxer=new p(s,t,n,this.logger),this.probe=p.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new ko(this.config)),e}}function nv(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 fa=r=>({remuxResult:{},chunkMeta:r});function Ys(r){return"then"in r&&r.then instanceof Function}class rv{constructor(e,t,s,n,a){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=s,this.duration=n,this.defaultInitPts=a||null}}class av{constructor(e,t,s,n,a,h){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=s,this.trackSwitch=n,this.timeOffset=a,this.initSegmentChange=h}}let Lh=0;class au{constructor(e,t,s,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Lh++,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=u=>{const d=u.data,p=this.hls;if(!(!p||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var g;const y=(g=this.workerContext)==null?void 0:g.objectURL;y&&self.URL.revokeObjectURL(y);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{p.logger[d.data.logType]&&p.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,p.trigger(d.event,d.data);break}}},this.onWorkerError=u=>{if(!this.hls)return;const d=new Error(`${u.message} (${u.filename}:${u.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(E.ERROR,{type:Z.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};const a=e.config;this.hls=e,this.id=t,this.useWorker=!!a.enableWorker,this.onTransmuxComplete=s,this.onFlush=n;const h=(u,d)=>{d=d||{},d.frag=this.frag||void 0,u===E.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(u,d)};this.observer=new Bo,this.observer.on(E.FRAG_DECRYPTED,h),this.observer.on(E.ERROR,h);const l=Hl(a.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const u=this.hls.logger;if(a.workerPath||cy()){try{a.workerPath?(u.log(`loading Web Worker ${a.workerPath} for "${t}"`),this.workerContext=uy(a.workerPath)):(u.log(`injecting Web Worker for "${t}"`),this.workerContext=dy());const{worker:p}=this.workerContext;p.addEventListener("message",this.onWorkerMessage),p.addEventListener("error",this.onWorkerError),p.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:l,id:t,config:be(a)})}catch(p){u.warn(`Error setting up "${t}" Web Worker, fallback to inline`,p),this.terminateWorker(),this.error=null,this.transmuxer=new wh(this.observer,l,a,"",t,e.logger)}return}}this.transmuxer=new wh(this.observer,l,a,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Lh++;const t=this.hls.config,s=Hl(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:be(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),fy(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,s,n,a,h,l,u,d,p){var g,y;d.transmuxing.start=self.performance.now();const{instanceNo:x,transmuxer:v}=this,_=h?h.start:a.start,o=a.decryptdata,c=this.frag,f=!(c&&a.cc===c.cc),m=!(c&&d.level===c.level),S=c?d.sn-c.sn:-1,T=this.part?d.part-this.part.index:-1,b=S===0&&d.id>1&&d.id===(c==null?void 0:c.stats.chunkCount),A=!m&&(S===1||S===0&&(T===1||b&&T<=0)),I=self.performance.now();(m||S||a.stats.parsing.start===0)&&(a.stats.parsing.start=I),h&&(T||!A)&&(h.stats.parsing.start=I);const L=!(c&&((g=a.initSegment)==null?void 0:g.url)===((y=c.initSegment)==null?void 0:y.url)),w=new av(f,A,u,m,_,L);if(!A||f||L){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${a.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===X.MAIN?"level":"track"}: ${d.level} id: ${d.id}
|
|
121
121
|
discontinuity: ${f}
|
|
122
122
|
trackSwitch: ${m}
|
|
123
123
|
contiguous: ${A}
|
|
124
124
|
accurateTimeOffset: ${u}
|
|
125
|
-
timeOffset: ${
|
|
126
|
-
initSegmentChange: ${L}`);const C=new Dy(s,n,t,l,p);this.configureTransmuxer(C)}if(this.frag=a,this.part=h,this.workerContext)this.workerContext.worker.postMessage({instanceNo:v,cmd:"demux",data:e,decryptdata:o,chunkMeta:d,state:w},e instanceof ArrayBuffer?[e]:[]);else if(x){const C=x.push(e,o,d,w);Os(C)?C.then(k=>{this.handleTransmuxComplete(k)}).catch(k=>{this.transmuxerError(k,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(C)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const n=s.flush(e);Os(n)?n.then(a=>{this.handleFlushResult(a,e)}).catch(a=>{this.transmuxerError(a,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(_.ERROR,{type:Q.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const uh=100;class ky extends To{constructor(e,t,s){super(e,t,s,"audio-stream-controller",X.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(_.LEVEL_LOADED,this.onLevelLoaded,this),e.on(_.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(_.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(_.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(_.BUFFER_RESET,this.onBufferReset,this),e.on(_.BUFFER_CREATED,this.onBufferCreated,this),e.on(_.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(_.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(_.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(_.FRAG_LOADING,this.onFragLoading,this),e.on(_.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(_.LEVEL_LOADED,this.onLevelLoaded,this),e.off(_.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(_.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(_.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(_.BUFFER_RESET,this.onBufferReset,this),e.off(_.BUFFER_CREATED,this.onBufferCreated,this),e.off(_.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(_.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(_.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(_.FRAG_LOADING,this.onFragLoading,this),e.off(_.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:n,timescale:a}){if(s===X.MAIN){const h=t.cc,l=this.fragCurrent;if(this.initPTS[h]={baseTime:n,timescale:a},this.log(`InitPTS for cc: ${h} found from main: ${n}/${a}`),this.mainAnchor=t,this.state===M.WAITING_INIT_PTS){const u=this.waitingData;(!u&&!this.loadingParts||u&&u.frag.cc!==h)&&(this.nextLoadPosition=this.findSyncFrag(t).start),this.tick()}else!this.hls.hasEnoughToStart&&l&&l.cc!==h?(this.startFragRequested=!1,this.nextLoadPosition=this.findSyncFrag(t).start,l.abortRequests(),this.resetLoadingState()):this.state===M.IDLE&&this.tick()}}findSyncFrag(e){const t=this.getLevelDetails(),s=e.cc;return q0(t,s,e)||t&&nd(t.fragments,s)||e}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=M.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(uh),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=M.IDLE):this.state=M.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case M.IDLE:this.doTickIdle();break;case M.WAITING_TRACK:{const{levels:t,trackId:s}=this,n=t==null?void 0:t[s],a=n==null?void 0:n.details;if(a&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(a))break;this.state=M.WAITING_INIT_PTS}break}case M.FRAG_LOADING_WAITING_RETRY:{var e;const t=performance.now(),s=this.retryDate;if(!s||t>=s||(e=this.media)!=null&&e.seeking){const{levels:n,trackId:a}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((n==null?void 0:n[a])||null),this.state=M.IDLE}break}case M.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:s,part:n,cache:a,complete:h}=t,l=this.mainAnchor;if(this.initPTS[s.cc]!==void 0){this.waitingData=null,this.state=M.FRAG_LOADING;const u=a.flush().buffer,d={frag:s,part:n,payload:u,networkDetails:null};this._handleFragmentLoadProgress(d),h&&super._handleFragmentLoadComplete(d)}else l&&l.cc!==t.frag.cc&&(this.log(`Waiting fragment cc (${s.cc}) cancelled because video is at cc ${l.cc}`),this.nextLoadPosition=this.findSyncFrag(l).start,this.clearWaitingFragment())}else this.state=M.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!==M.STOPPED&&(this.state=M.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:s,media:n,trackId:a}=this,h=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!h.startFragPrefetch)||!(s!=null&&s[a]))return;const l=s[a],u=l.details;if(!u||this.waitForLive(l)||this.waitForCdnTuneIn(u)){this.state=M.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,Ee.AUDIO,X.AUDIO));const p=this.getFwdBufferInfo(d,X.AUDIO);if(p===null)return;if(!this.switchingTrack&&this._streamEnded(p,u)){t.trigger(_.BUFFER_EOS,{type:"audio"}),this.state=M.ENDED;return}const g=p.len,y=t.maxBufferLength,v=u.fragments,x=v[0].start,E=this.getLoadPosition(),o=this.flushing?E:p.end;if(this.switchingTrack&&n){const m=E;u.PTSKnown&&m<x&&(p.end>x||p.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=x+.05)}if(g>=y&&!this.switchingTrack&&o<v[v.length-1].start)return;let c=this.getNextFragment(o,u);if(c&&this.isLoopLoading(c,o)&&(c=this.getNextFragmentLoopLoading(c,u,p,X.MAIN,y)),!c){this.bufferFlushed=!0;return}let f=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&f&&Ne(c)&&!c.endList&&(!u.live||!this.loadingParts&&o<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(f)===ke.OK&&(this.mainFragLoading=f=null),f&&Ne(f))){if(c.start>f.end){const S=this.fragmentTracker.getFragAtPos(o,X.MAIN);S&&S.end>f.end&&(f=S,this.mainFragLoading={frag:S,targetBufferTime:null})}if(c.start>f.end)return}this.loadFragment(c,l,o)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new Ps(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==M.STOPPED&&(this.setInterval(uh),this.state=M.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 s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(_.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:n}=this,{details:a,id:h,groupId:l,track:u}=t;if(!n){this.warn(`Audio tracks reset while loading track ${h} "${u.name}" of "${l}"`);return}const d=this.mainDetails;if(!d||a.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==M.STOPPED&&(this.state=M.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${h} "${u.name}" of "${l}" loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`);const p=n[h];let g=0;if(a.live||(s=p.details)!=null&&s.live){if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;if(p.details){var y;g=this.alignPlaylists(a,p.details,(y=this.levelLastLoaded)==null?void 0:y.details)}a.alignedSliding||(xd(a,d),a.alignedSliding||Wn(a,d),g=a.fragmentStart)}p.details=a,this.levelLastLoaded=p,this.startFragRequested||this.setStartPosition(d,g),this.hls.trigger(_.AUDIO_TRACK_UPDATED,{details:a,id:h,groupId:t.groupId}),this.state===M.WAITING_TRACK&&!this.waitForCdnTuneIn(a)&&(this.state=M.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:n,payload:a}=e,{config:h,trackId:l,levels:u}=this;if(!u){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const d=u[l];if(!d){this.warn("Audio track is undefined on fragment load progress");return}const p=d.details;if(!p){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const g=h.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let y=this.transmuxer;y||(y=this.transmuxer=new Nd(this.hls,X.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const v=this.initPTS[s.cc],x=(t=s.initSegment)==null?void 0:t.data;if(v!==void 0){const o=n?n.index:-1,c=o!==-1,f=new So(s.level,s.sn,s.stats.chunkCount,a.byteLength,o,c);y.push(a,x,g,"",s,n,p.totalduration,!1,f,v)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${p.startSN} ,${p.endSN}],track ${l}`);const{cache:E}=this.waitingData=this.waitingData||{frag:s,part:n,cache:new vd,complete:!1};E.push(new Uint8Array(a)),this.state!==M.STOPPED&&(this.state=M.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 s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===X.MAIN&&Ne(t.frag)&&(this.mainFragLoading=t,this.state===M.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:n}=t;if(s.type!==X.AUDIO){!this.audioOnly&&s.type===X.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${n?" p: "+n.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Ne(s)){this.fragPrevious=s;const a=this.switchingTrack;a&&(this.bufferedTrack=a,this.switchingTrack=null,this.hls.trigger(_.AUDIO_TRACK_SWITCHED,xe({},a)))}this.fragBufferedComplete(s,n),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=M.ERROR;return}switch(t.details){case P.FRAG_GAP:case P.FRAG_PARSING_ERROR:case P.FRAG_DECRYPT_ERROR:case P.FRAG_LOAD_ERROR:case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_ERROR:case P.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(X.AUDIO,t);break;case P.AUDIO_TRACK_LOAD_ERROR:case P.AUDIO_TRACK_LOAD_TIMEOUT:case P.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===M.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===ue.AUDIO_TRACK&&(this.state=M.IDLE);break;case P.BUFFER_ADD_CODEC_ERROR:case P.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.resetLoadingState();break;case P.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case P.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Ee.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Ee.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===M.ENDED&&(this.state=M.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,X.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:n}=this,{remuxResult:a,chunkMeta:h}=e,l=this.getCurrentContext(h);if(!l){this.resetWhenMissingContext(h);return}const{frag:u,part:d,level:p}=l,{details:g}=p,{audio:y,text:v,id3:x,initSegment:E}=a;if(this.fragContextChanged(u)||!g){this.fragmentTracker.removeFragment(u);return}if(this.state=M.PARSING,this.switchingTrack&&y&&this.completeAudioSwitch(this.switchingTrack),E!=null&&E.tracks){const o=u.initSegment||u;this._bufferInitSegment(p,E.tracks,o,h),n.trigger(_.FRAG_PARSING_INIT_SEGMENT,{frag:o,id:s,tracks:E.tracks})}if(y){const{startPTS:o,endPTS:c,startDTS:f,endDTS:m}=y;d&&(d.elementaryStreams[Ee.AUDIO]={startPTS:o,endPTS:c,startDTS:f,endDTS:m}),u.setElementaryStreamInfo(Ee.AUDIO,o,c,f,m),this.bufferFragmentData(y,u,d,h)}if(x!=null&&(t=x.samples)!=null&&t.length){const o=Te({id:s,frag:u,details:g},x);n.trigger(_.FRAG_PARSING_METADATA,o)}if(v){const o=Te({id:s,frag:u,details:g},v);n.trigger(_.FRAG_PARSING_USERDATA,o)}}_bufferInitSegment(e,t,s,n){if(this.state!==M.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const a=t.audio;a.id=X.AUDIO;const h=e.audioCodec;this.log(`Init audio buffer, container:${a.container}, codecs[level/parsed]=[${h}/${a.codec}]`),h&&h.split(",").length===1&&(a.levelCodec=h),this.hls.trigger(_.BUFFER_CODECS,t);const l=a.initSegment;if(l!=null&&l.byteLength){const u={type:"audio",frag:s,part:null,chunkMeta:n,parent:s.type,data:l};this.hls.trigger(_.BUFFER_APPENDING,u)}this.tickImmediate()}loadFragment(e,t,s){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===ke.NOT_LOADED||n===ke.PARTIAL){var a;if(!Ne(e))this._loadInitSegment(e,t);else if((a=t.details)!=null&&a.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=M.WAITING_INIT_PTS;const h=this.mainDetails;h&&h.fragmentStart!==t.details.fragmentStart&&Wn(t.details,h)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:n,characteristics:a,audioCodec:h,channels:l}=this.bufferedTrack;Ci({name:t,lang:s,assocLang:n,characteristics:a,audioCodec:h,channels:l},e,Ai)||(Hn(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(_.AUDIO_TRACK_SWITCHED,xe({},e))}}class Do extends Jt{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,s){const n=t==null?void 0:t.renditionReports;if(n){let a=-1;for(let h=0;h<n.length;h++){const l=n[h];let u;try{u=new self.URL(l.URI,t.url).href}catch(d){this.warn(`Could not construct new URL for Rendition Report: ${d}`),u=l.URI||""}if(u===e){a=h;break}else u===e.substring(0,u.length)&&(a=h)}if(a!==-1){const h=n[a],l=parseInt(h["LAST-MSN"])||(t==null?void 0:t.lastPartSn);let u=parseInt(h["LAST-PART"])||(t==null?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const p=Math.min(t.age-t.partTarget,t.targetduration);u>=0&&p>t.partTarget&&(u+=1)}const d=s&&Rl(s);return new Cl(l,u>=0?u:void 0,d)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:n,stats:a}=t,h=self.performance.now(),l=a.loading.first?Math.max(0,h-a.loading.first):0;n.advancedDateTime=Date.now()-l;const u=this.hls.config.timelineOffset;if(u!==n.appliedTimelineOffset){const p=Math.max(u||0,0);n.appliedTimelineOffset=p,n.fragments.forEach(g=>{g.start=g.playlistOffset+p})}if(n.live||s!=null&&s.live){const p="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(s),s&&n.fragments.length>0){Am(s,n);const f=n.playlistParsingError;if(f){this.warn(f);const m=this.hls;if(!m.config.ignorePlaylistParsingErrors){var d;const{networkDetails:S}=t;m.trigger(_.ERROR,{type:Q.NETWORK_ERROR,details:P.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:f,reason:f.message,level:t.level||void 0,parent:(d=n.fragments[0])==null?void 0:d.type,networkDetails:S,stats:a});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=a.loading.start);const g=this.hls.mainForwardBufferInfo,y=g?g.end-g.len:0,v=(n.edge-y)*1e3,x=fd(n,v);if(n.requestScheduled+x<h?n.requestScheduled=h:n.requestScheduled+=x,this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED"}`),!this.canLoad||!n.live)return;let E,o,c;if(n.canBlockReload&&n.endSN&&n.advanced){const f=this.hls.config.lowLatencyMode,m=n.lastPartSn,S=n.endSN,T=n.lastPartIndex,b=T!==-1,A=m===S;b?A?(o=S+1,c=f?0:T):(o=m,c=f?T+1:n.maxPartIndex):o=S+1;const I=n.age,L=I+n.ageHeader;let w=Math.min(L-n.partTarget,n.targetduration*1.5);if(w>0){if(L>n.targetduration*3)this.log(`Playlist last advanced ${I.toFixed(2)}s ago. Omitting segment and part directives.`),o=void 0,c=void 0;else if(s!=null&&s.tuneInGoal&&L-n.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${w} with playlist age: ${n.age}`),w=0;else{const C=Math.floor(w/n.targetduration);if(o+=C,c!==void 0){const k=Math.round(w%n.targetduration/n.partTarget);c+=k}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${I.toFixed(2)}s goal: ${w} skip sn ${C} to part ${c}`)}n.tuneInGoal=w}if(E=this.getDeliveryDirectives(n,t.deliveryDirectives,o,c),f||!A){n.requestScheduled=h,this.loadingPlaylist(p,E);return}}else(n.canBlockReload||n.canSkipUntil)&&(E=this.getDeliveryDirectives(n,t.deliveryDirectives,o,c));E&&o!==void 0&&n.canBlockReload&&(n.requestScheduled=a.loading.first+Math.max(x-l*2,x/2)),this.scheduleLoading(p,E,n)}else this.clearTimer()}scheduleLoading(e,t,s){const n=s||e.details;if(!n){this.loadingPlaylist(e,t);return}const a=self.performance.now(),h=n.requestScheduled;if(a>=h){this.loadingPlaylist(e,t);return}const l=h-a;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(l)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),l)}getDeliveryDirectives(e,t,s,n){let a=Rl(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,n=t.part,a=An.No),new Cl(s,n,a)}checkRetry(e){const t=e.details,s=Vn(e),n=e.errorAction,{action:a,retryCount:h=0,retryConfig:l}=n||{},u=!!n&&!!l&&(a===Ve.RetryRequest||!n.resolved&&a===Ve.SendAlternateToPenaltyBox);if(u){var d;if(h>=l.maxNumRetry)return!1;if(s&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${h+1}/${l.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const p=xo(l,h);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),p),this.warn(`Retrying playlist loading ${h+1}/${l.maxNumRetry} after "${t}" in ${p}ms`)}e.levelRetry=!0,n.resolved=!0}return u}}function $d(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!Bs(r[t].attrs,e[t].attrs))return!1;return!0}function Bs(r,e,t){const s=r["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(n=>r[n]!==e[n])}function Na(r,e){return e.label.toLowerCase()===r.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(r.lang||"").toLowerCase())}class My extends Do{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(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.MANIFEST_PARSED,this.onManifestParsed,this),e.on(_.LEVEL_LOADING,this.onLevelLoading,this),e.on(_.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(_.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(_.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.MANIFEST_PARSED,this.onManifestParsed,this),e.off(_.LEVEL_LOADING,this.onLevelLoading,this),e.off(_.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(_.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(_.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:s,groupId:n,details:a}=t,h=this.tracksInGroup[s];if(!h||h.groupId!==n){this.warn(`Audio track with id:${s} and group:${n} not found in active group ${h==null?void 0:h.groupId}`);return}const l=h.details;h.details=t.details,this.log(`Audio track ${s} "${h.name}" lang:${h.lang} group:${n} loaded [${a.startSN}-${a.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,l)}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 s=t.audioGroups||null,n=this.groupIds;let a=this.currentTrack;if(!s||(n==null?void 0:n.length)!==(s==null?void 0:s.length)||s!=null&&s.some(l=>(n==null?void 0:n.indexOf(l))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const l=this.tracks.filter(y=>!s||s.indexOf(y.groupId)!==-1);if(l.length)this.selectDefaultTrack&&!l.some(y=>y.default)&&(this.selectDefaultTrack=!1),l.forEach((y,v)=>{y.id=v});else if(!a&&!this.tracksInGroup.length)return;this.tracksInGroup=l;const u=this.hls.config.audioPreference;if(!a&&u){const y=wt(u,l,Ai);if(y>-1)a=l[y];else{const v=wt(u,this.tracks);a=this.tracks[v]}}let d=this.findTrackId(a);d===-1&&a&&(d=this.findTrackId(null));const p={audioTracks:l};this.log(`Updating audio tracks, ${l.length} track(s) found in group(s): ${s==null?void 0:s.join(",")}`),this.hls.trigger(_.AUDIO_TRACKS_UPDATED,p);const g=this.trackId;if(d!==-1&&g===-1)this.setAudioTrack(d);else if(l.length&&g===-1){var h;const y=new Error(`No audio track selected for current audio group-ID(s): ${(h=this.groupIds)==null?void 0:h.join(",")} track count: ${l.length}`);this.warn(y.message),this.hls.trigger(_.ERROR,{type:Q.MEDIA_ERROR,details:P.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:y})}}}onError(e,t){t.fatal||!t.context||t.context.type===ue.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 s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const n=this.currentTrack;if(n&&Ci(e,n,Ai))return n;const a=wt(e,this.tracksInGroup,Ai);if(a>-1){const h=this.tracksInGroup[a];return this.setAudioTrack(a),h}else if(n){let h=t.loadLevel;h===-1&&(h=t.firstAutoLevel);const l=V0(e,t.levels,s,h,Ai);if(l===-1)return null;t.nextLoadLevel=l}if(e.channels||e.audioCodec){const h=wt(e,s);if(h>-1)return s[h]}}}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 s=this.currentTrack,n=t[e],a=n.details&&!n.details.live;if(e===this.trackId&&n===s&&a||(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(_.AUDIO_TRACK_SWITCHING,xe({},n)),a))return;const h=this.switchParams(n.url,s==null?void 0:s.details,n.details);this.loadPlaylist(h)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const n=t[s];if(!(this.selectDefaultTrack&&!n.default)&&(!e||Ci(e,n,Ai)))return s}if(e){const{name:s,lang:n,assocLang:a,characteristics:h,audioCodec:l,channels:u}=e;for(let d=0;d<t.length;d++){const p=t[d];if(Ci({name:s,lang:n,assocLang:a,characteristics:h,audioCodec:l,channels:u},p,Ai))return d}for(let d=0;d<t.length;d++){const p=t[d];if(Bs(e.attrs,p.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(let d=0;d<t.length;d++){const p=t[d];if(Bs(e.attrs,p.attrs,["LANGUAGE"]))return d}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Hn(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,t),h=e.details,l=h==null?void 0:h.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${l&&h.live?" age "+l.toFixed(1)+(h.type&&" "+h.type||""):""} ${a}`),this.hls.trigger(_.AUDIO_TRACK_LOADING,{url:a,id:s,groupId:n,deliveryDirectives:t||null,track:e})}}class Fy{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const n=this.queues[t];n.push(e),n.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="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(a){var s;if(n.onError(a),this.queues===null||this.tracks===null)return;const h=(s=this.tracks[e])==null?void 0:s.buffer;h!=null&&h.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>":`
|
|
125
|
+
timeOffset: ${_}
|
|
126
|
+
initSegmentChange: ${L}`);const R=new rv(s,n,t,l,p);this.configureTransmuxer(R)}if(this.frag=a,this.part=h,this.workerContext)this.workerContext.worker.postMessage({instanceNo:x,cmd:"demux",data:e,decryptdata:o,chunkMeta:d,state:w},e instanceof ArrayBuffer?[e]:[]);else if(v){const R=v.push(e,o,d,w);Ys(R)?R.then(M=>{this.handleTransmuxComplete(M)}).catch(M=>{this.transmuxerError(M,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(R)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const n=s.flush(e);Ys(n)?n.then(a=>{this.handleFlushResult(a,e)}).catch(a=>{this.transmuxerError(a,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Rh=100;class ov extends Oo{constructor(e,t,s){super(e,t,s,"audio-stream-controller",X.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(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:n,timescale:a,trackId:h}){if(s===X.MAIN){const l=t.cc,u=this.fragCurrent;if(this.initPTS[l]={baseTime:n,timescale:a,trackId:h},this.log(`InitPTS for cc: ${l} found from main: ${n/a} (${n}/${a}) trackId: ${h}`),this.mainAnchor=t,this.state===F.WAITING_INIT_PTS){const d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==l)&&this.syncWithAnchor(t,d==null?void 0:d.frag)}else!this.hls.hasEnoughToStart&&u&&u.cc!==l?(u.abortRequests(),this.syncWithAnchor(t,u)):this.state===F.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const n=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&(n==null?void 0:n.cc)===t.cc)return;const a=(n||e).cc,h=this.getLevelDetails(),l=this.getLoadPosition(),u=Ed(h,a,l);u&&(this.log(`Syncing with main frag at ${u.start} cc ${u.cc}`),this.startFragRequested=!1,this.nextLoadPosition=u.start,this.resetLoadingState(),this.state===F.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=F.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(Rh),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=F.IDLE):this.state=F.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case F.IDLE:this.doTickIdle();break;case F.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=e==null?void 0:e[t],n=s==null?void 0:s.details;if(n&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(n))break;this.state=F.WAITING_INIT_PTS}break}case F.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case F.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:n,complete:a}=e,h=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=F.FRAG_LOADING;const l=n.flush().buffer,u={frag:t,part:s,payload:l,networkDetails:null};this._handleFragmentLoadProgress(u),a&&super._handleFragmentLoadComplete(u)}else h&&h.cc!==e.frag.cc&&this.syncWithAnchor(h,e.frag)}else this.state=F.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:s,media:n,trackId:a}=this,h=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!h.startFragPrefetch)||!(s!=null&&s[a]))return;const l=s[a],u=l.details;if(!u||this.waitForLive(l)||this.waitForCdnTuneIn(u)){this.state=F.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,Te.AUDIO,X.AUDIO));const p=this.getFwdBufferInfo(d,X.AUDIO);if(p===null)return;if(!this.switchingTrack&&this._streamEnded(p,u)){t.trigger(E.BUFFER_EOS,{type:"audio"}),this.state=F.ENDED;return}const g=p.len,y=t.maxBufferLength,x=u.fragments,v=x[0].start,_=this.getLoadPosition(),o=this.flushing?_:p.end;if(this.switchingTrack&&n){const m=_;u.PTSKnown&&m<v&&(p.end>v||p.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=v+.05)}if(g>=y&&!this.switchingTrack&&o<x[x.length-1].start)return;let c=this.getNextFragment(o,u);if(c&&this.isLoopLoading(c,o)&&(c=this.getNextFragmentLoopLoading(c,u,p,X.MAIN,y)),!c){this.bufferFlushed=!0;return}let f=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&f&&Pe(c)&&!c.endList&&(!u.live||!this.loadingParts&&o<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(f)===Fe.OK&&(this.mainFragLoading=f=null),f&&Pe(f))){if(c.start>f.end){const S=this.fragmentTracker.getFragAtPos(o,X.MAIN);S&&S.end>f.end&&(f=S,this.mainFragLoading={frag:S,targetBufferTime:null})}if(c.start>f.end)return}this.loadFragment(c,l,o)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new Hs(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==F.STOPPED&&(this.setInterval(Rh),this.state=F.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 s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(E.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:n}=this,{details:a,id:h,groupId:l,track:u}=t;if(!n){this.warn(`Audio tracks reset while loading track ${h} "${u.name}" of "${l}"`);return}const d=this.mainDetails;if(!d||a.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==F.STOPPED&&(this.state=F.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${h} "${u.name}" of "${l}" loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`);const p=n[h];let g=0;if(a.live||(s=p.details)!=null&&s.live){if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;if(p.details){var y;g=this.alignPlaylists(a,p.details,(y=this.levelLastLoaded)==null?void 0:y.details)}a.alignedSliding||($d(a,d),a.alignedSliding||nr(a,d),g=a.fragmentStart)}p.details=a,this.levelLastLoaded=p,this.startFragRequested||this.setStartPosition(d,g),this.hls.trigger(E.AUDIO_TRACK_UPDATED,{details:a,id:h,groupId:t.groupId}),this.state===F.WAITING_TRACK&&!this.waitForCdnTuneIn(a)&&(this.state=F.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:n,payload:a}=e,{config:h,trackId:l,levels:u}=this;if(!u){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const d=u[l];if(!d){this.warn("Audio track is undefined on fragment load progress");return}const p=d.details;if(!p){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const g=h.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let y=this.transmuxer;y||(y=this.transmuxer=new au(this.hls,X.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const x=this.initPTS[s.cc],v=(t=s.initSegment)==null?void 0:t.data;if(x!==void 0){const o=n?n.index:-1,c=o!==-1,f=new Mo(s.level,s.sn,s.stats.chunkCount,a.byteLength,o,c);y.push(a,v,g,"",s,n,p.totalduration,!1,f,x)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${p.startSN} ,${p.endSN}],track ${l}`);const{cache:_}=this.waitingData=this.waitingData||{frag:s,part:n,cache:new Gd,complete:!1};_.push(new Uint8Array(a)),this.state!==F.STOPPED&&(this.state=F.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 s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===X.MAIN&&Pe(t.frag)&&(this.mainFragLoading=t,this.state===F.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:n}=t;if(s.type!==X.AUDIO){!this.audioOnly&&s.type===X.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${n?" p: "+n.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Pe(s)){this.fragPrevious=s;const a=this.switchingTrack;a&&(this.bufferedTrack=a,this.switchingTrack=null,this.hls.trigger(E.AUDIO_TRACK_SWITCHED,xe({},a)))}this.fragBufferedComplete(s,n),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=F.ERROR;return}switch(t.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(X.AUDIO,t);break;case D.AUDIO_TRACK_LOAD_ERROR:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===F.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===fe.AUDIO_TRACK&&(this.state=F.IDLE);break;case D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case D.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case D.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Te.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Te.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===F.ENDED&&(this.state=F.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,X.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:n}=this,{remuxResult:a,chunkMeta:h}=e,l=this.getCurrentContext(h);if(!l){this.resetWhenMissingContext(h);return}const{frag:u,part:d,level:p}=l,{details:g}=p,{audio:y,text:x,id3:v,initSegment:_}=a;if(this.fragContextChanged(u)||!g){this.fragmentTracker.removeFragment(u);return}if(this.state=F.PARSING,this.switchingTrack&&y&&this.completeAudioSwitch(this.switchingTrack),_!=null&&_.tracks){const o=u.initSegment||u;if(this.unhandledEncryptionError(_,u))return;this._bufferInitSegment(p,_.tracks,o,h),n.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:o,id:s,tracks:_.tracks})}if(y){const{startPTS:o,endPTS:c,startDTS:f,endDTS:m}=y;d&&(d.elementaryStreams[Te.AUDIO]={startPTS:o,endPTS:c,startDTS:f,endDTS:m}),u.setElementaryStreamInfo(Te.AUDIO,o,c,f,m),this.bufferFragmentData(y,u,d,h)}if(v!=null&&(t=v.samples)!=null&&t.length){const o=Ee({id:s,frag:u,details:g},v);n.trigger(E.FRAG_PARSING_METADATA,o)}if(x){const o=Ee({id:s,frag:u,details:g},x);n.trigger(E.FRAG_PARSING_USERDATA,o)}}_bufferInitSegment(e,t,s,n){if(this.state!==F.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const a=t.audio;a.id=X.AUDIO;const h=e.audioCodec;this.log(`Init audio buffer, container:${a.container}, codecs[level/parsed]=[${h}/${a.codec}]`),h&&h.split(",").length===1&&(a.levelCodec=h),this.hls.trigger(E.BUFFER_CODECS,t);const l=a.initSegment;if(l!=null&&l.byteLength){const u={type:"audio",frag:s,part:null,chunkMeta:n,parent:s.type,data:l};this.hls.trigger(E.BUFFER_APPENDING,u)}this.tickImmediate()}loadFragment(e,t,s){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===Fe.NOT_LOADED||n===Fe.PARTIAL){var a;if(!Pe(e))this._loadInitSegment(e,t);else if((a=t.details)!=null&&a.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=F.WAITING_INIT_PTS;const h=this.mainDetails;h&&h.fragmentStart!==t.details.fragmentStart&&nr(t.details,h)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:n,characteristics:a,audioCodec:h,channels:l}=this.bufferedTrack;Bi({name:t,lang:s,assocLang:n,characteristics:a,audioCodec:h,channels:l},e,ki)||(Jn(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(E.AUDIO_TRACK_SWITCHED,xe({},e))}}class Ko extends xt{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,s){const n=t==null?void 0:t.renditionReports;if(n){let a=-1;for(let h=0;h<n.length;h++){const l=n[h];let u;try{u=new self.URL(l.URI,t.url).href}catch(d){this.warn(`Could not construct new URL for Rendition Report: ${d}`),u=l.URI||""}if(u===e){a=h;break}else u===e.substring(0,u.length)&&(a=h)}if(a!==-1){const h=n[a],l=parseInt(h["LAST-MSN"])||t.lastPartSn;let u=parseInt(h["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const p=Math.min(t.age-t.partTarget,t.targetduration);u>=0&&p>t.partTarget&&(u+=1)}const d=s&&Vl(s);return new Kl(l,u>=0?u:void 0,d)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:n,stats:a}=t,h=self.performance.now(),l=a.loading.first?Math.max(0,h-a.loading.first):0;n.advancedDateTime=Date.now()-l;const u=this.hls.config.timelineOffset;if(u!==n.appliedTimelineOffset){const p=Math.max(u||0,0);n.appliedTimelineOffset=p,n.fragments.forEach(g=>{g.setStart(g.playlistOffset+p)})}if(n.live||s!=null&&s.live){const p="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(s),s&&n.fragments.length>0){Jm(s,n,this);const f=n.playlistParsingError;if(f){this.warn(f);const m=this.hls;if(!m.config.ignorePlaylistParsingErrors){var d;const{networkDetails:S}=t;m.trigger(E.ERROR,{type:Z.NETWORK_ERROR,details:D.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:f,reason:f.message,level:t.level||void 0,parent:(d=n.fragments[0])==null?void 0:d.type,networkDetails:S,stats:a});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=a.loading.start);const g=this.hls.mainForwardBufferInfo,y=g?g.end-g.len:0,x=(n.edge-y)*1e3,v=Fd(n,x);if(n.requestScheduled+v<h?n.requestScheduled=h:n.requestScheduled+=v,this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED"}`),!this.canLoad||!n.live)return;let _,o,c;if(n.canBlockReload&&n.endSN&&n.advanced){const f=this.hls.config.lowLatencyMode,m=n.lastPartSn,S=n.endSN,T=n.lastPartIndex,b=T!==-1,A=m===S;b?A?(o=S+1,c=f?0:T):(o=m,c=f?T+1:n.maxPartIndex):o=S+1;const I=n.age,L=I+n.ageHeader;let w=Math.min(L-n.partTarget,n.targetduration*1.5);if(w>0){if(L>n.targetduration*3)this.log(`Playlist last advanced ${I.toFixed(2)}s ago. Omitting segment and part directives.`),o=void 0,c=void 0;else if(s!=null&&s.tuneInGoal&&L-n.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${w} with playlist age: ${n.age}`),w=0;else{const R=Math.floor(w/n.targetduration);if(o+=R,c!==void 0){const M=Math.round(w%n.targetduration/n.partTarget);c+=M}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${I.toFixed(2)}s goal: ${w} skip sn ${R} to part ${c}`)}n.tuneInGoal=w}if(_=this.getDeliveryDirectives(n,t.deliveryDirectives,o,c),f||!A){n.requestScheduled=h,this.loadingPlaylist(p,_);return}}else(n.canBlockReload||n.canSkipUntil)&&(_=this.getDeliveryDirectives(n,t.deliveryDirectives,o,c));_&&o!==void 0&&n.canBlockReload&&(n.requestScheduled=a.loading.first+Math.max(v-l*2,v/2)),this.scheduleLoading(p,_,n)}else this.clearTimer()}scheduleLoading(e,t,s){const n=s||e.details;if(!n){this.loadingPlaylist(e,t);return}const a=self.performance.now(),h=n.requestScheduled;if(a>=h){this.loadingPlaylist(e,t);return}const l=h-a;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(l)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),l)}getDeliveryDirectives(e,t,s,n){let a=Vl(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,n=t.part,a=Fn.No),new Kl(s,n,a)}checkRetry(e){const t=e.details,s=er(e),n=e.errorAction,{action:a,retryCount:h=0,retryConfig:l}=n||{},u=!!n&&!!l&&(a===He.RetryRequest||!n.resolved&&a===He.SendAlternateToPenaltyBox);if(u){var d;if(h>=l.maxNumRetry)return!1;if(s&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${h+1}/${l.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const p=Do(l,h);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),p),this.warn(`Retrying playlist loading ${h+1}/${l.maxNumRetry} after "${t}" in ${p}ms`)}e.levelRetry=!0,n.resolved=!0}return u}}function ou(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!Ws(r[t].attrs,e[t].attrs))return!1;return!0}function Ws(r,e,t){const s=r["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(n=>r[n]!==e[n])}function Za(r,e){return e.label.toLowerCase()===r.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(r.lang||"").toLowerCase())}class lv extends Ko{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(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.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:s,groupId:n,details:a}=t,h=this.tracksInGroup[s];if(!h||h.groupId!==n){this.warn(`Audio track with id:${s} and group:${n} not found in active group ${h==null?void 0:h.groupId}`);return}const l=h.details;h.details=t.details,this.log(`Audio track ${s} "${h.name}" lang:${h.lang} group:${n} loaded [${a.startSN}-${a.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,l)}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 s=t.audioGroups||null,n=this.groupIds;let a=this.currentTrack;if(!s||(n==null?void 0:n.length)!==(s==null?void 0:s.length)||s!=null&&s.some(l=>(n==null?void 0:n.indexOf(l))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const l=this.tracks.filter(y=>!s||s.indexOf(y.groupId)!==-1);if(l.length)this.selectDefaultTrack&&!l.some(y=>y.default)&&(this.selectDefaultTrack=!1),l.forEach((y,x)=>{y.id=x});else if(!a&&!this.tracksInGroup.length)return;this.tracksInGroup=l;const u=this.hls.config.audioPreference;if(!a&&u){const y=Ft(u,l,ki);if(y>-1)a=l[y];else{const x=Ft(u,this.tracks);a=this.tracks[x]}}let d=this.findTrackId(a);d===-1&&a&&(d=this.findTrackId(null));const p={audioTracks:l};this.log(`Updating audio tracks, ${l.length} track(s) found in group(s): ${s==null?void 0:s.join(",")}`),this.hls.trigger(E.AUDIO_TRACKS_UPDATED,p);const g=this.trackId;if(d!==-1&&g===-1)this.setAudioTrack(d);else if(l.length&&g===-1){var h;const y=new Error(`No audio track selected for current audio group-ID(s): ${(h=this.groupIds)==null?void 0:h.join(",")} track count: ${l.length}`);this.warn(y.message),this.hls.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:y})}}}onError(e,t){t.fatal||!t.context||t.context.type===fe.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 s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const n=this.currentTrack;if(n&&Bi(e,n,ki))return n;const a=Ft(e,this.tracksInGroup,ki);if(a>-1){const h=this.tracksInGroup[a];return this.setAudioTrack(a),h}else if(n){let h=t.loadLevel;h===-1&&(h=t.firstAutoLevel);const l=Sm(e,t.levels,s,h,ki);if(l===-1)return null;t.nextLoadLevel=l}if(e.channels||e.audioCodec){const h=Ft(e,s);if(h>-1)return s[h]}}}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 s=this.currentTrack,n=t[e],a=n.details&&!n.details.live;if(e===this.trackId&&n===s&&a||(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(E.AUDIO_TRACK_SWITCHING,xe({},n)),a))return;const h=this.switchParams(n.url,s==null?void 0:s.details,n.details);this.loadPlaylist(h)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const n=t[s];if(!(this.selectDefaultTrack&&!n.default)&&(!e||Bi(e,n,ki)))return s}if(e){const{name:s,lang:n,assocLang:a,characteristics:h,audioCodec:l,channels:u}=e;for(let d=0;d<t.length;d++){const p=t[d];if(Bi({name:s,lang:n,assocLang:a,characteristics:h,audioCodec:l,channels:u},p,ki))return d}for(let d=0;d<t.length;d++){const p=t[d];if(Ws(e.attrs,p.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(let d=0;d<t.length;d++){const p=t[d];if(Ws(e.attrs,p.attrs,["LANGUAGE"]))return d}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Jn(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,t),h=e.details,l=h==null?void 0:h.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${l&&h.live?" age "+l.toFixed(1)+(h.type&&" "+h.type||""):""} ${a}`),this.hls.trigger(E.AUDIO_TRACK_LOADING,{url:a,id:s,groupId:n,deliveryDirectives:t||null,track:e})}}class hv{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const n=this.queues[t];n.push(e),n.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="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(a){var s;if(n.onError(a),this.queues===null||this.tracks===null)return;const h=(s=this.tracks[e])==null?void 0:s.buffer;h!=null&&h.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>":`
|
|
127
127
|
${this.list("video")}
|
|
128
128
|
${this.list("audio")}
|
|
129
|
-
${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],n=s==null?void 0:s.buffer;return n?`SourceBuffer${n.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}}const
|
|
130
|
-
required tracks: ${
|
|
131
|
-
transfer tracks: ${Ae(n,(u,d)=>u==="initSegment"?void 0:d)}}`),!Gc(n,s)){t.mediaSource=null,t.tracks=void 0;const u=e.currentTime,d=this.details,p=Math.max(u,(d==null?void 0:d.fragments[0].start)||0);if(p-u>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${u} -> ${p}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(s)}") start time: ${p} currentTime: ${u}`),this.onMediaDetaching(_.MEDIA_DETACHING,{}),this.onMediaAttaching(_.MEDIA_ATTACHING,t),e.currentTime=p;return}this.transferData=void 0,a.forEach(u=>{const d=u,p=n[d];if(p){const g=p.buffer;if(g){const y=this.fragmentTracker,v=p.id;if(y.hasFragments(v)||y.hasParts(v)){const o=ce.getBuffered(g);y.detectEvictedFragments(d,o,v,null,!0)}const x=ra(d),E=[d,g];this.sourceBuffers[x]=E,g.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,p)}}}),l(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),l()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:a,_objectUrl:h}=this;if(a){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([l])=>{l&&this.removeBuffer(l)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const l=a.readyState==="open";try{const u=a.sourceBuffers;for(let d=u.length;d--;)l&&u[d].abort(),a.removeSourceBuffer(u[d]);l&&a.endOfStream()}catch(u){this.warn(`onMediaDetaching: ${u.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}a.removeEventListener("sourceopen",this._onMediaSourceOpen),a.removeEventListener("sourceended",this._onMediaSourceEnded),a.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(a.removeEventListener("startstreaming",this._onStartStreaming),a.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),s||(h&&self.URL.revokeObjectURL(h),this.mediaSrc===h?(n.removeAttribute("src"),this.appendSource&&ph(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(_.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(a){this.warn(`onBufferReset ${e}`,a)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[ra(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Fy(this.tracks)}onBufferCodecs(e,t){const s=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),h=!a&&this.sourceBufferCount&&this.media&&n.some(l=>!s[l]);if(a||h){this.warn(`Unsupported transition between "${Object.keys(s)}" and "${n}" SourceBuffers`);return}n.forEach(l=>{var u,d,p;const g=t[l],{id:y,codec:v,levelCodec:x,container:E,metadata:o,supplemental:c}=g;let f=s[l];const m=(u=this.transferData)==null||(d=u.tracks)==null?void 0:d[l],S=m!=null&&m.buffer?m:f,T=(S==null?void 0:S.pendingCodec)||(S==null?void 0:S.codec),b=S==null?void 0:S.levelCodec;f||(f=s[l]={buffer:void 0,listeners:[],codec:v,supplemental:c,container:E,levelCodec:x,metadata:o,id:y});const A=bn(T,b),I=A==null?void 0:A.replace(fh,"$1");let L=bn(v,x);const w=(p=L)==null?void 0:p.replace(fh,"$1");L&&A&&I!==w&&(l.slice(0,5)==="audio"&&(L=Gn(L,this.appendSource)),this.log(`switching codec ${T} to ${L}`),L!==(f.pendingCodec||f.codec)&&(f.pendingCodec=L),f.container=E,this.appendChangeType(l,E,L))}),(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 s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const n=`${t};codecs=${s}`,a={label:`change-type=${n}`,execute:()=>{const h=this.tracks[e];if(h){const l=h.buffer;l!=null&&l.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),l.changeType(n),h.codec=s,h.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:h=>{this.warn(`Failed to change ${e} SourceBuffer type`,h)}};this.append(a,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,n=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,X.MAIN))==null?void 0:t.gap)===!0)return;const h={label:"block-audio",execute:()=>{var l;const u=this.tracks.video;(this.lastVideoAppendEnd>n||u!=null&&u.buffer&&ce.isBuffered(u.buffer,n)||((l=this.fragmentTracker.getAppendedFrag(n,X.MAIN))==null?void 0:l.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:l=>{this.warn("Error executing block-audio operation",l)}};this.blockedAudioAppend={op:h,frag:e},this.append(h,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:n,type:a,parent:h,frag:l,part:u,chunkMeta:d}=t,p=d.buffering[a],g=l.sn,y=self.performance.now();p.start=y;const v=l.stats.buffering,x=u?u.stats.buffering:null;v.start===0&&(v.start=y),x&&x.start===0&&(x.start=y);const E=s.audio;let o=!1;a==="audio"&&(E==null?void 0:E.container)==="audio/mpeg"&&(o=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const c=this.tracks.video,f=c==null?void 0:c.buffer;if(f&&g!=="initSegment"){const T=u||l,b=this.blockedAudioAppend;if(a==="audio"&&h!=="main"&&!this.blockedAudioAppend){const I=T.start+T.duration*.05,L=f.buffered,w=this.currentOp("video");!L.length&&!w?this.blockAudio(T):!w&&!ce.isBuffered(f,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(T)}else if(a==="video"){const A=T.end;if(b){const I=b.frag.start;(A>I||A<this.lastVideoAppendEnd||ce.isBuffered(f,I))&&this.unblockAudio()}this.lastVideoAppendEnd=A}}const m=(u||l).start,S={label:`append-${a}`,execute:()=>{if(p.executeStart=self.performance.now(),o){const T=this.tracks[a];if(T){const b=T.buffer;if(b){const A=m-b.timestampOffset;Math.abs(A)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${m} (delta: ${A}) sn: ${g})`),b.timestampOffset=m)}}}this.appendExecutor(n,a)},onStart:()=>{},onComplete:()=>{const T=self.performance.now();p.executeEnd=p.end=T,v.first===0&&(v.first=T),x&&x.first===0&&(x.first=T);const b={};this.sourceBuffers.forEach(([A,I])=>{A&&(b[A]=ce.getBuffered(I))}),this.appendErrors[a]=0,a==="audio"||a==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(_.BUFFER_APPENDED,{type:a,frag:l,part:u,chunkMeta:d,parent:l.type,timeRanges:b})},onError:T=>{var b;const A={type:Q.MEDIA_ERROR,parent:l.type,details:P.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:l,part:u,chunkMeta:d,error:T,err:T,fatal:!1},I=(b=this.media)==null?void 0:b.error;if(T.code===DOMException.QUOTA_EXCEEDED_ERR)A.details=P.BUFFER_FULL_ERROR;else if(T.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!I)A.errorAction=ks(!0);else if(T.name===Gd&&this.sourceBufferCount===0)A.errorAction=ks(!0);else{const L=++this.appendErrors[a];this.warn(`Failed ${L}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer (${I||"no media error"})`),(L>=this.hls.config.appendErrorMaxRetry||I)&&(A.fatal=!0)}this.hls.trigger(_.ERROR,A)}};this.append(S,a,this.isPending(this.tracks[a]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(_.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:s,startOffset:n,endOffset:a}=t;s?this.append(this.getFlushOp(s,n,a),s):this.sourceBuffers.forEach(([h])=>{h&&this.append(this.getFlushOp(h,n,a),h)})}onFragParsed(e,t){const{frag:s,part:n}=t,a=[],h=n?n.elementaryStreams:s.elementaryStreams;h[Ee.AUDIOVIDEO]?a.push("audiovideo"):(h[Ee.AUDIO]&&a.push("audio"),h[Ee.VIDEO]&&a.push("video"));const l=()=>{const u=self.performance.now();s.stats.buffering.end=u,n&&(n.stats.buffering.end=u);const d=n?n.stats:s.stats;this.hls.trigger(_.FRAG_BUFFERED,{frag:s,part:n,stats:d,id:s.type})};a.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(l,a).catch(u=>{this.warn(`Fragment buffered callback ${u}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t,s;return e&&(!((t=this.tracks[e])!=null&&t.ended)||((s=this.tracks[e])==null?void 0:s.ending))})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([h])=>{if(h){const l=this.tracks[h];(!t.type||t.type===h)&&(l.ending=!0,l.ended||(l.ended=!0,this.log(`${h} buffer reached EOS`)))}});const n=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([h])=>{var l;return h&&!((l=this.tracks[h])!=null&&l.ended)})&&(n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:h}=this;if(!h||h.readyState!=="open"){h&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${h.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),h.endOfStream(),this.hls.trigger(_.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(_.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===P.BUFFER_APPEND_ERROR&&t.frag){var s;const n=(s=t.errorAction)==null?void 0:s.nextAutoLevel;K(n)&&n!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;const n=e.config,a=s.currentTime,h=t.levelTargetDuration,l=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(K(l)&&l>=0){const u=Math.max(l,h),d=Math.floor(a/h)*h-u;this.flushBackBuffer(a,h,d)}if(K(n.frontBufferFlushThreshold)&&n.frontBufferFlushThreshold>0){const u=Math.max(n.maxBufferLength,n.frontBufferFlushThreshold),d=Math.max(u,h),p=Math.floor(a/h)*h+d;this.flushFrontBuffer(a,h,p)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([n,a])=>{if(a){const l=ce.getBuffered(a);if(l.length>0&&s>l.start(0)){var h;this.hls.trigger(_.BACK_BUFFER_REACHED,{bufferEnd:s});const u=this.tracks[n];if((h=this.details)!=null&&h.live)this.hls.trigger(_.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(u!=null&&u.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(_.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:n})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([n,a])=>{if(a){const h=ce.getBuffered(a),l=h.length;if(l<2)return;const u=h.start(l-1),d=h.end(l-1);if(s>u||e>=u&&e<=d)return;this.hls.trigger(_.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||(s==null?void 0:s.readyState)!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&s.setLiveSeekableRange){const d=Math.max(0,t.fragmentStart),p=Math.max(d,n);return{duration:1/0,start:d,end:p}}return{duration:1/0}}const a=(e=this.overrides)==null?void 0:e.duration;if(a)return K(a)?{duration:a}:null;const h=this.media.duration,l=K(s.duration)?s.duration:0;return n>l&&n>h||!K(h)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:s}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(K(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${s}.`),n.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Ae(s)}`),this.tracksReady){var n;const a=(n=this.transferData)==null?void 0:n.tracks;a&&Object.keys(a).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const n=this.tracks[t];e[t]={buffer:s,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger(_.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(_.ERROR,{type:Q.MEDIA_ERROR,details:P.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const a in e){const h=a,l=e[h];if(this.isPending(l)){const u=this.getTrackCodec(l,h),d=`${l.container};codecs=${u}`;l.codec=u,this.log(`creating sourceBuffer(${d})${this.currentOp(h)?" Queued":""} ${Ae(l)}`);try{const p=s.addSourceBuffer(d),g=ra(h),y=[h,p];t[g]=y,l.buffer=p}catch(p){var n;this.error(`error while trying to add sourceBuffer: ${p.message}`),this.shiftAndExecuteNext(h),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[h],this.hls.trigger(_.ERROR,{type:Q.MEDIA_ERROR,details:P.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:p,sourceBufferName:h,mimeType:d,parent:l.id});return}this.trackSourceBuffer(h,l)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let n=e.codec;s&&(t==="video"||t==="audiovideo")&&Da(s,"video")&&(n=C0(n,s));const a=bn(n,e.levelCodec);return a?t.slice(0,5)==="audio"?Gn(a,this.appendSource):a:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,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",(a,h)=>{const l=h.removedRanges;l!=null&&l.length&&this.hls.trigger(_.BUFFER_FLUSHED,{type:a})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s==null?void 0:s.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 s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${n}`,t),this.hls.trigger(_.ERROR,{type:Q.MEDIA_ERROR,details:P.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const a=this.currentOp(e);a&&a.onError(n)}removeExecutor(e,t,s){const{media:n,mediaSource:a}=this,h=this.tracks[e],l=h==null?void 0:h.buffer;if(!n||!a||!l){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const u=K(n.duration)?n.duration:1/0,d=K(a.duration)?a.duration:1/0,p=Math.max(0,t),g=Math.min(s,u,d);g>p&&(!h.ending||h.ended)?(h.ended=!1,this.log(`Removing [${p},${g}] from the ${e} SourceBuffer`),l.remove(p,g)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],n=s==null?void 0:s.buffer;if(!n)throw new Uy(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.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:s}=this,n=t.map(h=>this.appendBlocker(h));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(h=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const n=(s=this.tracks[t])==null?void 0:s.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}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,s){const n=this.tracks[e];if(!n)return;const a=n.buffer;if(!a)return;const h=s.bind(this,e);n.listeners.push({event:t,listener:h}),a.addEventListener(t,h)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(n=>{s.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}}function ph(r){const e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function By(r,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}function ra(r){return r==="audio"?1:0}class Po{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(_.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(_.MANIFEST_PARSED,this.onManifestParsed,this),e.on(_.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(_.BUFFER_CODECS,this.onBufferCodecs,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(_.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(_.MANIFEST_PARSED,this.onManifestParsed,this),e.off(_.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(_.BUFFER_CODECS,this.onBufferCodecs,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.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 s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&K(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,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,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 s=t.filter((n,a)=>this.isLevelAllowed(n)&&a<=e);return this.clientRect=null,Po.getMaxLevelByMediaSize(s,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 s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.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(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const n=(l,u)=>u?l.width!==u.width||l.height!==u.height:!0;let a=e.length-1;const h=Math.max(t,s);for(let l=0;l<e.length;l+=1){const u=e[l];if((u.width>=h||u.height>=h)&&n(u,e[l+1])){a=l;break}}return a}}const Ny={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Xe=Ny,$y={HLS:"h"},Gy=$y,zy="CMCD-Object",Hy="CMCD-Request",Vy="CMCD-Session",Ky="CMCD-Status",vs={OBJECT:zy,REQUEST:Hy,SESSION:Vy,STATUS:Ky},Yy={[vs.OBJECT]:["br","d","ot","tb"],[vs.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[vs.SESSION]:["cid","pr","sf","sid","st","v"],[vs.STATUS]:["bs","rtp"]};class os{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof os?s:new os(s))),this.value=e,this.params=t}}const Wy="Dict";function jy(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 qy(r,e,t,s){return new Error(`failed to ${r} "${jy(e)}" as ${t}`,{cause:s})}function Mt(r,e,t){return qy("serialize",r,e,t)}class zd{constructor(e){this.description=e}}const gh="Bare Item",Xy="Boolean";function Qy(r){if(typeof r!="boolean")throw Mt(r,Xy);return r?"?1":"?0"}const Zy="Byte Sequence";function Jy(r){if(ArrayBuffer.isView(r)===!1)throw Mt(r,Zy);return`:${jm(r)}:`}const ex="Integer";function tx(r){return r<-999999999999999||999999999999999<r}function Hd(r){if(tx(r))throw Mt(r,ex);return r.toString()}function ix(r){return`@${Hd(r.getTime()/1e3)}`}const sx="Decimal";function nx(r){const e=Id(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Mt(r,sx);const t=e.toString();return t.includes(".")?t:`${t}.0`}const rx="String",ax=/[\x00-\x1f\x7f]+/;function ox(r){if(ax.test(r))throw Mt(r,rx);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function lx(r){return r.description||r.toString().slice(7,-1)}const hx="Token";function mh(r){const e=lx(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Mt(e,hx);return e}function $a(r){switch(typeof r){case"number":if(!K(r))throw Mt(r,gh);return Number.isInteger(r)?Hd(r):nx(r);case"string":return ox(r);case"symbol":return mh(r);case"boolean":return Qy(r);case"object":if(r instanceof Date)return ix(r);if(r instanceof Uint8Array)return Jy(r);if(r instanceof zd)return mh(r);default:throw Mt(r,gh)}}const cx="Key";function Ga(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw Mt(r,cx);return r}function ko(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${Ga(e)}`:`;${Ga(e)}=${$a(t)}`).join("")}function Vd(r){return r instanceof os?`${$a(r.value)}${ko(r.params)}`:$a(r)}function dx(r){return`(${r.value.map(Vd).join(" ")})${ko(r.params)}`}function ux(r,e={whitespace:!0}){if(typeof r!="object")throw Mt(r,Wy);const t=r instanceof Map?r.entries():Object.entries(r),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([n,a])=>{a instanceof os||(a=new os(a));let h=Ga(n);return a.value===!0?h+=ko(a.params):(h+="=",Array.isArray(a.value)?h+=dx(a):h+=Vd(a)),h}).join(`,${s}`)}function fx(r,e){return ux(r,e)}function px(r){return r==="ot"||r==="sf"||r==="st"}function gx(r){return typeof r=="number"?K(r):r!=null&&r!==""&&r!==!1}const Ln=r=>Math.round(r),mx=(r,e)=>(e!=null&&e.baseUrl&&(r=qm(r,e.baseUrl)),encodeURIComponent(r)),un=r=>Ln(r/100)*100,yx={br:Ln,d:Ln,bl:un,dl:un,mtp:un,nor:mx,rtp:un,tb:Ln};function xx(r,e){const t={};if(r==null||typeof r!="object")return t;const s=Object.keys(r).sort(),n=Te({},yx,e==null?void 0:e.formatters),a=e==null?void 0:e.filter;return s.forEach(h=>{if(a!=null&&a(h))return;let l=r[h];const u=n[h];u&&(l=u(l,e)),!(h==="v"&&l===1)&&(h=="pr"&&l===1||gx(l)&&(px(h)&&typeof l=="string"&&(l=new zd(l)),t[h]=l))}),t}function Kd(r,e={}){return r?fx(xx(r,e),Te({whitespace:!1},e)):""}function vx(r,e={}){const t={};if(!r)return t;const s=Object.entries(r),n=Object.entries(Yy).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),a=s.reduce((h,l)=>{var u,d;const[p,g]=l,y=((u=n.find(v=>v[1].includes(p)))===null||u===void 0?void 0:u[0])||vs.REQUEST;return(d=h[y])!==null&&d!==void 0||(h[y]={}),h[y][p]=g,h},{});return Object.entries(a).reduce((h,[l,u])=>(h[l]=Kd(u,e),h),t)}function Sx(r,e,t){return Te(r,vx(e,t))}const _x="CMCD";function Ex(r,e={}){if(!r)return"";const t=Kd(r,e);return`${_x}=${encodeURIComponent(t)}`}const yh=/CMCD=[^&#]+/;function Tx(r,e,t){const s=Ex(e,t);if(!s)return r;if(yh.test(r))return r.replace(yh,s);const n=r.includes("?")?"&":"?";return`${r}${n}${s}`}class bx{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:Xe.MANIFEST,su:!this.initialized})}catch(a){this.hls.logger.warn("Could not generate manifest CMCD data.",a)}},this.applyFragmentData=n=>{try{const{frag:a,part:h}=n,l=this.hls.levels[a.level],u=this.getObjectType(a),d={d:(h||a).duration*1e3,ot:u};(u===Xe.VIDEO||u===Xe.AUDIO||u==Xe.MUXED)&&(d.br=l.bitrate/1e3,d.tb=this.getTopBandwidth(u)/1e3,d.bl=this.getBufferLength(u));const p=h?this.getNextPart(h):this.getNextFrag(a);p!=null&&p.url&&p.url!==a.url&&(d.nor=p.url),this.apply(n,d)}catch(a){this.hls.logger.warn("Could not generate segment CMCD data.",a)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(_.MEDIA_DETACHED,this.onMediaDetached,this),e.on(_.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(_.MEDIA_DETACHED,this.onMediaDetached,this),e.off(_.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 s,n;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:Gy.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Te(t,this.createData());const s=t.ot===Xe.INIT||t.ot===Xe.VIDEO||t.ot===Xe.MUXED;this.starved&&s&&(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((h,l)=>(n.includes(l)&&(h[l]=t[l]),h),{}));const a={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Sx(e.headers,t,a)):e.url=Tx(e.url,t,a)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const n=e.sn-s.startSN;return s.fragments[n+1]}}getNextPart(e){var t,s;const{index:n,fragment:a}=e,h=(t=this.hls.levels[a.level])==null||(s=t.details)==null?void 0:s.partList;if(h){const{sn:l}=a;for(let u=h.length-1;u>=0;u--){const d=h[u];if(d.index===n&&d.fragment.sn===l)return h[u+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Xe.TIMED_TEXT;if(e.sn==="initSegment")return Xe.INIT;if(t==="audio")return Xe.AUDIO;if(t==="main")return this.hls.audioTracks.length?Xe.VIDEO:Xe.MUXED}getTopBandwidth(e){let t=0,s;const n=this.hls;if(e===Xe.AUDIO)s=n.audioTracks;else{const a=n.maxAutoLevel,h=a>-1?a+1:n.levels.length;s=n.levels.slice(0,h)}for(const a of s)a.bitrate>t&&(t=a.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===Xe.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:ce.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(a){this.loader=void 0,this.loader=new s(a)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(a,h,l){t(a),this.loader.load(a,h,l)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(a){this.loader=void 0,this.loader=new s(a)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(a,h,l){t(a),this.loader.load(a,h,l)}}}}const Ax=3e5;class Ix extends Jt{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(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(_.MANIFEST_PARSED,this.onManifestParsed,this),e.on(_.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(_.MANIFEST_PARSED,this.onManifestParsed,this),e.off(_.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(s=>s!==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:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((s==null?void 0:s.action)===Ve.SendAlternateToPenaltyBox&&s.flags===gt.MoveAllAlternatesMatchingHost){const n=this.levels;let a=this._pathwayPriority,h=this.pathwayId;if(t.context){const{groupId:l,pathwayId:u,type:d}=t.context;l&&n?h=this.getPathwayForGroupId(l,d,h):u&&(h=u)}h in this.penalizedPathways||(this.penalizedPathways[h]=performance.now()),!a&&n&&(a=this.pathways()),a&&a.length>1&&(this.updatePathwayPriority(a),s.resolved=this.pathwayId!==h),s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${h} levels: ${n&&n.length} priorities: ${Ae(a)} penalized: ${Ae(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}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 s=this.penalizedPathways,n=performance.now();Object.keys(s).forEach(a=>{n-s[a]>Ax&&delete s[a]});for(let a=0;a<e.length;a++){const h=e[a];if(h in s)continue;if(h===this.pathwayId)return;const l=this.hls.nextLoadLevel,u=this.hls.levels[l];if(t=this.getLevelsForPathway(h),t.length>0){this.log(`Setting Pathway to "${h}"`),this.pathwayId=h,md(t),this.hls.trigger(_.LEVELS_UPDATED,{levels:t});const d=this.hls.levels[l];u&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==u.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==u.bitrate&&this.log(`Unstable Pathways change from bitrate ${u.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=l);break}}}getPathwayForGroupId(e,t,s){const n=this.getLevelsForPathway(s).concat(this.levels||[]);for(let a=0;a<n.length;a++)if(t===ue.AUDIO_TRACK&&n[a].hasAudioGroup(e)||t===ue.SUBTITLE_TRACK&&n[a].hasSubtitleGroup(e))return n[a].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},n={};e.forEach(a=>{const{ID:h,"BASE-ID":l,"URI-REPLACEMENT":u}=a;if(t.some(p=>p.pathwayId===h))return;const d=this.getLevelsForPathway(l).map(p=>{const g=new Ie(p.attrs);g["PATHWAY-ID"]=h;const y=g.AUDIO&&`${g.AUDIO}_clone_${h}`,v=g.SUBTITLES&&`${g.SUBTITLES}_clone_${h}`;y&&(s[g.AUDIO]=y,g.AUDIO=y),v&&(n[g.SUBTITLES]=v,g.SUBTITLES=v);const x=Yd(p.uri,g["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",u),E=new Ps({attrs:g,audioCodec:p.audioCodec,bitrate:p.bitrate,height:p.height,name:p.name,url:x,videoCodec:p.videoCodec,width:p.width});if(p.audioGroups)for(let o=1;o<p.audioGroups.length;o++)E.addGroupId("audio",`${p.audioGroups[o]}_clone_${h}`);if(p.subtitleGroups)for(let o=1;o<p.subtitleGroups.length;o++)E.addGroupId("text",`${p.subtitleGroups[o]}_clone_${h}`);return E});t.push(...d),xh(this.audioTracks,s,u,h),xh(this.subtitleTracks,n,u,h)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(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 p=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+p)}const a={responseType:"json",url:n.href},h=t.steeringManifestLoadPolicy.default,l=h.errorRetry||h.timeoutRetry||{},u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},d={onSuccess:(p,g,y,v)=>{this.log(`Loaded steering manifest: "${n}"`);const x=p.data;if((x==null?void 0:x.VERSION)!==1){this.log(`Steering VERSION ${x.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=x.TTL;const{"RELOAD-URI":E,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":c}=x;if(E)try{this.uri=new self.URL(E,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${E}`);return}this.scheduleRefresh(this.uri||y.url),o&&this.clonePathways(o);const f={steeringManifest:x,url:n.toString()};this.hls.trigger(_.STEERING_MANIFEST_LOADED,f),c&&this.updatePathwayPriority(c)},onError:(p,g,y,v)=>{if(this.log(`Error loading steering manifest: ${p.code} ${p.text} (${g.url})`),this.stopLoad(),p.code===410){this.enabled=!1,this.log(`Steering manifest ${g.url} no longer available`);return}let x=this.timeToLoad*1e3;if(p.code===429){const E=this.loader;if(typeof(E==null?void 0:E.getResponseHeader)=="function"){const o=E.getResponseHeader("Retry-After");o&&(x=parseFloat(o)*1e3)}this.log(`Steering manifest ${g.url} rate limited`);return}this.scheduleRefresh(this.uri||g.url,x)},onTimeout:(p,g,y)=>{this.log(`Timeout loading steering manifest (${g.url})`),this.scheduleRefresh(this.uri||g.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(a,u,d)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const n=(s=this.hls)==null?void 0:s.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function xh(r,e,t,s){r&&Object.keys(e).forEach(n=>{const a=r.filter(h=>h.groupId===n).map(h=>{const l=Te({},h);return l.details=void 0,l.attrs=new Ie(l.attrs),l.url=l.attrs.URI=Yd(h.url,h.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),l.groupId=l.attrs["GROUP-ID"]=e[n],l.attrs["PATHWAY-ID"]=s,l});r.push(...a)})}function Yd(r,e,t,s){const{HOST:n,PARAMS:a,[t]:h}=s;let l;e&&(l=h==null?void 0:h[e],l&&(r=l));const u=new self.URL(r);return n&&!l&&(u.host=n),a&&Object.keys(a).sort().forEach(d=>{d&&u.searchParams.set(d,a[d])}),u.href}class Ji extends Jt{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=Ji.CDMCleanupPromise?[Ji.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:s,initData:n}=t,a=`"${t.type}" event: init data type: "${s}"`;if(this.debug(a),n!==null){if(!this.keyFormatPromise){let h=Object.keys(this.keySystemAccessPromises);h.length||(h=ln(this.config));const l=h.map(Qr).filter(u=>!!u);this.keyFormatPromise=this.getKeyFormatPromise(l)}this.keyFormatPromise.then(h=>{const l=qr(h);let u,d;if(s==="sinf"){if(l!==ve.FAIRPLAY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${s}" for selected key-system ${l}`);return}const x=Pe(new Uint8Array(n));try{const E=Eo(JSON.parse(x).sinf),o=jc(E);if(!o)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");u=new Uint8Array(o.subarray(8,24)),d=ve.FAIRPLAY}catch(E){this.warn(`${a} Failed to parse sinf: ${E}`);return}}else{if(l!==ve.WIDEVINE&&l!==ve.PLAYREADY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${s}" for selected key-system ${l}`);return}const x=I0(n),E=x.filter(c=>!!c.systemId&&Xr(c.systemId)===l);E.length>1&&this.warn(`${a} Using first of ${E.length} pssh found for selected key-system ${l}`);const o=E[0];if(!o){x.length===0||x.some(c=>!c.systemId)?this.warn(`${a} contains incomplete or invalid pssh data`):this.log(`ignoring ${a} for ${x.map(c=>Xr(c.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(d=Xr(o.systemId),o.version===0&&o.data)if(d===ve.WIDEVINE){const c=o.data.length-22;u=new Uint8Array(o.data.subarray(c,c+16))}else d===ve.PLAYREADY&&(u=hd(o.data))}if(!d||!u)return;const p=Et.hexDump(u),{keyIdToKeySessionPromise:g,mediaKeySessions:y}=this;let v=g[p];for(let x=0;x<y.length;x++){const E=y[x],o=E.decryptdata;if(!o.keyId)continue;const c=Et.hexDump(o.keyId);if(p===c||o.uri.replace(/-/g,"").indexOf(p)!==-1){if(v=g[c],o.pssh)break;delete g[c],o.pssh=new Uint8Array(n),o.keyId=u,v=g[p]=v.then(()=>this.generateRequestWithPreferredKeySession(E,s,n,"encrypted-event-key-match")),v.catch(f=>this.handleError(f));break}}if(!v){if(d!==l){this.log(`Ignoring "${t.type}" event with ${d} init data for selected key-system ${l}`);return}v=g[p]=this.getKeySystemSelectionPromise([d]).then(({keySystem:x,mediaKeys:E})=>{var o;this.throwIfDestroyed();const c=new Ms("ISO-23001-7",p,(o=Qr(x))!=null?o:"");return c.pssh=new Uint8Array(n),c.keyId=u,this.attemptSetMediaKeys(x,E).then(()=>{this.throwIfDestroyed();const f=this.createMediaKeySessionContext({decryptdata:c,keySystem:x,mediaKeys:E});return this.generateRequestWithPreferredKeySession(f,s,n,"encrypted-event-no-match")})}),v.catch(x=>this.handleError(x))}})}},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(_.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(_.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(_.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(_.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(_.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(_.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(_.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(_.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,n=t[e];if(n)return n.licenseUrl;if(e===ve.WIDEVINE&&s)return s}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,s=t[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(h,l,u)=>!!h&&u.indexOf(h)===l,n=t.map(h=>h.audioCodec).filter(s),a=t.map(h=>h.videoCodec).filter(s);return n.length+a.length===0&&a.push("avc1.42e01e"),new Promise((h,l)=>{const u=d=>{const p=d.shift();this.getMediaKeysPromise(p,n,a).then(g=>h({keySystem:p,mediaKeys:g})).catch(g=>{d.length?u(d):g instanceof ot?l(g):l(new ot({type:Q.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_ACCESS,error:g,fatal:!0},g.message))})};u(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${s}`;return ld===null&&self.location.protocol==="http:"&&(n=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(n))}return s(e,t)}getMediaKeysPromise(e,t,s){const n=ym(e,t,s,this.config.drmSystemOptions),a=this.keySystemAccessPromises[e];let h=a==null?void 0:a.keySystemAccess;if(!h){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Ae(n)}`),h=this.requestMediaKeySystemAccess(e,n);const l=this.keySystemAccessPromises[e]={keySystemAccess:h};return h.catch(u=>{this.log(`Failed to obtain access to key-system "${e}": ${u}`)}),h.then(u=>{this.log(`Access for key-system "${u.keySystem}" obtained`);const d=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),l.mediaKeys=u.createMediaKeys().then(p=>(this.log(`Media-keys created for "${e}"`),d.then(g=>g?this.setMediaKeysServerCertificate(p,e,g):p))),l.mediaKeys.catch(p=>{this.error(`Failed to create media-keys for "${e}"}: ${p}`)}),l.mediaKeys})}return h.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Et.hexDump(e.keyId||[])}`);const n=s.createSession(),a={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(a),a}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),n=this.getKeyIdString(t),a="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(s,a,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 Et.hexDump(e.keyId)}updateKeySession(e,t){var s;const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyID ${Et.hexDump(((s=e.decryptdata)==null?void 0:s.keyId)||[])}
|
|
132
|
-
} (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,s)=>{const n=ln(this.config),a=e.map(qr).filter(h=>!!h&&n.indexOf(h)!==-1);return this.getKeySystemSelectionPromise(a).then(({keySystem:h})=>{const l=Qr(h);l?t(l):s(new Error(`Unable to find format for key-system "${h}"`))}).catch(s)})}loadKey(e){const t=e.keyInfo.decryptdata,s=this.getKeyIdString(t),n=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);let a=this.keyIdToKeySessionPromise[s];return a||(a=this.getKeySystemForKeyPromise(t).then(({keySystem:l,mediaKeys:u})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(l,u).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:l,mediaKeys:u,decryptdata:t}))))),(this.keyIdToKeySessionPromise[s]=a.then(l=>{const u="cenc",d=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(l,u,d,"playlist-key")})).catch(l=>this.handleError(l))),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof ot?this.hls.trigger(_.ERROR,e.data):this.hls.trigger(_.ERROR,{type:Q.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),s=this.keyIdToKeySessionPromise[t];if(!s){const n=qr(e.keyFormat),a=n?[n]:ln(this.config);return this.attemptKeySystemAccess(a)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=ln(this.config)),e.length===0)throw new ot({type:Q.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Ae({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(s).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}"`),s.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(a=>s.indexOf(a)===-1)})}generateRequestWithPreferredKeySession(e,t,s,n){var a,h;const l=(a=this.config.drmSystems)==null||(h=a[e.keySystem])==null?void 0:h.generateRequest;if(l)try{const x=l.call(this.hls,t,s,e);if(!x)throw new Error("Invalid response from configured generateRequest filter");t=x.initDataType,s=x.initData?x.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(x){var u;if(this.warn(x.message),(u=this.hls)!=null&&u.config.debug)throw x}if(s===null)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const d=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${n}": ${d} (init data type: ${t} length: ${s?s.byteLength:null})`);const p=new bo,g=e._onmessage=x=>{const E=e.mediaKeysSession;if(!E){p.emit("error",new Error("invalid state"));return}const{messageType:o,message:c}=x;this.log(`"${o}" message event for session "${E.sessionId}" message size: ${c.byteLength}`),o==="license-request"||o==="license-renewal"?this.renewLicense(e,c).catch(f=>{p.eventNames().length?p.emit("error",f):this.handleError(f)}):o==="license-release"?e.keySystem===ve.FAIRPLAY&&(this.updateKeySession(e,Ma("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${o}"`)},y=e._onkeystatuseschange=x=>{if(!e.mediaKeysSession){p.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const o=e.keyStatus;p.emit("keyStatus",o),o==="expired"&&(this.warn(`${e.keySystem} expired for key ${d}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",g),e.mediaKeysSession.addEventListener("keystatuseschange",y);const v=new Promise((x,E)=>{p.on("error",E),p.on("keyStatus",o=>{o.startsWith("usable")?x():o==="output-restricted"?E(new ot({type:Q.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):o==="internal-error"?E(new ot({type:Q.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${o}"`)):o==="expired"?E(new Error("key expired while generating request")):this.warn(`unhandled key status change "${o}"`)})});return e.mediaKeysSession.generateRequest(t,s).then(()=>{var x;this.log(`Request generated for key-session "${(x=e.mediaKeysSession)==null?void 0:x.sessionId}" keyId: ${d}`)}).catch(x=>{throw new ot({type:Q.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_SESSION,error:x,fatal:!1},`Error generating key-session request: ${x}`)}).then(()=>v).catch(x=>{throw p.removeAllListeners(),this.removeSession(e),x}).then(()=>(p.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,s)=>{if(typeof s=="string"&&typeof t=="object"){const n=s;s=t,t=n}this.log(`key status change "${t}" for keyStatuses keyId: ${Et.hexDump("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${Et.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,s=t.loader,n=new s(t),a=this.getServerCertificateUrl(e);return a?(this.log(`Fetching server certificate for "${e}"`),new Promise((h,l)=>{const u={responseType:"arraybuffer",url:a},d=t.certLoadPolicy.default,p={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(y,v,x,E)=>{h(y.data)},onError:(y,v,x,E)=>{l(new ot({type:Q.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:x,response:xe({url:u.url,data:void 0},y)},`"${e}" certificate request failed (${a}). Status: ${y.code} (${y.text})`))},onTimeout:(y,v,x)=>{l(new ot({type:Q.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:x,response:{url:u.url,data:void 0}},`"${e}" certificate request timed out (${a})`))},onAbort:(y,v,x)=>{l(new Error("aborted"))}};n.load(u,p,g)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((n,a)=>{e.setServerCertificate(s).then(h=>{this.log(`setServerCertificate ${h?"success":"not supported by CDM"} (${s==null?void 0:s.byteLength}) on "${t}"`),n(e)}).catch(h=>{a(new ot({type:Q.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:h,fatal:!0},h.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(n=>{throw new ot({type:Q.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:n,fatal:!0},n.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const n=new DOMParser().parseFromString(s,"application/xml"),a=n.querySelectorAll("HttpHeader");if(a.length>0){let p;for(let g=0,y=a.length;g<y;g++){var h,l;p=a[g];const v=(h=p.querySelector("name"))==null?void 0:h.textContent,x=(l=p.querySelector("value"))==null?void 0:l.textContent;v&&x&&e.setRequestHeader(v,x)}}const u=n.querySelector("Challenge"),d=u==null?void 0:u.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return Ma(atob(d))}setupLicenseXHR(e,t,s,n){const a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return a.call(this.hls,e,t,s,n)}).catch(h=>{if(!s.decryptdata)throw h;return e.open("POST",t,!0),a.call(this.hls,e,t,s,n)}).then(h=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:h||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((n,a)=>{const h=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${h}`);const l=new XMLHttpRequest;l.responseType="arraybuffer",l.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(l.readyState===4)if(l.status===200){this._requestLicenseFailureCount=0;let u=l.response;this.log(`License received ${u instanceof ArrayBuffer?u.byteLength:u}`);const d=this.config.licenseResponseCallback;if(d)try{u=d.call(this.hls,l,h,e)}catch(p){this.error(p)}n(u)}else{const u=s.errorRetry,d=u?u.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||l.status>=400&&l.status<500)a(new ot({type:Q.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:l,response:{url:h,data:void 0,code:l.status,text:l.statusText}},`License Request XHR failed (${h}). Status: ${l.status} (${l.statusText})`));else{const p=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${p} attempts left`),this.requestLicense(e,t).then(n,a)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=l,this.setupLicenseXHR(l,h,e,t).then(({xhr:u,licenseChallenge:d})=>{e.keySystem==ve.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(u,d)),u.send(d)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,s.removeEventListener("encrypted",this.onMediaEncrypted),s.removeEventListener("waitingforkey",this.onWaitingForKey),s.addEventListener("encrypted",this.onMediaEncrypted),s.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 s=this.mediaKeySessions;this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Ms.clearKeyUriToKeyIdMap();const n=s.length;Ji.CDMCleanupPromise=Promise.all(s.map(a=>this.removeSession(a)).concat(e==null||(t=e.setMediaKeys(null))==null?void 0:t.catch(a=>{var h;this.log(`Could not clear media keys: ${a}`),(h=this.hls)==null||h.trigger(_.ERROR,{type:Q.OTHER_ERROR,details:P.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))).then(()=>{n&&(this.log("finished closing key sessions and clearing media keys"),s.length=0)}).catch(a=>{var h;this.log(`Could not close sessions and clear media keys: ${a}`),(h=this.hls)==null||h.trigger(_.ERROR,{type:Q.OTHER_ERROR,details:P.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((n,a)=>(n.indexOf(a.keyFormat)===-1&&n.push(a.keyFormat),n),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s}=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),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);const{drmSystemOptions:a}=this.config;return(vm(a)?new Promise((l,u)=>{self.setTimeout(()=>u(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l)}):Promise.resolve()).catch(l=>{var u;this.log(`Could not remove session: ${l}`),(u=this.hls)==null||u.trigger(_.ERROR,{type:Q.OTHER_ERROR,details:P.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>t.close()).catch(l=>{var u;this.log(`Could not close session: ${l}`),(u=this.hls)==null||u.trigger(_.ERROR,{type:Q.OTHER_ERROR,details:P.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}}}Ji.CDMCleanupPromise=void 0;class ot 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 wx{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(_.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(_.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(_.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(_.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.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),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const n=performance.now();if(t){if(this.lastTime){const a=n-this.lastTime,h=s-this.lastDroppedFrames,l=t-this.lastDecodedFrames,u=1e3*h/a,d=this.hls;if(d.trigger(_.FPS_DROP,{currentDropped:h,currentDecoded:l,totalDroppedFrames:s}),u>0&&h>d.config.fpsDroppedMonitoringThreshold*l){let p=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+p),p>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=p)&&(p=p-1,d.trigger(_.FPS_DROP_LEVEL_CAPPING,{level:p,droppedLevel:d.currentLevel}),d.autoLevelCapping=p,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=s,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 Wd(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 jd(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(s){pe.debug(`[texttrack-utils]: ${s}`);try{const n=new self.TextTrackCue(e.startTime,e.endTime,e.text);n.id=e.id,r.addCue(n)}catch(n){pe.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(r.mode=t)}function Wi(r,e){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues)for(let s=r.cues.length;s--;)e&&r.cues[s].removeEventListener("enter",e),r.removeCue(r.cues[s]);t==="disabled"&&(r.mode=t)}function za(r,e,t,s){const n=r.mode;if(n==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){const a=Rx(r.cues,e,t);for(let h=0;h<a.length;h++)(!s||s(a[h]))&&r.removeCue(a[h])}n==="disabled"&&(r.mode=n)}function Lx(r,e){if(e<=r[0].startTime)return 0;const t=r.length-1;if(e>r[t].endTime)return-1;let s=0,n=t,a;for(;s<=n;)if(a=Math.floor((n+s)/2),e<r[a].startTime)n=a-1;else if(e>r[a].startTime&&s<t)s=a+1;else return a;return r[s].startTime-e<e-r[n].startTime?s:n}function Rx(r,e,t){const s=[],n=Lx(r,e);if(n>-1)for(let a=n,h=r.length;a<h;a++){const l=r[a];if(l.startTime>=e&&l.endTime<=t)s.push(l);else if(l.startTime>t)return s}return s}function Rn(r){const e=[];for(let t=0;t<r.length;t++){const s=r[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(r[t])}return e}class Cx extends Do{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 s=Rn(this.media.textTracks);for(let a=0;a<s.length;a++)if(s[a].mode==="hidden")t=s[a];else if(s[a].mode==="showing"){t=s[a];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(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.MANIFEST_PARSED,this.onManifestParsed,this),e.on(_.LEVEL_LOADING,this.onLevelLoading,this),e.on(_.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(_.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(_.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.MANIFEST_PARSED,this.onManifestParsed,this),e.off(_.LEVEL_LOADING,this.onLevelLoading,this),e.off(_.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(_.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(_.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 s=this.media;if(!s)return;const n=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,n)return;Rn(s.textTracks).forEach(h=>{Wi(h)})}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:s,groupId:n,details:a}=t,h=this.tracksInGroup[s];if(!h||h.groupId!==n){this.warn(`Subtitle track with id:${s} and group:${n} not found in active group ${h==null?void 0:h.groupId}`);return}const l=h.details;h.details=t.details,this.log(`Subtitle track ${s} "${h.name}" lang:${h.lang} group:${n} loaded [${a.startSN}-${a.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,l)}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 s=t.subtitleGroups||null,n=this.groupIds;let a=this.currentTrack;if(!s||(n==null?void 0:n.length)!==(s==null?void 0:s.length)||s!=null&&s.some(h=>(n==null?void 0:n.indexOf(h))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const h=this.tracks.filter(p=>!s||s.indexOf(p.groupId)!==-1);if(h.length)this.selectDefaultTrack&&!h.some(p=>p.default)&&(this.selectDefaultTrack=!1),h.forEach((p,g)=>{p.id=g});else if(!a&&!this.tracksInGroup.length)return;this.tracksInGroup=h;const l=this.hls.config.subtitlePreference;if(!a&&l){this.selectDefaultTrack=!1;const p=wt(l,h);if(p>-1)a=h[p];else{const g=wt(l,this.tracks);a=this.tracks[g]}}let u=this.findTrackId(a);u===-1&&a&&(u=this.findTrackId(null));const d={subtitleTracks:h};this.log(`Updating subtitle tracks, ${h.length} track(s) found in "${s==null?void 0:s.join(",")}" group-id`),this.hls.trigger(_.SUBTITLE_TRACKS_UPDATED,d),u!==-1&&this.trackId===-1&&this.setSubtitleTrack(u)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let n=0;n<t.length;n++){const a=t[n];if(!(s&&!a.default||!s&&!e)&&(!e||Ci(a,e)))return n}if(e){for(let n=0;n<t.length;n++){const a=t[n];if(Bs(e.attrs,a.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(let n=0;n<t.length;n++){const a=t[n];if(Bs(e.attrs,a.attrs,["LANGUAGE"]))return n}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const n=t[s];if(Na(n,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===ue.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 s=this.currentTrack;if(s&&Ci(e,s))return s;const n=wt(e,this.tracksInGroup);if(n>-1){const a=this.tracksInGroup[n];return this.setSubtitleTrack(n),a}else{if(s)return null;{const a=wt(e,t);if(a>-1)return t[a]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,t),h=e.details,l=h==null?void 0:h.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${l&&h.live?" age "+l.toFixed(1)+(h.type&&" "+h.type||""):""} ${a}`),this.hls.trigger(_.SUBTITLE_TRACK_LOADING,{url:a,id:s,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Rn(e.textTracks),s=this.currentTrack;let n;if(s&&(n=t.filter(a=>Na(s,a))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(a=>{a.mode!=="disabled"&&a!==n&&(a.mode="disabled")}),n){const a=this.subtitleDisplay?"showing":"hidden";n.mode!==a&&(n.mode=a)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!K(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,n=t[e]||null;if(this.trackId=e,this.currentTrack=n,this.toggleTrackModes(),!n){this.hls.trigger(_.SUBTITLE_TRACK_SWITCH,{id:e});return}const a=!!n.details&&!n.details.live;if(e===this.trackId&&n===s&&a)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:h,groupId:l="",name:u,type:d,url:p}=n;this.hls.trigger(_.SUBTITLE_TRACK_SWITCH,{id:h,groupId:l,name:u,type:d,url:p});const g=this.switchParams(n.url,s==null?void 0:s.details,n.details);this.loadPlaylist(g)}}function Is(r){let e=5381,t=r.length;for(;t;)e=e*33^r.charCodeAt(--t);return(e>>>0).toString()}const es=.025;let qn=function(r){return r[r.Point=0]="Point",r[r.Range=1]="Range",r}({});function Dx(r,e,t){return`${r.identifier}-${t+1}-${Is(e)}`}class Px{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 aa(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,s=aa(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=K(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 aa(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)<es))}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"?qn.Range:qn.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 kx(this)}}function aa(r,e){return r-e.start<e.duration/2&&!(Math.abs(r-(e.start+e.duration))<es)?e.start:e.start+e.duration}function qd(r,e,t){const s=new self.URL(r,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function kx(r){return`["${r.identifier}" ${r.cue.pre?"<pre>":r.cue.post?"<post>":""}${r.timelineStart.toFixed(2)}-${r.resumeTime.toFixed(2)}]`}function Ha(r){const e=r.timelineStart,t=r.duration||0;return`["${r.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class Mx{constructor(e,t,s,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 d=this.interstitial.playoutLimit,p=this.currentTime;this.startOffset+p>=d&&this.hls.trigger(_.PLAYOUT_LIMIT_REACHED,{})};const a=this.hls=new e(t);this.interstitial=s,this.assetItem=n;let h=n.uri;try{h=qd(h,a.sessionId).href}catch{}a.loadSource(h);const l=()=>{this.hasDetails=!0};a.once(_.LEVEL_LOADED,l),a.once(_.AUDIO_TRACK_LOADED,l),a.once(_.SUBTITLE_TRACK_LOADED,l),a.on(_.MEDIA_ATTACHING,(u,{media:d})=>{this.removeMediaListeners(),this.mediaAttached=d,this.interstitial.playoutLimit&&d.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 s=this.timelineOffset,n=ce.bufferInfo(e,s,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=ce.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 s=e-t;if(Math.abs(s)>1/9e4){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}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,s){this.hls.on(e,t)}once(e,t,s){this.hls.once(e,t)}off(e,t,s){this.hls.off(e,t)}toString(){var e,t;return`HlsAssetPlayer: ${Ha(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${(t=this.interstitial)!=null&&t.appendInPlace?"append-in-place":""}`}}const vh=.033;class Fx extends Jt{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((s,n)=>e<=n.startOffset&&t>n.startOffset?(delete n.error,s+1):s,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 s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const n=this.items;if(n)for(n[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(a=n[s])!=null&&a.event;){var a;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let n=0;n<s.length;n++){let a=s[n];if(t&&t!=="primary"&&(a=a[t]),e===a.start||e>a.start&&e<a.end)return n}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let n=e;n<=t&&s[n];n++){const a=s[n].event;if(a!=null&&a.restrictions.jump&&!a.appendInPlace)return n}return-1}findEventIndex(e){const t=this.items;if(t)for(let n=t.length;n--;){var s;if(((s=t[n].event)==null?void 0:s.identifier)===e)return n}return-1}findAssetIndex(e,t){const s=e.assetList,n=s.length;if(n>1)for(let a=0;a<n;a++){const h=s[a];if(!h.error){const l=h.timelineStart;if(t===l||t>l&&t<l+(h.duration||0))return a}}return 0}get assetIdAtEnd(){var e,t;const s=(e=this.items)==null||(t=e[this.length-1])==null?void 0:t.event;if(s){const n=s.assetList,a=n[n.length-1];if(a)return a.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:n}=s,a=this.events,h=this.parseDateRanges(n,{url:s.url},t),l=Object.keys(n),u=a?a.filter(d=>!l.includes(d.identifier)):[];h.length&&h.sort((d,p)=>{const g=d.cue.pre,y=d.cue.post,v=p.cue.pre,x=p.cue.post;if(g&&!v)return-1;if(v&&!g||y&&!x)return 1;if(x&&!y)return-1;if(!g&&!v&&!y&&!x){const E=d.startTime,o=p.startTime;if(E!==o)return E-o}return d.dateRange.tagOrder-p.dateRange.tagOrder}),this.events=h,u.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(e,u)}updateSchedule(e,t=[]){const s=this.events||[];if(s.length||t.length||this.length<2){const n=this.items,a=this.parseSchedule(s,e);(t.length||(n==null?void 0:n.length)!==a.length||a.some((l,u)=>Math.abs(l.playout.start-n[u].playout.start)>.005||Math.abs(l.playout.end-n[u].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,n))}}parseDateRanges(e,t,s){const n=[],a=Object.keys(e);for(let h=0;h<a.length;h++){const l=a[h],u=e[l];if(u.isInterstitial){let d=this.eventMap[l];d?d.setDateRange(u):(d=new Px(u,t),this.eventMap[l]=d,s===!1&&(d.appendInPlace=s)),n.push(d)}}return n}parseSchedule(e,t){const s=[],n=t.main.details,a=n.live?1/0:n.edge;let h=0;if(e=e.filter(u=>!u.error&&!(u.cue.once&&u.hasPlayed)),e.length){this.resolveOffsets(e,t);let u=0,d=0;if(e.forEach((p,g)=>{const y=p.cue.pre,v=p.cue.post,x=e[g-1]||null,E=p.appendInPlace,o=v?a:p.startOffset,c=p.duration,f=p.timelineOccupancy===qn.Range?c:0,m=p.resumptionOffset,S=(x==null?void 0:x.startTime)===o,T=o+p.cumulativeDuration;let b=E?T+c:o+m;if(y||!v&&o<=0){const I=d;d+=f,p.timelineStart=T;const L=h;h+=c,s.push({event:p,start:T,end:b,playout:{start:L,end:h},integrated:{start:I,end:d}})}else if(o<=a){if(!S){const w=o-u;if(w>vh){const C=u,k=d;d+=w;const U=h;h+=w;const G={previousEvent:e[g-1]||null,nextEvent:p,start:C,end:C+w,playout:{start:U,end:h},integrated:{start:k,end:d}};s.push(G)}else w>0&&x&&(x.cumulativeDuration+=w,s[s.length-1].end=o)}v&&(b=T),p.timelineStart=T;const I=d;d+=f;const L=h;h+=c,s.push({event:p,start:T,end:b,playout:{start:L,end:h},integrated:{start:I,end:d}})}else return;const A=p.resumeTime;v||A>a?u=a:u=A}),u<a){var l;const p=u,g=d,y=a-u;d+=y;const v=h;h+=y,s.push({previousEvent:((l=s[s.length-1])==null?void 0:l.event)||null,nextEvent:null,start:u,end:p+y,playout:{start:v,end:h},integrated:{start:g,end:d}})}this.setDurations(a,h,d)}else s.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,n=s.live?1/0:s.edge;let a=0,h=-1;e.forEach((l,u)=>{const d=l.cue.pre,p=l.cue.post,g=d?0:p?n:l.startTime;this.updateAssetDurations(l),h===g?l.cumulativeDuration=a:(a=0,h=g),!p&&l.snapOptions.in&&(l.resumeAnchor=ki(null,s.fragments,l.startOffset+l.resumptionOffset,0,0)||void 0),l.appendInPlace&&!l.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(l,t)||(l.appendInPlace=!1)),!l.appendInPlace&&u+1<e.length&&e[u+1].startTime-e[u].resumeTime<vh&&(e[u+1].appendInPlace=!1,e[u+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${l}`));const v=K(l.resumeOffset)?l.resumeOffset:l.duration;a+=v})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(s-n)>es?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${n}`),!1):t?!Object.keys(t).some(h=>{const l=t[h].details,u=l.edge;if(s>=u)return this.log(`"${e.identifier}" resumption ${s} past ${h} playlist end ${u}`),!1;const d=ki(null,l.fragments,s);if(!d)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${h} playlist (${l.fragStart}-${l.fragmentEnd})`),!0;const p=h==="audio"?.175:0;return Math.abs(d.start-s)<es+p||Math.abs(d.end-s)<es+p?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${h} fragment bounds (${d.start}-${d.end} sn: ${d.sn} cc: ${d.cc})`),!0)}):(this.log(`"${e.identifier}" resumption ${s} can not be aligned with media (none selected)`),!1)}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,n=!1,a=!1;e.assetList.forEach((h,l)=>{const u=t+s;h.startOffset=s,h.timelineStart=u,n||(n=h.duration===null),a||(a=!!h.error);const d=h.error?0:h.duration||0;s+=d}),n&&!a?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function ii(r){return`[${r.event?'"'+r.event.identifier+'"':"primary"}: ${r.start.toFixed(2)}-${r.end.toFixed(2)}]`}class Ux{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let n;try{n=qd(s,this.hls.sessionId,e.baseUrl)}catch(y){const v=this.assignAssetListError(e,P.ASSET_LIST_LOAD_ERROR,y,s);this.hls.trigger(_.ERROR,v);return}t&&n.protocol!=="data:"&&n.searchParams.set("_HLS_start_offset",""+t);const a=this.hls.config,h=a.loader,l=new h(a),u={responseType:"json",url:n.href},d=a.interstitialAssetListLoadPolicy.default,p={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(y,v,x,E)=>{const o=y.data,c=o==null?void 0:o.ASSETS;if(!Array.isArray(c)){const f=this.assignAssetListError(e,P.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),x.url,v,E);this.hls.trigger(_.ERROR,f);return}e.assetListResponse=o,this.hls.trigger(_.ASSET_LIST_LOADED,{event:e,assetListResponse:o,networkDetails:E})},onError:(y,v,x,E)=>{const o=this.assignAssetListError(e,P.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${y.code} ${y.text} (${v.url})`),v.url,E,x);this.hls.trigger(_.ERROR,o)},onTimeout:(y,v,x)=>{const E=this.assignAssetListError(e,P.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${v.url})`),v.url,y,x);this.hls.trigger(_.ERROR,E)}};return l.load(u,p,g),this.hls.trigger(_.ASSET_LIST_LOADING,{event:e}),l}assignAssetListError(e,t,s,n,a,h){return e.error=s,{type:Q.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:s,networkDetails:h,stats:a}}}function Yt(r,e,t){Rt(r,e,t),r.addEventListener(e,t)}function Rt(r,e,t){r.removeEventListener(e,t)}function Sh(r){r==null||r.play().catch(()=>{})}class Ox extends Jt{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 s=this.currentTime;if(s===void 0||this.playbackDisabled)return;const n=s-this.timelinePos;if(Math.abs(n)<1/7056e5)return;const h=n<=-.01;this.timelinePos=s,this.bufferedPos=s;const l=this.playingItem;if(!l){this.checkBuffer();return}if(h&&this.schedule.resetErrorsInRange(s,s-n)&&this.updateSchedule(),this.checkBuffer(),h&&s<l.start||s>=l.end){var u;const y=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(l)&&(u=this.media)!=null&&u.paused&&(this.shouldPlay=!1),!h){const v=this.findItemIndex(l);if(y>v){const x=this.schedule.findJumpRestrictedIndex(v+1,y);if(x>v){this.setSchedulePosition(x);return}}}this.setSchedulePosition(y);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(l)){const y=l.event.assetList[0];y&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,y))}return}const p=d.timelineStart,g=d.duration||0;(h&&s<p||s>=p+g)&&this.setScheduleToAssetAtTime(s,d)},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const n=this.playingItem;if(!n||this.playingLastItem)return;if(s>=n.end){this.timelinePos=n.end;const l=this.findItemIndex(n);this.setSchedulePosition(l+1)}const a=this.playingAsset;if(!a)return;const h=a.timelineStart+(a.duration||0);s>=h&&this.setScheduleToAssetAtTime(s,a)},this.onScheduleUpdate=(s,n)=>{const a=this.schedule,h=this.playingItem,l=a.events||[],u=a.items||[],d=a.durations,p=s.map(v=>v.identifier),g=!!(l.length||p.length);if(g&&this.log(`INTERSTITIALS_UPDATED (${l.length}): ${l}
|
|
133
|
-
Schedule: ${u.map(v=>ii(v))}`),p.length&&this.log(`Removed events ${p}`),this.playerQueue.forEach(v=>{if(v.interstitial.appendInPlace){const x=v.assetItem.timelineStart,E=v.timelineOffset-x;if(E)try{v.timelineOffset=x}catch(o){Math.abs(E)>es&&this.warn(`${o} ("${v.assetId}" ${v.timelineOffset}->${x})`)}}}),h){const v=this.updateItem(h,this.timelinePos);this.itemsMatch(h,v)&&(this.playingItem=v,this.waitingItem=this.endedItem=null)}else this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const y=this.bufferingItem;if(y){const v=this.updateItem(y,this.bufferedPos);this.itemsMatch(y,v)?this.bufferingItem=v:y.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(y.event,null))}if(s.forEach(v=>{v.assetList.forEach(x=>{this.clearAssetPlayer(x.identifier,null)})}),g||n){if(this.hls.trigger(_.INTERSTITIALS_UPDATED,{events:l.slice(0),schedule:u.slice(0),durations:d,removedIds:p}),this.isInterstitial(h)&&p.includes(h.event.identifier)){this.warn(`Interstitial "${h.event.identifier}" removed while playing`),this.primaryFallback(h.event);return}this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Ux(e),this.schedule=new Fx(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e.on(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(_.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(_.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(_.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(_.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(_.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(_.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(_.BUFFER_APPENDED,this.onBufferAppended,this),e.on(_.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(_.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(_.MEDIA_ENDED,this.onMediaEnded,this),e.on(_.ERROR,this.onError,this),e.on(_.DESTROYING,this.onDestroying,this)}unregisterListeners(){const e=this.hls;e&&(e.off(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(_.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(_.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(_.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(_.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(_.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(_.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(_.BUFFER_CODECS,this.onBufferCodecs,this),e.off(_.BUFFER_APPENDED,this.onBufferAppended,this),e.off(_.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(_.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(_.MEDIA_ENDED,this.onMediaEnded,this),e.off(_.ERROR,this.onError,this),e.off(_.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){Rt(e,"play",this.onPlay),Rt(e,"pause",this.onPause),Rt(e,"seeking",this.onSeeking),Rt(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;Yt(s,"seeking",this.onSeeking),Yt(s,"timeupdate",this.onTimeupdate),Yt(s,"play",this.onPlay),Yt(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!n){this.clearScheduleState();const a=this.findItemIndex(s);this.setSchedulePosition(a)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,n=this.media;if(this.media=null,!s&&(n&&this.removeMediaListeners(n),this.detachedData)){const a=this.getBufferingPlayer();a&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,a.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.manager){if(!this.hls)return null;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=g=>g&&e.getAssetPlayer(g.identifier),n=(g,y,v,x,E)=>{if(g){let o=g[y].start;const c=g.event;if(c){if(y==="playout"||c.timelineOccupancy!==qn.Point){const f=s(v);(f==null?void 0:f.interstitial)===c&&(o+=f.assetItem.startOffset+f[E])}}else{const f=x==="bufferedPos"?h():e[x];o+=f-g.start}return o}return 0},a=(g,y)=>{if(g!==0&&y!=="primary"&&e.schedule.length){var v;const x=e.schedule.findItemIndexAtTime(g),E=(v=e.schedule.items)==null?void 0:v[x];if(E){const o=E[y].start-E.start;return g+o}}return g},h=()=>{const g=e.bufferedPos;return g===Number.MAX_VALUE?l("primary"):Math.max(g,0)},l=g=>{var y;return(y=e.primaryDetails)!=null&&y.live?e.primaryDetails.edge:e.schedule.durations[g]},u=(g,y)=>{var v,x;const E=e.effectivePlayingItem;if(E!=null&&(v=E.event)!=null&&v.restrictions.skip)return;e.log(`seek to ${g} "${y}"`);const o=e.effectivePlayingItem,c=e.schedule.findItemIndexAtTime(g,y),f=(x=e.schedule.items)==null?void 0:x[c],m=e.getBufferingPlayer(),S=m==null?void 0:m.interstitial,T=S==null?void 0:S.appendInPlace,b=o&&e.itemsMatch(o,f);if(o&&(T||b)){const I=s(e.playingAsset),L=(I==null?void 0:I.media)||e.primaryMedia;if(L){const w=y==="primary"?L.currentTime:n(o,y,e.playingAsset,"timelinePos","currentTime"),C=g-w,k=(T?w:L.currentTime)+C;if(k>=0&&(!I||T||k<=I.duration)){L.currentTime=k;return}}}if(f){let I=g;if(y!=="primary"){const w=f[y].start,C=g-w;I=f.start+C}const L=!e.isInterstitial(f);if((!e.isInterstitial(o)||o.event.appendInPlace)&&(L||f.event.appendInPlace)){const w=e.media||(T?m==null?void 0:m.media:null);w&&(w.currentTime=I)}else if(o){const w=e.findItemIndex(o);if(c>w){const k=e.schedule.findJumpRestrictedIndex(w+1,c);if(k>w){e.setSchedulePosition(k);return}}let C=0;if(L)e.timelinePos=I,e.checkBuffer();else{var A;const k=f==null||(A=f.event)==null?void 0:A.assetList;if(k){const U=g-(f[y]||f).start;for(let G=k.length;G--;){const $=k[G];if($.duration&&U>=$.startOffset&&U<$.startOffset+$.duration){C=G;break}}}}e.setSchedulePosition(c,C)}}},d=()=>{const g=e.effectivePlayingItem;if(e.isInterstitial(g))return g;const y=t();return e.isInterstitial(y)?y:null},p={get currentTime(){const g=d(),y=e.effectivePlayingItem;return y&&y===g?n(y,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-y.playout.start:0},set currentTime(g){const y=d(),v=e.effectivePlayingItem;v&&v===y&&u(g+v.playout.start,"playout")},get duration(){const g=d();return g?g.playout.end-g.playout.start:0},get assetPlayers(){var g;const y=(g=d())==null?void 0:g.event.assetList;return y?y.map(v=>e.getAssetPlayer(v.identifier)):[]},get playingIndex(){var g;const y=(g=d())==null?void 0:g.event;return y&&e.effectivePlayingAsset?y.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};this.manager={get events(){var g,y;return((g=e.schedule)==null||(y=g.events)==null?void 0:y.slice(0))||[]},get schedule(){var g,y;return((g=e.schedule)==null||(y=g.items)==null?void 0:y.slice(0))||[]},get interstitialPlayer(){return d()?p:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const g=t();return e.findItemIndex(g)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const g=e.effectivePlayingItem;return e.findItemIndex(g)},primary:{get bufferedEnd(){return h()},get currentTime(){const g=e.timelinePos;return g>0?g:0},set currentTime(g){u(g,"primary")},get duration(){return l("primary")},get seekableStart(){var g;return((g=e.primaryDetails)==null?void 0:g.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(g){u(g,"integrated")},get duration(){return l("integrated")},get seekableStart(){var g;return a(((g=e.primaryDetails)==null?void 0:g.fragmentStart)||0,"integrated")}},skip:()=>{const g=e.effectivePlayingItem,y=g==null?void 0:g.event;if(y&&!y.restrictions.skip){const v=e.findItemIndex(g);if(y.appendInPlace){const x=g.playout.start+g.event.duration;u(x+.001,"playout")}else e.advanceAfterAssetEnded(y,v,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,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t,s;if(this.mediaSelection===null)return;const n=this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&!n.event.appendInPlace)return;let a=this.media;!a&&(e=this.bufferingItem)!=null&&(t=e.event)!=null&&t.appendInPlace&&(a=this.primaryMedia);const h=(s=a)==null?void 0:s.currentTime;if(!(h===void 0||!K(h)))return h}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 s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,n=e.media;if(s&&n===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&n){this.detachedData={media:n};return}const a=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Ae(a)}`),this.detachedData=a}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(e,t){var s,n;if(e.media===t)return;let a=null;const h=this.hls,l=e!==h,u=l&&e.interstitial.appendInPlace,d=(s=this.detachedData)==null?void 0:s.mediaSource;let p;if(h.media)u&&(a=h.transferMedia(),this.detachedData=a),p="Primary";else if(d){const v=this.getBufferingPlayer();v?(a=v.transferMedia(),p=`${v}`):p="detached MediaSource"}else p="detached media";if(!a){if(d)a=this.detachedData,this.log(`using detachedData: MediaSource ${Ae(a)}`);else if(!this.detachedData||h.media===t){const v=this.playerQueue;v.length>1&&v.forEach(x=>{if(l&&x.interstitial.appendInPlace!==u){const E=x.interstitial;this.clearInterstitial(x.interstitial,null),E.appendInPlace=!1,E.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${E}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const g=a&&"mediaSource"in a&&((n=a.mediaSource)==null?void 0:n.readyState)!=="closed",y=g&&a?a:t;if(this.log(`${g?"transfering MediaSource":"attaching media"} to ${l?e:"Primary"} from ${p}`),y===a){const v=l&&e.assetId===this.schedule.assetIdAtEnd;y.overrides={duration:this.schedule.duration,endOfStream:!l||v,cueRemoval:!l}}e.attachMedia(y)}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 s=this.timelinePos,n=this.effectivePlayingItem;if(s===-1){const a=this.hls.startPosition;if(this.timelinePos=a,t.length&&t[0].cue.pre){const h=e.findEventIndex(t[0].identifier);this.setSchedulePosition(h)}else if(a>=0||!this.primaryLive){const h=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(h);this.setSchedulePosition(l)}}else if(n&&!this.playingItem){const a=e.findItemIndex(n);this.setSchedulePosition(a)}}advanceAfterAssetEnded(e,t,s){const n=s+1;if(!e.isAssetPastPlayoutLimit(n)&&!e.assetList[n].error)this.setSchedulePosition(t,n);else{const a=this.schedule.items;if(a){const h=t+1,l=a.length;if(h>=l){this.setSchedulePosition(-1);return}const u=e.resumeTime;this.timelinePos<u&&(this.timelinePos=u,this.checkBuffer()),this.setSchedulePosition(h)}}}setScheduleToAssetAtTime(e,t){const s=this.schedule,n=t.parentIdentifier,a=s.getEvent(n);if(a){const h=s.findEventIndex(n),l=s.findAssetIndex(a,e);this.setSchedulePosition(h,l)}}setSchedulePosition(e,t){const s=this.schedule.items;if(!s||this.playbackDisabled)return;this.log(`setSchedulePosition ${e}, ${t}`);const n=e>=0?s[e]:null,a=this.playingItem,h=this.playingLastItem;if(this.isInterstitial(a)){var l;const d=a.event,p=this.playingAsset,g=p==null?void 0:p.identifier,y=g?this.getAssetPlayer(g):null;if(y&&g&&(!this.eventItemsMatch(a,n)||t!==void 0&&g!==((l=d.assetList)==null?void 0:l[t].identifier))){var u;const v=d.findAssetIndex(p);this.log(`INTERSTITIAL_ASSET_ENDED ${v+1}/${d.assetList.length} ${Ha(p)}`),this.endedAsset=p,this.playingAsset=null,this.hls.trigger(_.INTERSTITIAL_ASSET_ENDED,{asset:p,assetListIndex:v,event:d,schedule:s.slice(0),scheduleIndex:e,player:y}),this.retreiveMediaSource(g,n),y.media&&!((u=this.detachedData)!=null&&u.mediaSource)&&y.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${d} ${ii(a)}`),d.hasPlayed=!0,this.hls.trigger(_.INTERSTITIAL_ENDED,{event:d,schedule:s.slice(0),scheduleIndex:e}),d.cue.once)){this.updateSchedule();const v=this.schedule.items;if(n&&v){const x=this.schedule.findItemIndex(n);this.advanceSchedule(x,v,t,a,h)}return}}this.advanceSchedule(e,s,t,a,h)}advanceSchedule(e,t,s,n,a){const h=e>=0?t[e]:null,l=this.primaryMedia,u=this.playerQueue;if(u.length&&u.forEach(d=>{const p=d.interstitial,g=this.schedule.findEventIndex(p.identifier);(g<e||g>e+1)&&this.clearInterstitial(p,h)}),this.isInterstitial(h)){this.timelinePos=Math.min(Math.max(this.timelinePos,h.start),h.end);const d=h.event;s===void 0&&(s=this.schedule.findAssetIndex(d,this.timelinePos));const p=this.waitingItem;this.assetsBuffered(h,l)||this.setBufferingItem(h);let g=this.preloadAssets(d,s);if(this.eventItemsMatch(h,p||n)||(this.waitingItem=h,this.log(`INTERSTITIAL_STARTED ${ii(h)} ${d.appendInPlace?"append in place":""}`),this.hls.trigger(_.INTERSTITIAL_STARTED,{event:d,schedule:t.slice(0),scheduleIndex:e})),!d.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${d}`);return}if(d.assetListLoader&&(d.assetListLoader.destroy(),d.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${d}`);return}this.waitingItem=this.endedItem=null,this.playingItem=h;const y=d.assetList[s];if(!y){const v=t[e+1],x=this.media;v&&x&&!this.isInterstitial(v)&&x.currentTime<v.start&&(x.currentTime=this.timelinePos=v.start),this.advanceAfterAssetEnded(d,e,s||0);return}if(g||(g=this.getAssetPlayer(y.identifier)),g===null||g.destroyed){const v=d.assetList.length;this.warn(`asset ${s+1}/${v} player destroyed ${d}`),g=this.createAssetPlayer(d,y,s)}if(!this.eventItemsMatch(h,this.bufferingItem)&&d.appendInPlace&&this.isAssetBuffered(y))return;this.startAssetPlayer(g,s,t,e,l),this.shouldPlay&&Sh(g.media)}else h!==null?(this.resumePrimary(h,e,n),this.shouldPlay&&Sh(this.hls.media)):a&&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,s){var n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${ii(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let h=this.timelinePos;(h<e.start||h>=e.end)&&(h=this.getPrimaryResumption(e,t),this.timelinePos=h),this.attachPrimary(h,e)}if(!s)return;const a=this.schedule.items;a&&(this.log(`resumed ${ii(e)}`),this.hls.trigger(_.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const n=this.primaryDetails;if(t===0)return this.hls.startPosition;if(n&&(s<n.fragmentStart||s>n.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:ce.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const n=this.primaryMedia;if(!n)return;const a=this.hls;a.media?this.checkBuffer():(this.transferMediaTo(a,n),s&&this.startLoadingPrimaryAt(e,s)),s||(this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs((((s=n.mainForwardBufferInfo)==null?void 0:s.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(_.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(_.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1)return;const s=this.hls.levels[t.level],n=xe(xe({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=xe(xe({},this.altSelection),{},{audio:s});return}const a=xe(xe({},n),{},{audio:s});this.mediaSelection=a}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=xe(xe({},this.altSelection),{},{subtitles:s});return}const a=xe(xe({},n),{},{subtitles:s});this.mediaSelection=a}onAudioTrackSwitching(e,t){const s=Pl(t);this.playerQueue.forEach(n=>n.hls.setAudioOption(t)||n.hls.setAudioOption(s))}onSubtitleTrackSwitch(e,t){const s=Pl(t);this.playerQueue.forEach(n=>n.hls.setSubtitleOption(t)||t.id!==-1&&n.hls.setSubtitleOption(s))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){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 a=t[n];if(a.cue.post){var s;const h=this.schedule.findEventIndex(a.identifier),l=(s=this.schedule.items)==null?void 0:s[h];this.isInterstitial(l)&&this.eventItemsMatch(l,this.bufferingItem)&&this.bufferedToItem(l,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){const s=this.schedule.items;if(e&&s){const n=this.findItemIndex(e,t);return s[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 s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.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 s=ce.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=s.len<1),this.updateBufferedPos(s.end,t,e)}updateBufferedPos(e,t,s){const n=this.schedule,a=this.bufferingItem;if(this.bufferedPos>e)return;if(t.length===1&&this.itemsMatch(t[0],a)){this.bufferedPos=e;return}const h=this.playingItem,l=this.findItemIndex(h);let u=n.findItemIndexAtTime(e);if(this.bufferedPos<e){var d,p;const g=this.findItemIndex(a),y=Math.min(g+1,t.length-1),v=t[y];if((u===-1&&a&&e>=a.end||(d=v.event)!=null&&d.appendInPlace&&e+.01>=v.start)&&(u=y),y-l>1&&(a==null||(p=a.event)==null?void 0:p.appendInPlace)===!1)return;if(this.bufferedPos=e,u>g&&u>l)this.bufferedToItem(v);else{const x=this.primaryDetails;this.primaryLive&&x&&e>x.edge-x.targetduration&&v.start<x.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(v)&&this.preloadAssets(v.event,0)}}else s&&h&&!this.itemsMatch(h,a)&&(u===l?this.bufferedToItem(h):u===l+1&&this.bufferedToItem(t[u]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(n=>{const a=this.getAssetPlayer(n.identifier);return!(a!=null&&a.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(this.itemsMatch(e,t))this.bufferingItem!==e&&(this.bufferingItem=e);else{const{items:n,events:a}=s;if(!n||!a)return t;const h=this.isInterstitial(e),l=this.getBufferingPlayer();if(this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos)),!this.playbackDisabled){const u=l?l.remaining:t?t.end-this.timelinePos:0;this.log(`buffered to boundary ${ii(e)}`+(t?` (${u.toFixed(2)} remaining)`:"")),h?e.event.assetList.forEach(d=>{const p=this.getAssetPlayer(d.identifier);p&&p.resumeBuffering()}):(this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering()))}this.hls.trigger(_.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:a.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==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),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,n=s.assetList.length===0&&!s.assetListLoader,a=s.cue.once;if(n||!a){const h=this.preloadAssets(s,t);if(h!=null&&h.interstitial.appendInPlace){const l=s.assetList[t],u=this.primaryMedia;l&&u&&this.bufferAssetPlayer(h,u)}}}preloadAssets(e,t){const s=e.assetUrl,n=e.assetList.length,a=n===0&&!e.assetListLoader,h=e.cue.once;if(a){const u=e.timelineStart;if(e.appendInPlace){var l;const y=this.playingItem;!this.isInterstitial(y)&&(y==null||(l=y.nextEvent)==null?void 0:l.identifier)===e.identifier&&this.flushFrontBuffer(u+.25)}let d,p=0;if(!this.playingItem&&this.primaryLive&&(p=this.hls.startPosition,p===-1&&(p=this.hls.liveSyncPosition||0)),p&&!(e.cue.pre||e.cue.post)){const y=p-u;y>0&&(d=Math.round(y*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:n} ${e}${d?` live-start: ${p} start-offset: ${d}`:""}`),s)return this.createAsset(e,0,0,u,e.duration,s);const g=this.assetListLoader.loadAssetList(e,d);g&&(e.assetListLoader=g)}else if(!h&&n){for(let u=t;u<n;u++){const d=e.assetList[u],p=this.getAssetPlayerQueueIndex(d.identifier);(p===-1||this.playerQueue[p].destroyed)&&!d.error&&this.createAssetPlayer(e,d,u)}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(_.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;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 s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,n,a,h){const l={parentIdentifier:e.identifier,identifier:Dx(e,h,t),duration:a,startOffset:s,timelineStart:n,uri:h};return this.createAssetPlayer(e,l,t)}createAssetPlayer(e,t,s){this.log(`create HLSAssetPlayer for ${Ha(t)}`);const n=this.hls,a=n.userConfig;let h=a.videoPreference;const l=n.loadLevelObj||n.levels[n.currentLevel];(h||l)&&(h=Te({},h),l.videoCodec&&(h.videoCodec=l.videoCodec),l.videoRange&&(h.allowedVideoRanges=[l.videoRange]));const u=n.audioTracks[n.audioTrack],d=n.subtitleTracks[n.subtitleTrack];let p=0;if(this.primaryLive||e.appendInPlace){const m=this.timelinePos-t.timelineStart;if(m>1){const S=t.duration;S&&m<S&&(p=m)}}const g=t.identifier,y=xe(xe({},a),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:g,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:p,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:h,audioPreference:u||a.audioPreference,subtitlePreference:d||a.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(y.timelineOffset=t.timelineStart));const v=y.cmcd;v!=null&&v.sessionId&&v.contentId&&(y.cmcd=Te({},v,{contentId:Is(t.uri)})),this.getAssetPlayer(g)&&this.warn(`Duplicate date range identifier ${e} and asset ${g}`);const x=new Mx(this.HlsPlayerClass,y,e,t);this.playerQueue.push(x),e.assetList[s]=t;const E=m=>{if(m.live){const b=new Error(`Interstitials MUST be VOD assets ${e}`),A={fatal:!0,type:Q.OTHER_ERROR,details:P.INTERSTITIAL_ASSET_ITEM_ERROR,error:b};this.handleAssetItemError(A,e,this.schedule.findEventIndex(e.identifier),s,b.message);return}const S=m.edge-m.fragmentStart,T=t.duration;(T===null||S>T)&&(this.log(`Interstitial asset "${g}" duration change ${T} > ${S}`),t.duration=S,this.updateSchedule())};x.on(_.LEVEL_UPDATED,(m,{details:S})=>E(S)),x.on(_.LEVEL_PTS_UPDATED,(m,{details:S})=>E(S));const o=(m,S)=>{const T=this.getAssetPlayer(g);if(T&&S.tracks){T.off(_.BUFFER_CODECS,o),T.tracks=S.tracks;const b=this.primaryMedia;this.bufferingAsset===T.assetItem&&b&&!T.media&&this.bufferAssetPlayer(T,b)}};x.on(_.BUFFER_CODECS,o);const c=()=>{var m;const S=this.getAssetPlayer(g);if(this.log(`buffered to end of asset ${S}`),!S)return;const T=this.schedule.findEventIndex(e.identifier),b=e.findAssetIndex(t),A=b+1,I=(m=this.schedule.items)==null?void 0:m[T];if(this.isInterstitial(I))if(b!==-1&&!e.isAssetPastPlayoutLimit(A)&&!e.assetList[A].error)this.bufferedToItem(I,A);else{var L;const w=(L=this.schedule.items)==null?void 0:L[T+1];w&&this.bufferedToItem(w)}};x.on(_.BUFFERED_TO_END,c);const f=m=>()=>{if(!this.getAssetPlayer(g))return;this.shouldPlay=!0;const T=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,T,m)};return x.once(_.MEDIA_ENDED,f(s)),x.once(_.PLAYOUT_LIMIT_REACHED,f(1/0)),x.on(_.ERROR,(m,S)=>{const T=this.getAssetPlayer(g);if(S.details===P.BUFFER_STALLED_ERROR){if(T!=null&&T.media){const b=T.currentTime,A=T.duration-b;b&&e.appendInPlace&&A/T.media.playbackRate<.5?(this.log(`Advancing buffer past end of asset ${g} ${e} at ${T.media.currentTime}`),c()):(this.warn(`Stalled at ${b} of ${b+A} in asset ${g} ${e}`),this.onTimeupdate(),this.checkBuffer(!0))}return}this.handleAssetItemError(S,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${S.error} ${e}`)}),x.on(_.DESTROYING,()=>{if(!this.getAssetPlayer(g))return;const S=new Error(`Asset player destroyed unexpectedly ${g}`),T={fatal:!0,type:Q.OTHER_ERROR,details:P.INTERSTITIAL_ASSET_ITEM_ERROR,error:S};this.handleAssetItemError(T,e,this.schedule.findEventIndex(e.identifier),s,S.message)}),this.hls.trigger(_.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:x}),x}clearInterstitial(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)}),e.reset()}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){this.log(`clearAssetPlayer "${e}" toSegment: ${t&&ii(t)}`);const n=this.playerQueue[s];this.transferMediaFromPlayer(n,t),this.playerQueue.splice(s,1),n.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,n,a){const{interstitial:h,assetItem:l,assetId:u}=e,d=h.assetList.length,p=this.playingAsset;this.endedAsset=null,this.playingAsset=l,(!p||p.identifier!==u)&&(p&&(this.clearAssetPlayer(p.identifier,s[n]),delete p.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${e}`),this.hls.trigger(_.INTERSTITIAL_ASSET_STARTED,{asset:l,assetListIndex:t,event:h,schedule:s.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,a)}bufferAssetPlayer(e,t){var s,n;const{interstitial:a,assetItem:h,assetId:l}=e,u=this.schedule.findEventIndex(a.identifier),d=(s=this.schedule.items)==null?void 0:s[u];if(!d)return;this.setBufferingItem(d),this.bufferingAsset=h;const p=this.getBufferingPlayer();if(p===e)return;const g=a.appendInPlace;if(g&&(p==null?void 0:p.interstitial.appendInPlace)===!1)return;const y=(p==null?void 0:p.tracks)||((n=this.detachedData)==null?void 0:n.tracks)||this.requiredTracks;if(g&&h!==this.playingAsset){if(!e.tracks)return;if(y&&!Gc(y,e.tracks)){const v=new Error(`Asset "${l}" SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(y)}')`),x={fatal:!0,type:Q.OTHER_ERROR,details:P.INTERSTITIAL_ASSET_ITEM_ERROR,error:v},E=a.findAssetIndex(h);this.handleAssetItemError(x,a,u,E,v.message);return}}this.transferMediaTo(e,t)}handleAssetItemError(e,t,s,n,a){if(e.details===P.BUFFER_STALLED_ERROR)return;const h=t.assetList[n]||null;let l=null;if(h){const g=this.getAssetPlayerQueueIndex(h.identifier);l=this.playerQueue[g]||null}const u=this.schedule.items,d=Te({},e,{fatal:!1,errorAction:ks(!0),asset:h,assetListIndex:n,event:t,schedule:u,scheduleIndex:s,player:l});if(this.warn(`Asset item error: ${e.error}`),this.hls.trigger(_.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;const p=new Error(a);h&&(this.playingAsset!==h&&this.clearAssetPlayer(h.identifier,null),h.error=p),t.assetList.some(g=>!g.error)?t.appendInPlace&&(t.error=p):t.error=p,this.primaryFallback(t)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;if(this.updateSchedule(),s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${s?ii(s):"<none>"} error: ${e.error}`),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t));let n=this.timelinePos;n===-1&&(n=this.hls.startPosition);const a=this.updateItem(s,n);if(this.itemsMatch(s,a))this.clearInterstitial(e,null);else{const h=this.schedule.findItemIndexAtTime(n);this.setSchedulePosition(h)}}else this.checkStart()}onAssetListLoaded(e,t){var s;const n=t.event,a=n.identifier,h=t.assetListResponse.ASSETS;if(!this.schedule.hasEvent(a))return;const l=n.timelineStart,u=n.duration;let d=0;h.forEach((x,E)=>{const o=parseFloat(x.DURATION);this.createAsset(n,E,d,l+d,o,x.URI),d+=o}),n.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${u}) ${n}`);const p=this.waitingItem,g=(p==null?void 0:p.event.identifier)===a;this.updateSchedule();const y=(s=this.bufferingItem)==null?void 0:s.event;if(g){var v;const x=this.schedule.findEventIndex(a),E=(v=this.schedule.items)==null?void 0:v[x];if(E){if(!this.playingItem&&this.timelinePos>E.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==x){n.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${n}`),this.primaryFallback(n);return}this.setBufferingItem(E)}this.setSchedulePosition(x)}else if((y==null?void 0:y.identifier)===a&&y.appendInPlace){const x=n.assetList[0],E=this.getAssetPlayer(x.identifier),o=this.primaryMedia;x&&E&&o&&this.bufferAssetPlayer(E,o)}}onError(e,t){switch(t.details){case P.ASSET_LIST_PARSING_ERROR:case P.ASSET_LIST_LOAD_ERROR:case P.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&this.primaryFallback(s);break}case P.BUFFER_STALLED_ERROR:{this.onTimeupdate(),this.checkBuffer(!0);break}}}}const _h=500;class Bx extends To{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",X.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(_.LEVEL_LOADED,this.onLevelLoaded,this),e.on(_.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(_.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(_.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(_.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(_.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(_.LEVEL_LOADED,this.onLevelLoaded,this),e.off(_.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(_.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(_.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(_.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(_.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=M.IDLE,this.setInterval(_h),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:s,success:n}=t;if(Ne(s)&&(this.fragPrevious=s),this.state=M.IDLE,!n)return;const a=this.tracksBuffered[this.currentTrackId];if(!a)return;let h;const l=s.start;for(let d=0;d<a.length;d++)if(l>=a[d].start&&l<=a[d].end){h=a[d];break}const u=s.start+s.duration;h?h.end=u:(h={start:l,end:u},a.push(h)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:n}=t;if(s===0&&n!==Number.POSITIVE_INFINITY){const a=n-1;if(a<=0)return;t.endOffsetSubtitles=Math.max(0,a),this.tracksBuffered.forEach(h=>{for(let l=0;l<h.length;){if(h[l].end<=a){h.shift();continue}else if(h[l].start<a)h[l].start=a;else break;l++}}),this.fragmentTracker.removeFragmentsInRange(s,a,X.SUBTITLE)}}onError(e,t){const s=t.frag;(s==null?void 0:s.type)===X.SUBTITLE&&(t.details===P.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==M.STOPPED&&(this.state=M.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&$d(this.levels,t)){this.levels=t.map(s=>new Ps(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const n=new Ps(s);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,X.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.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!==M.STOPPED&&this.setInterval(_h)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:n,levels:a}=this,{details:h,id:l}=t;if(!a){this.warn(`Subtitle tracks were reset while loading level ${l}`);return}const u=a[l];if(l>=a.length||!u)return;this.log(`Subtitle track ${l} loaded [${h.startSN},${h.endSN}]${h.lastPartSn?`[part-${h.lastPartSn}-${h.lastPartIndex}]`:""},duration:${h.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(h.live||(s=u.details)!=null&&s.live){const g=this.mainDetails;if(h.deltaUpdateFailed||!g)return;const y=g.fragments[0];if(!u.details)h.hasProgramDateTime&&g.hasProgramDateTime?(Wn(h,g),d=h.fragmentStart):y&&(d=y.start,Ua(h,d));else{var p;d=this.alignPlaylists(h,u.details,(p=this.levelLastLoaded)==null?void 0:p.details),d===0&&y&&(d=y.start,Ua(h,d))}}u.details=h,this.levelLastLoaded=u,l===n&&(this.hls.trigger(_.SUBTITLE_TRACK_UPDATED,{details:h,id:l,groupId:t.groupId}),this.tick(),h.live&&!this.fragCurrent&&this.media&&this.state===M.IDLE&&(ki(null,h.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),u.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,n=t.decryptdata,a=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&n!=null&&n.key&&n.iv&&Zi(n.method)){const h=performance.now();this.decrypter.decrypt(new Uint8Array(s),n.key.buffer,n.iv.buffer,_o(n.method)).catch(l=>{throw a.trigger(_.ERROR,{type:Q.MEDIA_ERROR,details:P.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:t}),l}).then(l=>{const u=performance.now();a.trigger(_.FRAG_DECRYPTED,{frag:t,payload:l,stats:{tstart:h,tdecrypt:u}})}).catch(l=>{this.warn(`${l.name}: ${l.message}`),this.state=M.IDLE})}}doTick(){if(!this.media){this.state=M.IDLE;return}if(this.state===M.IDLE){const{currentTrackId:e,levels:t}=this,s=t==null?void 0:t[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:n}=this,a=this.getLoadPosition(),h=ce.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],a,n.maxBufferHole),{end:l,len:u}=h,d=s.details,p=this.hls.maxBufferLength+d.levelTargetDuration;if(u>p)return;const g=d.fragments,y=g.length,v=d.edge;let x=null;const E=this.fragPrevious;if(l<v){const f=n.maxFragLookUpTolerance,m=l>v-f?0:f;x=ki(E,g,Math.max(g[0].start,l),m),!x&&E&&E.start<g[0].start&&(x=g[0])}else x=g[y-1];if(x=this.filterReplacedPrimary(x,s.details),!x)return;const o=x.sn-d.startSN,c=g[o-1];if(c&&c.cc===x.cc&&this.fragmentTracker.getState(c)===ke.NOT_LOADED&&(x=c),this.fragmentTracker.getState(x)===ke.NOT_LOADED){const f=this.mapToInitFragWhenRequired(x);f&&this.loadFragment(f,s,l)}}}loadFragment(e,t,s){Ne(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Nx(this.tracksBuffered[this.currentTrackId]||[])}}class Nx{constructor(e){this.buffered=void 0;const t=(s,n,a)=>{if(n=n>>>0,n>a-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${a})`);return e[n][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}const $x={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},Xd=r=>String.fromCharCode($x[r]||r),ft=15,Bt=100,Gx={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},zx={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Hx={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Vx={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Kx=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Yx{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;pe.log(`${this.time} [${e}] ${s}`)}}}const Ti=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class Qd{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 s=0;s<t.length;s++){const n=t[s];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 Wx{constructor(){this.uchar=" ",this.penState=new Qd}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 jx{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Qd,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Bt;t++)this.chars.push(new Wx);this.logger=e}equals(e){for(let t=0;t<Bt;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Bt;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Bt;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>Bt&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Bt)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].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=Xd(e);if(this.pos>=Bt){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<Bt;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 s=0;s<Bt;s++){const n=this.chars[s].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 oa{constructor(e){this.rows=[],this.currRow=ft-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<ft;t++)this.rows.push(new jx(e));this.logger=e}reset(){for(let e=0;e<ft;e++)this.rows[e].clear();this.currRow=ft-1}equals(e){let t=!0;for(let s=0;s<ft;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<ft;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<ft;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 = "+Ae(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let l=0;l<ft;l++)this.rows[l].clear();const a=this.currRow+1-this.nrRollUpRows,h=this.lastOutputScreen;if(h){const l=h.rows[a].cueStartTime,u=this.logger.time;if(l!==null&&u!==null&&l<u)for(let d=0;d<this.nrRollUpRows;d++)this.rows[t-this.nrRollUpRows+d+1].copy(h.rows[a+d])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const a=e.indent,h=Math.max(a-1,0);s.setCursor(e.indent),e.color=s.chars[h].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 = "+Ae(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 s="",n=-1;for(let a=0;a<ft;a++){const h=this.rows[a].getTextString();h&&(n=a+1,e?t.push("Row "+n+": '"+h+"'"):t.push(h.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
|
|
134
|
-
`)),s}getTextAndFormat(){return this.rows}}class Eh{constructor(e,t,s){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 oa(s),this.nonDisplayedMemory=new oa(s),this.lastOutputScreen=new oa(s),this.currRollUpRow=this.displayedMemory.rows[ft-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[ft-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 s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);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 s=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[s]}this.logger.log(2,"MIDROW: "+Ae(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 Th{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Xx(),this.logger=void 0;const n=this.logger=new Yx;this.channels=[null,new Eh(e,t,n),new Eh(e+1,s,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 s=0;s<t.length;s+=2){const n=t[s]&127,a=t[s+1]&127;let h=!1,l=null;if(n===0&&a===0)continue;this.logger.log(3,()=>"["+Ti([t[s],t[s+1]])+"] -> ("+Ti([n,a])+")");const u=this.cmdHistory;if(n>=16&&n<=31){if(qx(n,a,u)){fn(null,null,u),this.logger.log(3,()=>"Repeated command ("+Ti([n,a])+") is dropped");continue}fn(n,a,this.cmdHistory),h=this.parseCmd(n,a),h||(h=this.parseMidrow(n,a)),h||(h=this.parsePAC(n,a)),h||(h=this.parseBackgroundAttributes(n,a))}else fn(null,null,u);if(!h&&(l=this.parseChars(n,a),l)){const p=this.currentChannel;p&&p>0?this.channels[p].insertChars(l):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!h&&!l&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Ti([n,a])+" orig: "+Ti([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(s||n))return!1;const a=e===20||e===21||e===23?1:2,h=this.channels[a];return e===20||e===21||e===28||e===29?t===32?h.ccRCL():t===33?h.ccBS():t===34?h.ccAOF():t===35?h.ccAON():t===36?h.ccDER():t===37?h.ccRU(2):t===38?h.ccRU(3):t===39?h.ccRU(4):t===40?h.ccFON():t===41?h.ccRDC():t===42?h.ccTR():t===43?h.ccRTD():t===44?h.ccEDM():t===45?h.ccCR():t===46?h.ccENM():t===47&&h.ccEOC():h.ccTO(t-32),this.currentChannel=a,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[s];return n?(n.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Ti([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const n=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,a=(e===16||e===24)&&t>=64&&t<=95;if(!(n||a))return!1;const h=e<=23?1:2;t>=64&&t<=95?s=h===1?Gx[e]:Hx[e]:s=h===1?zx[e]:Vx[e];const l=this.channels[h];return l?(l.setPAC(this.interpretPAC(s,t)),this.currentChannel=h,!0):!1}interpretPAC(e,t){let s;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,n.underline=(s&1)===1,s<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(n.italics=!0,n.color="white"):n.indent=Math.floor((s-16)/2)*4,n}parseChars(e,t){let s,n=null,a=null;if(e>=25?(s=2,a=e-8):(s=1,a=e),a>=17&&a<=19){let h;a===17?h=t+80:a===18?h=t+112:h=t+144,this.logger.log(2,()=>"Special char '"+Xd(h)+"' in channel "+s),n=[h]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+Ti(n).join(",")),n}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=45&&t<=47;if(!(s||n))return!1;let a;const h={};e===16||e===24?(a=Math.floor((t-32)/2),h.background=Kx[a],t%2===1&&(h.background=h.background+"_semi")):t===45?h.background="transparent":(h.foreground="black",t===47&&(h.underline=!0));const l=e<=23?1:2;return this.channels[l].setBkgData(h),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}fn(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function fn(r,e,t){t.a=r,t.b=e}function qx(r,e,t){return t.a===r&&t.b===e}function Xx(){return{a:null,b:null}}var Mo=function(){if(Yn!=null&&Yn.VTTCue)return self.VTTCue;const r=["","lr","rl"],e=["start","middle","end","left","right"];function t(l,u){if(typeof u!="string"||!Array.isArray(l))return!1;const d=u.toLowerCase();return~l.indexOf(d)?d:!1}function s(l){return t(r,l)}function n(l){return t(e,l)}function a(l,...u){let d=1;for(;d<arguments.length;d++){const p=arguments[d];for(const g in p)l[g]=p[g]}return l}function h(l,u,d){const p=this,g={enumerable:!0};p.hasBeenReset=!1;let y="",v=!1,x=l,E=u,o=d,c=null,f="",m=!0,S="auto",T="start",b=50,A="middle",I=50,L="middle";Object.defineProperty(p,"id",a({},g,{get:function(){return y},set:function(w){y=""+w}})),Object.defineProperty(p,"pauseOnExit",a({},g,{get:function(){return v},set:function(w){v=!!w}})),Object.defineProperty(p,"startTime",a({},g,{get:function(){return x},set:function(w){if(typeof w!="number")throw new TypeError("Start time must be set to a number.");x=w,this.hasBeenReset=!0}})),Object.defineProperty(p,"endTime",a({},g,{get:function(){return E},set:function(w){if(typeof w!="number")throw new TypeError("End time must be set to a number.");E=w,this.hasBeenReset=!0}})),Object.defineProperty(p,"text",a({},g,{get:function(){return o},set:function(w){o=""+w,this.hasBeenReset=!0}})),Object.defineProperty(p,"region",a({},g,{get:function(){return c},set:function(w){c=w,this.hasBeenReset=!0}})),Object.defineProperty(p,"vertical",a({},g,{get:function(){return f},set:function(w){const C=s(w);if(C===!1)throw new SyntaxError("An invalid or illegal string was specified.");f=C,this.hasBeenReset=!0}})),Object.defineProperty(p,"snapToLines",a({},g,{get:function(){return m},set:function(w){m=!!w,this.hasBeenReset=!0}})),Object.defineProperty(p,"line",a({},g,{get:function(){return S},set:function(w){if(typeof w!="number"&&w!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=w,this.hasBeenReset=!0}})),Object.defineProperty(p,"lineAlign",a({},g,{get:function(){return T},set:function(w){const C=n(w);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");T=C,this.hasBeenReset=!0}})),Object.defineProperty(p,"position",a({},g,{get:function(){return b},set:function(w){if(w<0||w>100)throw new Error("Position must be between 0 and 100.");b=w,this.hasBeenReset=!0}})),Object.defineProperty(p,"positionAlign",a({},g,{get:function(){return A},set:function(w){const C=n(w);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");A=C,this.hasBeenReset=!0}})),Object.defineProperty(p,"size",a({},g,{get:function(){return I},set:function(w){if(w<0||w>100)throw new Error("Size must be between 0 and 100.");I=w,this.hasBeenReset=!0}})),Object.defineProperty(p,"align",a({},g,{get:function(){return L},set:function(w){const C=n(w);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");L=C,this.hasBeenReset=!0}})),p.displayState=void 0}return h.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},h}();class Qx{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Zd(r){function e(s,n,a,h){return(s|0)*3600+(n|0)*60+(a|0)+parseFloat(h||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 Zx{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let n=0;n<s.length;++n)if(t===s[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 s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function Jd(r,e,t,s){const n=s?r.split(s):[r];for(const a in n){if(typeof n[a]!="string")continue;const h=n[a].split(t);if(h.length!==2)continue;const l=h[0],u=h[1];e(l,u)}}const Va=new Mo(0,0,""),pn=Va.align==="middle"?"middle":"center";function Jx(r,e,t){const s=r;function n(){const l=Zd(r);if(l===null)throw new Error("Malformed timestamp: "+s);return r=r.replace(/^[^\sa-zA-Z-]+/,""),l}function a(l,u){const d=new Zx;Jd(l,function(y,v){let x;switch(y){case"region":for(let E=t.length-1;E>=0;E--)if(t[E].id===v){d.set(y,t[E].region);break}break;case"vertical":d.alt(y,v,["rl","lr"]);break;case"line":x=v.split(","),d.integer(y,x[0]),d.percent(y,x[0])&&d.set("snapToLines",!1),d.alt(y,x[0],["auto"]),x.length===2&&d.alt("lineAlign",x[1],["start",pn,"end"]);break;case"position":x=v.split(","),d.percent(y,x[0]),x.length===2&&d.alt("positionAlign",x[1],["start",pn,"end","line-left","line-right","auto"]);break;case"size":d.percent(y,v);break;case"align":d.alt(y,v,["start",pn,"end","left","right"]);break}},/:/,/\s/),u.region=d.get("region",null),u.vertical=d.get("vertical","");let p=d.get("line","auto");p==="auto"&&Va.line===-1&&(p=-1),u.line=p,u.lineAlign=d.get("lineAlign","start"),u.snapToLines=d.get("snapToLines",!0),u.size=d.get("size",100),u.align=d.get("align",pn);let g=d.get("position","auto");g==="auto"&&Va.position===50&&(g=u.align==="start"||u.align==="left"?0:u.align==="end"||u.align==="right"?100:50),u.position=g}function h(){r=r.replace(/^\s+/,"")}if(h(),e.startTime=n(),h(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);r=r.slice(3),h(),e.endTime=n(),h(),a(r,e)}function eu(r){return r.replace(/<br(?: \/)?>/gi,`
|
|
135
|
-
`)}class
|
|
129
|
+
${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],n=s==null?void 0:s.buffer;return n?`SourceBuffer${n.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}}const Ch=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,lu="HlsJsTrackRemovedError";class cv extends Error{constructor(e){super(e),this.name=lu}}class dv extends xt{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=s=>{var n;this.hls&&((n=this.mediaSource)==null?void 0:n.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:n,mediaSource:a}=this;s&&this.log("Media source opened"),!(!n||!a)&&(a.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(E.MEDIA_ATTACHED,{media:n,mediaSource:a}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:n}=this;s!==n&&this.error(`Media element src was set while attaching MediaSource (${n} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=k0(Si(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(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_APPENDING,this.onBufferAppending,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.BUFFER_EOS,this.onBufferEos,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.FRAG_PARSED,this.onFragParsed,this),e.on(E.FRAG_CHANGED,this.onFragChanged,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_APPENDING,this.onBufferAppending,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_EOS,this.onBufferEos,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.FRAG_PARSED,this.onFragParsed,this),e.off(E.FRAG_CHANGED,this.onFragChanged,this),e.off(E.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const a=this.isUpdating();a||this.operationQueue.removeBlockers();const h=this.isQueued();(a||h)&&this.warn(`Transfering MediaSource with${h?" operations in queue":""}${a?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?Ee(s,n.tracks):this.sourceBuffers.forEach(a=>{const[h]=a;h&&(s[h]=Ee({},this.tracks[h]),this.removeBuffer(h)),a[0]=a[1]=null}),{media:e,mediaSource:t,tracks:s}}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 s;let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const n=Si(this.appendSource);if(n){const a=!!t.mediaSource;(a||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const h=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(h),a)this._objectUrl=s.src,this.attachTransferred();else{const l=this._objectUrl=self.URL.createObjectURL(h);if(this.appendSource)try{s.removeAttribute("src");const u=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||u&&h instanceof u,Ph(s),uv(s,l),s.load()}catch{s.src=l}else s.src=l}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.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 s=this.tracks,n=t.tracks,a=n?Object.keys(n):null,h=a?a.length:0,l=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&a&&h){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
|
|
130
|
+
required tracks: ${be(s,(u,d)=>u==="initSegment"?void 0:d)};
|
|
131
|
+
transfer tracks: ${be(n,(u,d)=>u==="initSegment"?void 0:d)}}`),!nd(n,s)){t.mediaSource=null,t.tracks=void 0;const u=e.currentTime,d=this.details,p=Math.max(u,(d==null?void 0:d.fragments[0].start)||0);if(p-u>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${u} -> ${p}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(s)}") start time: ${p} currentTime: ${u}`),this.onMediaDetaching(E.MEDIA_DETACHING,{}),this.onMediaAttaching(E.MEDIA_ATTACHING,t),e.currentTime=p;return}this.transferData=void 0,a.forEach(u=>{const d=u,p=n[d];if(p){const g=p.buffer;if(g){const y=this.fragmentTracker,x=p.id;if(y.hasFragments(x)||y.hasParts(x)){const o=ae.getBuffered(g);y.detectEvictedFragments(d,o,x,null,!0)}const v=pa(d),_=[d,g];this.sourceBuffers[v]=_,g.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,p)}}}),l(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),l()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:a,_objectUrl:h}=this;if(a){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([l])=>{l&&this.removeBuffer(l)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const l=a.readyState==="open";try{const u=a.sourceBuffers;for(let d=u.length;d--;)l&&u[d].abort(),a.removeSourceBuffer(u[d]);l&&a.endOfStream()}catch(u){this.warn(`onMediaDetaching: ${u.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}a.removeEventListener("sourceopen",this._onMediaSourceOpen),a.removeEventListener("sourceended",this._onMediaSourceEnded),a.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(a.removeEventListener("startstreaming",this._onStartStreaming),a.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),s||(h&&self.URL.revokeObjectURL(h),this.mediaSrc===h?(n.removeAttribute("src"),this.appendSource&&Ph(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(E.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(a){this.warn(`onBufferReset ${e}`,a)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[pa(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new hv(this.tracks)}onBufferCodecs(e,t){var s;const n=this.tracks,a=Object.keys(t);this.log(`BUFFER_CODECS: "${a}" (current SB count ${this.sourceBufferCount})`);const h="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),l=!h&&this.sourceBufferCount&&this.media&&a.some(u=>!n[u]);if(h||l){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${a}" SourceBuffers`);return}a.forEach(u=>{var d,p;const g=t[u],{id:y,codec:x,levelCodec:v,container:_,metadata:o,supplemental:c}=g;let f=n[u];const m=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[u],S=m!=null&&m.buffer?m:f,T=(S==null?void 0:S.pendingCodec)||(S==null?void 0:S.codec),b=S==null?void 0:S.levelCodec;f||(f=n[u]={buffer:void 0,listeners:[],codec:x,supplemental:c,container:_,levelCodec:v,metadata:o,id:y});const A=Mn(T,b),I=A==null?void 0:A.replace(Ch,"$1");let L=Mn(x,v);const w=(p=L)==null?void 0:p.replace(Ch,"$1");L&&A&&I!==w&&(u.slice(0,5)==="audio"&&(L=Qn(L,this.appendSource)),this.log(`switching codec ${T} to ${L}`),L!==(f.pendingCodec||f.codec)&&(f.pendingCodec=L),f.container=_,this.appendChangeType(u,_,L))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const n=`${t};codecs=${s}`,a={label:`change-type=${n}`,execute:()=>{const h=this.tracks[e];if(h){const l=h.buffer;l!=null&&l.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),l.changeType(n),h.codec=s,h.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:h=>{this.warn(`Failed to change ${e} SourceBuffer type`,h)}};this.append(a,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,n=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,X.MAIN))==null?void 0:t.gap)===!0)return;const h={label:"block-audio",execute:()=>{var l;const u=this.tracks.video;(this.lastVideoAppendEnd>n||u!=null&&u.buffer&&ae.isBuffered(u.buffer,n)||((l=this.fragmentTracker.getAppendedFrag(n,X.MAIN))==null?void 0:l.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:l=>{this.warn("Error executing block-audio operation",l)}};this.blockedAudioAppend={op:h,frag:e},this.append(h,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:n,type:a,parent:h,frag:l,part:u,chunkMeta:d,offset:p}=t,g=d.buffering[a],{sn:y,cc:x}=l,v=self.performance.now();g.start=v;const _=l.stats.buffering,o=u?u.stats.buffering:null;_.start===0&&(_.start=v),o&&o.start===0&&(o.start=v);const c=s.audio;let f=!1;a==="audio"&&(c==null?void 0:c.container)==="audio/mpeg"&&(f=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const m=s.video,S=m==null?void 0:m.buffer;if(S&&y!=="initSegment"){const A=u||l,I=this.blockedAudioAppend;if(a==="audio"&&h!=="main"&&!this.blockedAudioAppend&&!(m.ending||m.ended)){const w=A.start+A.duration*.05,R=S.buffered,M=this.currentOp("video");!R.length&&!M?this.blockAudio(A):!M&&!ae.isBuffered(S,w)&&this.lastVideoAppendEnd<w&&this.blockAudio(A)}else if(a==="video"){const L=A.end;if(I){const w=I.frag.start;(L>w||L<this.lastVideoAppendEnd||ae.isBuffered(S,w))&&this.unblockAudio()}this.lastVideoAppendEnd=L}}const T=(u||l).start,b={label:`append-${a}`,execute:()=>{var A;g.executeStart=self.performance.now();const I=(A=this.tracks[a])==null?void 0:A.buffer;I&&(f?this.updateTimestampOffset(I,T,.1,a,y,x):p!==void 0&&q(p)&&this.updateTimestampOffset(I,p,1e-6,a,y,x)),this.appendExecutor(n,a)},onStart:()=>{},onComplete:()=>{const A=self.performance.now();g.executeEnd=g.end=A,_.first===0&&(_.first=A),o&&o.first===0&&(o.first=A);const I={};this.sourceBuffers.forEach(([L,w])=>{L&&(I[L]=ae.getBuffered(w))}),this.appendErrors[a]=0,a==="audio"||a==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(E.BUFFER_APPENDED,{type:a,frag:l,part:u,chunkMeta:d,parent:l.type,timeRanges:I})},onError:A=>{var I;const L={type:Z.MEDIA_ERROR,parent:l.type,details:D.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:l,part:u,chunkMeta:d,error:A,err:A,fatal:!1},w=(I=this.media)==null?void 0:I.error;if(A.code===DOMException.QUOTA_EXCEEDED_ERR||A.name=="QuotaExceededError"||"quota"in A)L.details=D.BUFFER_FULL_ERROR;else if(A.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!w)L.errorAction=ls(!0);else if(A.name===lu&&this.sourceBufferCount===0)L.errorAction=ls(!0);else{const R=++this.appendErrors[a];this.warn(`Failed ${R}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer (${w||"no media error"})`),(R>=this.hls.config.appendErrorMaxRetry||w)&&(L.fatal=!0)}this.hls.trigger(E.ERROR,L)}};this.log(`queuing "${a}" append sn: ${y}${u?" p: "+u.index:""} of ${l.type===X.MAIN?"level":"track"} ${l.level} cc: ${x}`),this.append(b,a,this.isPending(this.tracks[a]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(E.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:s,startOffset:n,endOffset:a}=t;s?this.append(this.getFlushOp(s,n,a),s):this.sourceBuffers.forEach(([h])=>{h&&this.append(this.getFlushOp(h,n,a),h)})}onFragParsed(e,t){const{frag:s,part:n}=t,a=[],h=n?n.elementaryStreams:s.elementaryStreams;h[Te.AUDIOVIDEO]?a.push("audiovideo"):(h[Te.AUDIO]&&a.push("audio"),h[Te.VIDEO]&&a.push("video"));const l=()=>{const u=self.performance.now();s.stats.buffering.end=u,n&&(n.stats.buffering.end=u);const d=n?n.stats:s.stats;this.hls.trigger(E.FRAG_BUFFERED,{frag:s,part:n,stats:d,id:s.type})};a.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(l,a).catch(u=>{this.warn(`Fragment buffered callback ${u}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([h])=>{if(h){const l=this.tracks[h];(!t.type||t.type===h)&&(l.ending=!0,l.ended||(l.ended=!0,this.log(`${h} buffer reached EOS`)))}});const n=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([h])=>{var l;return h&&!((l=this.tracks[h])!=null&&l.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:h}=this;if(!h||h.readyState!=="open"){h&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${h.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),h.endOfStream(),this.hls.trigger(E.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(E.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}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(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===D.BUFFER_APPEND_ERROR&&t.frag){var s;const n=(s=t.errorAction)==null?void 0:s.nextAutoLevel;q(n)&&n!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;const n=e.config,a=s.currentTime,h=t.levelTargetDuration,l=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(q(l)&&l>=0){const d=Math.max(l,h),p=Math.floor(a/h)*h-d;this.flushBackBuffer(a,h,p)}const u=n.frontBufferFlushThreshold;if(q(u)&&u>0){const d=Math.max(n.maxBufferLength,u),p=Math.max(d,h),g=Math.floor(a/h)*h+p;this.flushFrontBuffer(a,h,g)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([n,a])=>{if(a){const l=ae.getBuffered(a);if(l.length>0&&s>l.start(0)){var h;this.hls.trigger(E.BACK_BUFFER_REACHED,{bufferEnd:s});const u=this.tracks[n];if((h=this.details)!=null&&h.live)this.hls.trigger(E.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(u!=null&&u.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:n})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([n,a])=>{if(a){const h=ae.getBuffered(a),l=h.length;if(l<2)return;const u=h.start(l-1),d=h.end(l-1);if(s>u||e>=u&&e<=d)return;this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||(s==null?void 0:s.readyState)!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const d=Math.max(0,t.fragmentStart),p=Math.max(d,n);return{duration:1/0,start:d,end:p}}return{duration:1/0}}const a=(e=this.overrides)==null?void 0:e.duration;if(a)return q(a)?{duration:a}:null;const h=this.media.duration,l=q(s.duration)?s.duration:0;return n>l&&n>h||!q(h)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:s}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(q(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${s}.`),n.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${be(s)}`),this.tracksReady){var n;const a=(n=this.transferData)==null?void 0:n.tracks;a&&Object.keys(a).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const n=this.tracks[t];e[t]={buffer:s,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger(E.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(E.ERROR,{type:Z.MEDIA_ERROR,details:D.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const a in e){const h=a,l=e[h];if(this.isPending(l)){const u=this.getTrackCodec(l,h),d=`${l.container};codecs=${u}`;l.codec=u,this.log(`creating sourceBuffer(${d})${this.currentOp(h)?" Queued":""} ${be(l)}`);try{const p=s.addSourceBuffer(d),g=pa(h),y=[h,p];t[g]=y,l.buffer=p}catch(p){var n;this.error(`error while trying to add sourceBuffer: ${p.message}`),this.shiftAndExecuteNext(h),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[h],this.hls.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:p,sourceBufferName:h,mimeType:d,parent:l.id});return}this.trackSourceBuffer(h,l)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let n=e.codec;s&&(t==="video"||t==="audiovideo")&&Gs(s,"video")&&(n=tm(n,s));const a=Mn(n,e.levelCodec);return a?t.slice(0,5)==="audio"?Qn(a,this.appendSource):a:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,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",(a,h)=>{const l=h.removedRanges;l!=null&&l.length&&this.hls.trigger(E.BUFFER_FLUSHED,{type:a})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s==null?void 0:s.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 s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${n}`,t),this.hls.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const a=this.currentOp(e);a&&a.onError(n)}updateTimestampOffset(e,t,s,n,a,h){const l=t-e.timestampOffset;Math.abs(l)>=s&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${t} (sn: ${a} cc: ${h})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:n,mediaSource:a}=this,h=this.tracks[e],l=h==null?void 0:h.buffer;if(!n||!a||!l){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const u=q(n.duration)?n.duration:1/0,d=q(a.duration)?a.duration:1/0,p=Math.max(0,t),g=Math.min(s,u,d);g>p&&(!h.ending||h.ended)?(h.ended=!1,this.log(`Removing [${p},${g}] from the ${e} SourceBuffer`),l.remove(p,g)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],n=s==null?void 0:s.buffer;if(!n)throw new cv(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.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:s}=this,n=t.map(h=>this.appendBlocker(h));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(h=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const n=(s=this.tracks[t])==null?void 0:s.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}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,s){const n=this.tracks[e];if(!n)return;const a=n.buffer;if(!a)return;const h=s.bind(this,e);n.listeners.push({event:t,listener:h}),a.addEventListener(t,h)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(n=>{s.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}}function Ph(r){const e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function uv(r,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}function pa(r){return r==="audio"?1:0}class Yo{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(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.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 s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&q(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,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 s=t.filter((n,a)=>this.isLevelAllowed(n)&&a<=e);return this.clientRect=null,Yo.getMaxLevelByMediaSize(s,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 s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.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(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const n=(l,u)=>u?l.width!==u.width||l.height!==u.height:!0;let a=e.length-1;const h=Math.max(t,s);for(let l=0;l<e.length;l+=1){const u=e[l];if((u.width>=h||u.height>=h)&&n(u,e[l+1])){a=l;break}}return a}}const fv={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},et=fv,pv={HLS:"h"},gv=pv;class Gt{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof Gt?s:new Gt(s))),this.value=e,this.params=t}}const mv="Dict";function yv(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 vv(r,e,t,s){return new Error(`failed to ${r} "${yv(e)}" as ${t}`,{cause:s})}function zt(r,e,t){return vv("serialize",r,e,t)}class hu{constructor(e){this.description=e}}const Dh="Bare Item",xv="Boolean";function Sv(r){if(typeof r!="boolean")throw zt(r,xv);return r?"?1":"?0"}function _v(r){return btoa(String.fromCharCode(...r))}const Ev="Byte Sequence";function Tv(r){if(ArrayBuffer.isView(r)===!1)throw zt(r,Ev);return`:${_v(r)}:`}const bv="Integer";function Av(r){return r<-999999999999999||999999999999999<r}function cu(r){if(Av(r))throw zt(r,bv);return r.toString()}function Iv(r){return`@${cu(r.getTime()/1e3)}`}function du(r,e){if(r<0)return-du(-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}const wv="Decimal";function Lv(r){const e=du(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw zt(r,wv);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Rv="String",Cv=/[\x00-\x1f\x7f]+/;function Pv(r){if(Cv.test(r))throw zt(r,Rv);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Dv(r){return r.description||r.toString().slice(7,-1)}const kv="Token";function kh(r){const e=Dv(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw zt(e,kv);return e}function Ja(r){switch(typeof r){case"number":if(!q(r))throw zt(r,Dh);return Number.isInteger(r)?cu(r):Lv(r);case"string":return Pv(r);case"symbol":return kh(r);case"boolean":return Sv(r);case"object":if(r instanceof Date)return Iv(r);if(r instanceof Uint8Array)return Tv(r);if(r instanceof hu)return kh(r);default:throw zt(r,Dh)}}const Mv="Key";function eo(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw zt(r,Mv);return r}function Wo(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${eo(e)}`:`;${eo(e)}=${Ja(t)}`).join("")}function uu(r){return r instanceof Gt?`${Ja(r.value)}${Wo(r.params)}`:Ja(r)}function Fv(r){return`(${r.value.map(uu).join(" ")})${Wo(r.params)}`}function Uv(r,e={whitespace:!0}){if(typeof r!="object"||r==null)throw zt(r,mv);const t=r instanceof Map?r.entries():Object.entries(r),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([n,a])=>{a instanceof Gt||(a=new Gt(a));let h=eo(n);return a.value===!0?h+=Wo(a.params):(h+="=",Array.isArray(a.value)?h+=Fv(a):h+=uu(a)),h}).join(`,${s}`)}function fu(r,e){return Uv(r,e)}const Rt="CMCD-Object",Re="CMCD-Request",Ci="CMCD-Session",li="CMCD-Status",Ov={br:Rt,ab:Rt,d:Rt,ot:Rt,tb:Rt,tpb:Rt,lb:Rt,tab:Rt,lab:Rt,url:Rt,pb:Re,bl:Re,tbl:Re,dl:Re,ltc:Re,mtp:Re,nor:Re,nrr:Re,rc:Re,sn:Re,sta:Re,su:Re,ttfb:Re,ttfbb:Re,ttlb:Re,cmsdd:Re,cmsds:Re,smrt:Re,df:Re,cs:Re,ts:Re,cid:Ci,pr:Ci,sf:Ci,sid:Ci,st:Ci,v:Ci,msd:Ci,bs:li,bsd:li,cdn:li,rtp:li,bg:li,pt:li,ec:li,e:li},Bv={REQUEST:Re};function Nv(r){return Object.keys(r).reduce((e,t)=>{var s;return(s=r[t])===null||s===void 0||s.forEach(n=>e[n]=t),e},{})}function $v(r,e){const t={};if(!r)return t;const s=Object.keys(r),n=e?Nv(e):{};return s.reduce((a,h)=>{var l;const u=Ov[h]||n[h]||Bv.REQUEST,d=(l=a[u])!==null&&l!==void 0?l:a[u]={};return d[h]=r[h],a},t)}function Gv(r){return["ot","sf","st","e","sta"].includes(r)}function zv(r){return typeof r=="number"?q(r):r!=null&&r!==""&&r!==!1}const pu="event";function Hv(r,e){const t=new URL(r),s=new URL(e);if(t.origin!==s.origin)return r;const n=t.pathname.split("/").slice(1),a=s.pathname.split("/").slice(1,-1);for(;n[0]===a[0];)n.shift(),a.shift();for(;a.length;)a.shift(),n.unshift("..");return n.join("/")+t.search+t.hash}const Nn=r=>Math.round(r),to=(r,e)=>Array.isArray(r)?r.map(t=>to(t,e)):r instanceof Gt&&typeof r.value=="string"?new Gt(to(r.value,e),r.params):(e.baseUrl&&(r=Hv(r,e.baseUrl)),e.version===1?encodeURIComponent(r):r),Sn=r=>Nn(r/100)*100,Vv=(r,e)=>{let t=r;return e.version>=2&&(r instanceof Gt&&typeof r.value=="string"?t=new Gt([r]):typeof r=="string"&&(t=[r])),to(t,e)},Kv={br:Nn,d:Nn,bl:Sn,dl:Sn,mtp:Sn,nor:Vv,rtp:Sn,tb:Nn},gu="request",mu="response",jo=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Yv=["e"],Wv=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Cr(r){return Wv.test(r)}function jv(r){return jo.includes(r)||Yv.includes(r)||Cr(r)}const yu=["d","dl","nor","ot","rtp","su"];function qv(r){return jo.includes(r)||yu.includes(r)||Cr(r)}const Xv=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function Qv(r){return jo.includes(r)||yu.includes(r)||Xv.includes(r)||Cr(r)}const Zv=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Jv(r){return Zv.includes(r)||Cr(r)}const ex={[mu]:Qv,[pu]:jv,[gu]:qv};function vu(r,e={}){const t={};if(r==null||typeof r!="object")return t;const s=e.version||r.v||1,n=e.reportingMode||gu,a=s===1?Jv:ex[n];let h=Object.keys(r).filter(a);const l=e.filter;typeof l=="function"&&(h=h.filter(l));const u=n===mu||n===pu;u&&!h.includes("ts")&&h.push("ts"),s>1&&!h.includes("v")&&h.push("v");const d=Ee({},Kv,e.formatters),p={version:s,reportingMode:n,baseUrl:e.baseUrl};return h.sort().forEach(g=>{let y=r[g];const x=d[g];if(typeof x=="function"&&(y=x(y,p)),g==="v"){if(s===1)return;y=s}g=="pr"&&y===1||(u&&g==="ts"&&!q(y)&&(y=Date.now()),zv(y)&&(Gv(g)&&typeof y=="string"&&(y=new hu(y)),t[g]=y))}),t}function tx(r,e={}){const t={};if(!r)return t;const s=vu(r,e),n=$v(s,e==null?void 0:e.customHeaderMap);return Object.entries(n).reduce((a,[h,l])=>{const u=fu(l,{whitespace:!1});return u&&(a[h]=u),a},t)}function ix(r,e,t){return Ee(r,tx(e,t))}const sx="CMCD";function nx(r,e={}){return r?fu(vu(r,e),{whitespace:!1}):""}function rx(r,e={}){if(!r)return"";const t=nx(r,e);return encodeURIComponent(t)}function ax(r,e={}){if(!r)return"";const t=rx(r,e);return`${sx}=${t}`}const Mh=/CMCD=[^&#]+/;function ox(r,e,t){const s=ax(e,t);if(!s)return r;if(Mh.test(r))return r.replace(Mh,s);const n=r.includes("?")?"&":"?";return`${r}${n}${s}`}class lx{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:et.MANIFEST,su:!this.initialized})}catch(a){this.hls.logger.warn("Could not generate manifest CMCD data.",a)}},this.applyFragmentData=n=>{try{const{frag:a,part:h}=n,l=this.hls.levels[a.level],u=this.getObjectType(a),d={d:(h||a).duration*1e3,ot:u};(u===et.VIDEO||u===et.AUDIO||u==et.MUXED)&&(d.br=l.bitrate/1e3,d.tb=this.getTopBandwidth(u)/1e3,d.bl=this.getBufferLength(u));const p=h?this.getNextPart(h):this.getNextFrag(a);p!=null&&p.url&&p.url!==a.url&&(d.nor=p.url),this.apply(n,d)}catch(a){this.hls.logger.warn("Could not generate segment CMCD data.",a)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHED,this.onMediaDetached,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHED,this.onMediaDetached,this),e.off(E.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 s,n;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:gv.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Ee(t,this.createData());const s=t.ot===et.INIT||t.ot===et.VIDEO||t.ot===et.MUXED;this.starved&&s&&(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((h,l)=>(n.includes(l)&&(h[l]=t[l]),h),{}));const a={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),ix(e.headers,t,a)):e.url=ox(e.url,t,a)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const n=e.sn-s.startSN;return s.fragments[n+1]}}getNextPart(e){var t;const{index:s,fragment:n}=e,a=(t=this.hls.levels[n.level])==null||(t=t.details)==null?void 0:t.partList;if(a){const{sn:h}=n;for(let l=a.length-1;l>=0;l--){const u=a[l];if(u.index===s&&u.fragment.sn===h)return a[l+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return et.TIMED_TEXT;if(e.sn==="initSegment")return et.INIT;if(t==="audio")return et.AUDIO;if(t==="main")return this.hls.audioTracks.length?et.VIDEO:et.MUXED}getTopBandwidth(e){let t=0,s;const n=this.hls;if(e===et.AUDIO)s=n.audioTracks;else{const a=n.maxAutoLevel,h=a>-1?a+1:n.levels.length;s=n.levels.slice(0,h)}return s.forEach(a=>{a.bitrate>t&&(t=a.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===et.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:ae.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(a){this.loader=void 0,this.loader=new s(a)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(a,h,l){t(a),this.loader.load(a,h,l)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(a){this.loader=void 0,this.loader=new s(a)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(a,h,l){t(a),this.loader.load(a,h,l)}}}}const hx=3e5;class cx extends xt{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(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.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(s=>s!==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:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((s==null?void 0:s.action)===He.SendAlternateToPenaltyBox&&s.flags===ot.MoveAllAlternatesMatchingHost){const n=this.levels;let a=this._pathwayPriority,h=this.pathwayId;if(t.context){const{groupId:l,pathwayId:u,type:d}=t.context;l&&n?h=this.getPathwayForGroupId(l,d,h):u&&(h=u)}h in this.penalizedPathways||(this.penalizedPathways[h]=performance.now()),!a&&n&&(a=this.pathways()),a&&a.length>1&&(this.updatePathwayPriority(a),s.resolved=this.pathwayId!==h),t.details===D.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${h} levels: ${n&&n.length} priorities: ${be(a)} penalized: ${be(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}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 s=this.penalizedPathways,n=performance.now();Object.keys(s).forEach(a=>{n-s[a]>hx&&delete s[a]});for(let a=0;a<e.length;a++){const h=e[a];if(h in s)continue;if(h===this.pathwayId)return;const l=this.hls.nextLoadLevel,u=this.hls.levels[l];if(t=this.getLevelsForPathway(h),t.length>0){this.log(`Setting Pathway to "${h}"`),this.pathwayId=h,Bd(t),this.hls.trigger(E.LEVELS_UPDATED,{levels:t});const d=this.hls.levels[l];u&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==u.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==u.bitrate&&this.log(`Unstable Pathways change from bitrate ${u.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=l);break}}}getPathwayForGroupId(e,t,s){const n=this.getLevelsForPathway(s).concat(this.levels||[]);for(let a=0;a<n.length;a++)if(t===fe.AUDIO_TRACK&&n[a].hasAudioGroup(e)||t===fe.SUBTITLE_TRACK&&n[a].hasSubtitleGroup(e))return n[a].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},n={};e.forEach(a=>{const{ID:h,"BASE-ID":l,"URI-REPLACEMENT":u}=a;if(t.some(p=>p.pathwayId===h))return;const d=this.getLevelsForPathway(l).map(p=>{const g=new Ae(p.attrs);g["PATHWAY-ID"]=h;const y=g.AUDIO&&`${g.AUDIO}_clone_${h}`,x=g.SUBTITLES&&`${g.SUBTITLES}_clone_${h}`;y&&(s[g.AUDIO]=y,g.AUDIO=y),x&&(n[g.SUBTITLES]=x,g.SUBTITLES=x);const v=xu(p.uri,g["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",u),_=new Hs({attrs:g,audioCodec:p.audioCodec,bitrate:p.bitrate,height:p.height,name:p.name,url:v,videoCodec:p.videoCodec,width:p.width});if(p.audioGroups)for(let o=1;o<p.audioGroups.length;o++)_.addGroupId("audio",`${p.audioGroups[o]}_clone_${h}`);if(p.subtitleGroups)for(let o=1;o<p.subtitleGroups.length;o++)_.addGroupId("text",`${p.subtitleGroups[o]}_clone_${h}`);return _});t.push(...d),Fh(this.audioTracks,s,u,h),Fh(this.subtitleTracks,n,u,h)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(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 p=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+p)}const a={responseType:"json",url:n.href},h=t.steeringManifestLoadPolicy.default,l=h.errorRetry||h.timeoutRetry||{},u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},d={onSuccess:(p,g,y,x)=>{this.log(`Loaded steering manifest: "${n}"`);const v=p.data;if((v==null?void 0:v.VERSION)!==1){this.log(`Steering VERSION ${v.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=v.TTL;const{"RELOAD-URI":_,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":c}=v;if(_)try{this.uri=new self.URL(_,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${_}`);return}this.scheduleRefresh(this.uri||y.url),o&&this.clonePathways(o);const f={steeringManifest:v,url:n.toString()};this.hls.trigger(E.STEERING_MANIFEST_LOADED,f),c&&this.updatePathwayPriority(c)},onError:(p,g,y,x)=>{if(this.log(`Error loading steering manifest: ${p.code} ${p.text} (${g.url})`),this.stopLoad(),p.code===410){this.enabled=!1,this.log(`Steering manifest ${g.url} no longer available`);return}let v=this.timeToLoad*1e3;if(p.code===429){const _=this.loader;if(typeof(_==null?void 0:_.getResponseHeader)=="function"){const o=_.getResponseHeader("Retry-After");o&&(v=parseFloat(o)*1e3)}this.log(`Steering manifest ${g.url} rate limited`);return}this.scheduleRefresh(this.uri||g.url,v)},onTimeout:(p,g,y)=>{this.log(`Timeout loading steering manifest (${g.url})`),this.scheduleRefresh(this.uri||g.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(a,u,d)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const n=(s=this.hls)==null?void 0:s.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Fh(r,e,t,s){r&&Object.keys(e).forEach(n=>{const a=r.filter(h=>h.groupId===n).map(h=>{const l=Ee({},h);return l.details=void 0,l.attrs=new Ae(l.attrs),l.url=l.attrs.URI=xu(h.url,h.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),l.groupId=l.attrs["GROUP-ID"]=e[n],l.attrs["PATHWAY-ID"]=s,l});r.push(...a)})}function xu(r,e,t,s){const{HOST:n,PARAMS:a,[t]:h}=s;let l;e&&(l=h==null?void 0:h[e],l&&(r=l));const u=new self.URL(r);return n&&!l&&(u.host=n),a&&Object.keys(a).sort().forEach(d=>{d&&u.searchParams.set(d,a[d])}),u.href}class cs extends xt{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.mediaKeys=null,this.setMediaKeysQueue=cs.CDMCleanupPromise?[cs.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:s,initData:n}=t,a=`"${t.type}" event: init data type: "${s}"`;if(this.debug(a),n!==null){if(!this.keyFormatPromise){let h=Object.keys(this.keySystemAccessPromises);h.length||(h=Rs(this.config));const l=h.map(aa).filter(u=>!!u);this.keyFormatPromise=this.getKeyFormatPromise(l)}this.keyFormatPromise.then(h=>{const l=Un(h);if(s!=="sinf"||l!==Le.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${l}`);return}let u;try{const x=Me(new Uint8Array(n)),v=Uo(JSON.parse(x).sinf),_=fd(v);if(!_)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");u=new Uint8Array(_.subarray(8,24))}catch(x){this.warn(`${a} Failed to parse sinf: ${x}`);return}const d=Ze(u),{keyIdToKeySessionPromise:p,mediaKeySessions:g}=this;let y=p[d];for(let x=0;x<g.length;x++){const v=g[x],_=v.decryptdata;if(!_.keyId)continue;const o=Ze(_.keyId);if(ir(u,_.keyId)||_.uri.replace(/-/g,"").indexOf(d)!==-1){if(y=p[o],!y)continue;if(_.pssh)break;delete p[o],_.pssh=new Uint8Array(n),_.keyId=u,y=p[d]=y.then(()=>this.generateRequestWithPreferredKeySession(v,s,n,"encrypted-event-key-match")),y.catch(c=>this.handleError(c));break}}y||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${g.length}.`))}).catch(h=>this.handleError(h))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(E.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(E.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,n=t==null?void 0:t[e];if(n)return n.licenseUrl;if(e===Le.WIDEVINE&&s)return s}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,s=t==null?void 0:t[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(h,l,u)=>!!h&&u.indexOf(h)===l,n=t.map(h=>h.audioCodec).filter(s),a=t.map(h=>h.videoCodec).filter(s);return n.length+a.length===0&&a.push("avc1.42e01e"),new Promise((h,l)=>{const u=d=>{const p=d.shift();this.getMediaKeysPromise(p,n,a).then(g=>h({keySystem:p,mediaKeys:g})).catch(g=>{d.length?u(d):g instanceof at?l(g):l(new at({type:Z.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_ACCESS,error:g,fatal:!0},g.message))})};u(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${s}`;return Cd===null&&self.location.protocol==="http:"&&(n=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(n))}return s(e,t)}getMediaKeysPromise(e,t,s){var n;const a=Vm(e,t,s,this.config.drmSystemOptions||{});let h=this.keySystemAccessPromises[e],l=(n=h)==null?void 0:n.keySystemAccess;if(!l){this.log(`Requesting encrypted media "${e}" key-system access with config: ${be(a)}`),l=this.requestMediaKeySystemAccess(e,a);const u=h=this.keySystemAccessPromises[e]={keySystemAccess:l};return l.catch(d=>{this.log(`Failed to obtain access to key-system "${e}": ${d}`)}),l.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);const p=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const g=u.mediaKeys=d.createMediaKeys().then(y=>(this.log(`Media-keys created for "${e}"`),u.hasMediaKeys=!0,p.then(x=>x?this.setMediaKeysServerCertificate(y,e,x):y)));return g.catch(y=>{this.error(`Failed to create media-keys for "${e}"}: ${y}`)}),g})}return l.then(()=>h.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Ze(e.keyId||[])} keyUri: ${e.uri}`);const n=s.createSession(),a={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(a),a}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),n=_n(t),a="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(s,a,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${Ze(e.decryptdata.keyId||[])}
|
|
132
|
+
} (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>aa(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:n})=>{const a=aa(n);a?t(a):s(new Error(`Unable to find format for key-system "${n}"`))}).catch(s)})}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){const t=Rs(this.config),s=e.map(Un).filter(n=>!!n&&t.indexOf(n)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const n=dx(e,t[s]);if(n)return n}}loadKey(e){const t=e.keyInfo.decryptdata,s=_n(t),n=this.bannedKeyIds[s];if(n||this.getKeyStatus(t)==="internal-error"){const l=Uh(n||"internal-error",t);return this.handleError(l,e.frag),Promise.reject(l)}const a=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${a}`);const h=this.keyIdToKeySessionPromise[s];if(!h){const l=this.getKeySystemForKeyPromise(t).then(({keySystem:u,mediaKeys:d})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${a}`),this.attemptSetMediaKeys(u,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:u,mediaKeys:d,decryptdata:t}))))).then(u=>{const d="cenc",p=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(u,d,p,"playlist-key")});return l.catch(u=>this.handleError(u,e.frag)),this.keyIdToKeySessionPromise[s]=l,l}return h.catch(l=>{if(l instanceof at){const u=xe({},l.data);this.getKeyStatus(t)==="internal-error"&&(u.decryptdata=t);const d=new at(u,l.message);this.handleError(d,e.frag)}}),h}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof at){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Ze(s.keyId||[])})`:""}`),this.hls.trigger(E.ERROR,e.data)}else this.error(e.message),this.hls.trigger(E.ERROR,{type:Z.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=_n(e),s=this.keyIdToKeySessionPromise[t];if(!s){const n=Un(e.keyFormat),a=n?[n]:Rs(this.config);return this.attemptKeySystemAccess(a)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Rs(this.config)),e.length===0)throw new at({type:Z.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${be({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(s).then(()=>{if(!this.media)throw this.mediaKeys=null,new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(a=>s.indexOf(a)===-1)})}generateRequestWithPreferredKeySession(e,t,s,n){var a;const h=(a=this.config.drmSystems)==null||(a=a[e.keySystem])==null?void 0:a.generateRequest;if(h)try{const v=h.call(this.hls,t,s,e);if(!v)throw new Error("Invalid response from configured generateRequest filter");t=v.initDataType,s=v.initData?v.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(v){if(this.warn(v.message),this.hls&&this.hls.config.debug)throw v}if(s===null)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const l=_n(e.decryptdata),u=e.decryptdata.uri;this.log(`Generating key-session request for "${n}" keyId: ${l} URI: ${u} (init data type: ${t} length: ${s.byteLength})`);const d=new Bo,p=e._onmessage=v=>{const _=e.mediaKeysSession;if(!_){d.emit("error",new Error("invalid state"));return}const{messageType:o,message:c}=v;this.log(`"${o}" message event for session "${_.sessionId}" message size: ${c.byteLength}`),o==="license-request"||o==="license-renewal"?this.renewLicense(e,c).catch(f=>{d.eventNames().length?d.emit("error",f):this.handleError(f)}):o==="license-release"?e.keySystem===Le.FAIRPLAY&&this.updateKeySession(e,Wa("acknowledged")).then(()=>this.removeSession(e)).catch(f=>this.handleError(f)):this.warn(`unhandled media key message type "${o}"`)},g=(v,_)=>{_.keyStatus=v;let o;v.startsWith("usable")?d.emit("resolved"):v==="internal-error"||v==="output-restricted"||v==="output-downscaled"?o=Uh(v,_.decryptdata):v==="expired"?o=new Error(`key expired (keyId: ${l})`):v==="released"?o=new Error("key released"):v==="status-pending"||this.warn(`unhandled key status change "${v}" (keyId: ${l})`),o&&(d.eventNames().length?d.emit("error",o):this.handleError(o))},y=e._onkeystatuseschange=v=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const o=this.getKeyStatuses(e);if(!Object.keys(o).some(S=>o[S]!=="status-pending"))return;if(o[l]==="expired"){this.log(`Expired key ${be(o)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let f=o[l];if(f)g(f,e);else{var m;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(m=e.keyStatusTimeouts)[l]||(m[l]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const T=this.getKeyStatus(e.decryptdata);if(T&&T!=="status-pending")return this.log(`No status for keyId ${l} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${T} from other session.`),g(T,e);this.log(`key status for ${l} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),f="internal-error",g(f,e)},1e3)),this.log(`No status for keyId ${l} (${be(o)}).`)}};Je(e.mediaKeysSession,"message",p),Je(e.mediaKeysSession,"keystatuseschange",y);const x=new Promise((v,_)=>{d.on("error",_),d.on("resolved",v)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${l} URI: ${u}`)}).catch(v=>{throw new at({type:Z.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_SESSION,error:v,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${v}`)}).then(()=>x).catch(v=>(d.removeAllListeners(),this.removeSession(e).then(()=>{throw v}))).then(()=>(d.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,n)=>{if(typeof n=="string"&&typeof s=="object"){const l=n;n=s,s=l}const a="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);e.keySystem===Le.PLAYREADY&&a.length===16&&Ld(a);const h=Ze(a);s==="internal-error"&&(this.bannedKeyIds[h]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${h} key-session "${e.mediaKeysSession.sessionId}"`),t[h]=s}),t}fetchServerCertificate(e){const t=this.config,s=t.loader,n=new s(t),a=this.getServerCertificateUrl(e);return a?(this.log(`Fetching server certificate for "${e}"`),new Promise((h,l)=>{const u={responseType:"arraybuffer",url:a},d=t.certLoadPolicy.default,p={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(y,x,v,_)=>{h(y.data)},onError:(y,x,v,_)=>{l(new at({type:Z.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:v,response:xe({url:u.url,data:void 0},y)},`"${e}" certificate request failed (${a}). Status: ${y.code} (${y.text})`))},onTimeout:(y,x,v)=>{l(new at({type:Z.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:v,response:{url:u.url,data:void 0}},`"${e}" certificate request timed out (${a})`))},onAbort:(y,x,v)=>{l(new Error("aborted"))}};n.load(u,p,g)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((n,a)=>{e.setServerCertificate(s).then(h=>{this.log(`setServerCertificate ${h?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),n(e)}).catch(h=>{a(new at({type:Z.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:h,fatal:!0},h.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(n=>{throw new at({type:Z.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:n,fatal:!1},n.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const n=new DOMParser().parseFromString(s,"application/xml"),a=n.querySelectorAll("HttpHeader");if(a.length>0){let p;for(let g=0,y=a.length;g<y;g++){var h,l;p=a[g];const x=(h=p.querySelector("name"))==null?void 0:h.textContent,v=(l=p.querySelector("value"))==null?void 0:l.textContent;x&&v&&e.setRequestHeader(x,v)}}const u=n.querySelector("Challenge"),d=u==null?void 0:u.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return Wa(atob(d))}setupLicenseXHR(e,t,s,n){const a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return a.call(this.hls,e,t,s,n)}).catch(h=>{if(!s.decryptdata)throw h;return e.open("POST",t,!0),a.call(this.hls,e,t,s,n)}).then(h=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:h||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((n,a)=>{const h=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${h}`);const l=new XMLHttpRequest;l.responseType="arraybuffer",l.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(l.readyState===4)if(l.status===200){this._requestLicenseFailureCount=0;let u=l.response;this.log(`License received ${u instanceof ArrayBuffer?u.byteLength:u}`);const d=this.config.licenseResponseCallback;if(d)try{u=d.call(this.hls,l,h,e)}catch(p){this.error(p)}n(u)}else{const u=s.errorRetry,d=u?u.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||l.status>=400&&l.status<500)a(new at({type:Z.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:l,response:{url:h,data:void 0,code:l.status,text:l.statusText}},`License Request XHR failed (${h}). Status: ${l.status} (${l.statusText})`));else{const p=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${p} attempts left`),this.requestLicense(e,t).then(n,a)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=l,this.setupLicenseXHR(l,h,e,t).then(({xhr:u,licenseChallenge:d})=>{e.keySystem==Le.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(u,d)),u.send(d)}).catch(a)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,Je(s,"encrypted",this.onMediaEncrypted),Je(s,"waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media;e&&(it(e,"encrypted",this.onMediaEncrypted),it(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={},!this.mediaKeys&&!this.mediaKeySessions.length)return;const t=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Ni.clearKeyUriToKeyIdMap();const n=s.length;cs.CDMCleanupPromise=Promise.all(s.map(a=>this.removeSession(a)).concat((t==null||(e=t.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(E.ERROR,{type:Z.OTHER_ERROR,details:D.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(E.ERROR,{type:Z.OTHER_ERROR,details:D.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this.keyFormatPromise=null,this.bannedKeyIds={}}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((n,a)=>(n.indexOf(a.keyFormat)===-1&&n.push(a.keyFormat),n),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:n}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Ze((n==null?void 0:n.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const a=this.mediaKeySessions.indexOf(e);a>-1&&this.mediaKeySessions.splice(a,1);const{keyStatusTimeouts:h}=e;h&&Object.keys(h).forEach(d=>self.clearTimeout(h[d]));const{drmSystemOptions:l}=this.config;return(Ym(l)?new Promise((d,p)=>{self.setTimeout(()=>p(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(d).catch(p)}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(E.ERROR,{type:Z.OTHER_ERROR,details:D.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${d}`)})}).then(()=>t.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(E.ERROR,{type:Z.OTHER_ERROR,details:D.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}cs.CDMCleanupPromise=void 0;function _n(r){if(!r)throw new Error("Could not read keyId of undefined decryptdata");if(r.keyId===null)throw new Error("keyId is null");return Ze(r.keyId)}function dx(r,e){if(r.keyId&&e.mediaKeysSession.keyStatuses.has(r.keyId))return e.mediaKeysSession.keyStatuses.get(r.keyId);if(r.matches(e.decryptdata))return e.keyStatus}class at extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function Uh(r,e){const t=r==="output-restricted",s=t?D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:D.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new at({type:Z.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${r}"`)}class ux{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(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.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),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const n=performance.now();if(t){if(this.lastTime){const a=n-this.lastTime,h=s-this.lastDroppedFrames,l=t-this.lastDecodedFrames,u=1e3*h/a,d=this.hls;if(d.trigger(E.FPS_DROP,{currentDropped:h,currentDecoded:l,totalDroppedFrames:s}),u>0&&h>d.config.fpsDroppedMonitoringThreshold*l){let p=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+p),p>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=p)&&(p=p-1,d.trigger(E.FPS_DROP_LEVEL_CAPPING,{level:p,droppedLevel:d.currentLevel}),d.autoLevelCapping=p,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=s,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 Su(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 _u(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(s){_e.debug(`[texttrack-utils]: ${s}`);try{const n=new self.TextTrackCue(e.startTime,e.endTime,e.text);n.id=e.id,r.addCue(n)}catch(n){_e.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(r.mode=t)}function ss(r,e){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues)for(let s=r.cues.length;s--;)e&&r.cues[s].removeEventListener("enter",e),r.removeCue(r.cues[s]);t==="disabled"&&(r.mode=t)}function io(r,e,t,s){const n=r.mode;if(n==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){const a=px(r.cues,e,t);for(let h=0;h<a.length;h++)(!s||s(a[h]))&&r.removeCue(a[h])}n==="disabled"&&(r.mode=n)}function fx(r,e){if(e<=r[0].startTime)return 0;const t=r.length-1;if(e>r[t].endTime)return-1;let s=0,n=t,a;for(;s<=n;)if(a=Math.floor((n+s)/2),e<r[a].startTime)n=a-1;else if(e>r[a].startTime&&s<t)s=a+1;else return a;return r[s].startTime-e<e-r[n].startTime?s:n}function px(r,e,t){const s=[],n=fx(r,e);if(n>-1)for(let a=n,h=r.length;a<h;a++){const l=r[a];if(l.startTime>=e&&l.endTime<=t)s.push(l);else if(l.startTime>t)return s}return s}function $n(r){const e=[];for(let t=0;t<r.length;t++){const s=r[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(r[t])}return e}class gx extends Ko{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 s=$n(this.media.textTracks);for(let a=0;a<s.length;a++)if(s[a].mode==="hidden")t=s[a];else if(s[a].mode==="showing"){t=s[a];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(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.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 s=this.media;if(!s)return;const n=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,n)return;$n(s.textTracks).forEach(h=>{ss(h)})}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:s,groupId:n,details:a}=t,h=this.tracksInGroup[s];if(!h||h.groupId!==n){this.warn(`Subtitle track with id:${s} and group:${n} not found in active group ${h==null?void 0:h.groupId}`);return}const l=h.details;h.details=t.details,this.log(`Subtitle track ${s} "${h.name}" lang:${h.lang} group:${n} loaded [${a.startSN}-${a.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,l)}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 s=t.subtitleGroups||null,n=this.groupIds;let a=this.currentTrack;if(!s||(n==null?void 0:n.length)!==(s==null?void 0:s.length)||s!=null&&s.some(h=>(n==null?void 0:n.indexOf(h))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const h=this.tracks.filter(p=>!s||s.indexOf(p.groupId)!==-1);if(h.length)this.selectDefaultTrack&&!h.some(p=>p.default)&&(this.selectDefaultTrack=!1),h.forEach((p,g)=>{p.id=g});else if(!a&&!this.tracksInGroup.length)return;this.tracksInGroup=h;const l=this.hls.config.subtitlePreference;if(!a&&l){this.selectDefaultTrack=!1;const p=Ft(l,h);if(p>-1)a=h[p];else{const g=Ft(l,this.tracks);a=this.tracks[g]}}let u=this.findTrackId(a);u===-1&&a&&(u=this.findTrackId(null));const d={subtitleTracks:h};this.log(`Updating subtitle tracks, ${h.length} track(s) found in "${s==null?void 0:s.join(",")}" group-id`),this.hls.trigger(E.SUBTITLE_TRACKS_UPDATED,d),u!==-1&&this.trackId===-1&&this.setSubtitleTrack(u)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let n=0;n<t.length;n++){const a=t[n];if(!(s&&!a.default||!s&&!e)&&(!e||Bi(a,e)))return n}if(e){for(let n=0;n<t.length;n++){const a=t[n];if(Ws(e.attrs,a.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(let n=0;n<t.length;n++){const a=t[n];if(Ws(e.attrs,a.attrs,["LANGUAGE"]))return n}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const n=t[s];if(Za(n,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===fe.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 s=this.currentTrack;if(s&&Bi(e,s))return s;const n=Ft(e,this.tracksInGroup);if(n>-1){const a=this.tracksInGroup[n];return this.setSubtitleTrack(n),a}else{if(s)return null;{const a=Ft(e,t);if(a>-1)return t[a]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,t),h=e.details,l=h==null?void 0:h.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${l&&h.live?" age "+l.toFixed(1)+(h.type&&" "+h.type||""):""} ${a}`),this.hls.trigger(E.SUBTITLE_TRACK_LOADING,{url:a,id:s,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=$n(e.textTracks),s=this.currentTrack;let n;if(s&&(n=t.filter(a=>Za(s,a))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(a=>{a.mode!=="disabled"&&a!==n&&(a.mode="disabled")}),n){const a=this.subtitleDisplay?"showing":"hidden";n.mode!==a&&(n.mode=a)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!q(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,n=t[e]||null;if(this.trackId=e,this.currentTrack=n,this.toggleTrackModes(),!n){this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:e});return}const a=!!n.details&&!n.details.live;if(e===this.trackId&&n===s&&a)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:h,groupId:l="",name:u,type:d,url:p}=n;this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:h,groupId:l,name:u,type:d,url:p});const g=this.switchParams(n.url,s==null?void 0:s.details,n.details);this.loadPlaylist(g)}}function mx(){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 a=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(n=="x"?a:a&3|8).toString(16)})}}}function Us(r){let e=5381,t=r.length;for(;t;)e=e*33^r.charCodeAt(--t);return(e>>>0).toString()}const ds=.025;let ar=function(r){return r[r.Point=0]="Point",r[r.Range=1]="Range",r}({});function yx(r,e,t){return`${r.identifier}-${t+1}-${Us(e)}`}class vx{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){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}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,s=ga(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=q(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)<ds))}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"?ar.Range:ar.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 xx(this)}}function ga(r,e){return r-e.start<e.duration/2&&!(Math.abs(r-(e.start+e.duration))<ds)?e.start:e.start+e.duration}function Eu(r,e,t){const s=new self.URL(r,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function ma(r,e){for(;(t=r.assetList[++e])!=null&&t.error;)var t;return e}function xx(r){return`["${r.identifier}" ${r.cue.pre?"<pre>":r.cue.post?"<post>":""}${r.timelineStart.toFixed(2)}-${r.resumeTime.toFixed(2)}]`}function es(r){const e=r.timelineStart,t=r.duration||0;return`["${r.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class Sx{constructor(e,t,s,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=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(E.PLAYOUT_LIMIT_REACHED,{})};const a=this.hls=new e(t);this.interstitial=s,this.assetItem=n;const h=()=>{this.hasDetails=!0};a.once(E.LEVEL_LOADED,h),a.once(E.AUDIO_TRACK_LOADED,h),a.once(E.SUBTITLE_TRACK_LOADED,h),a.on(E.MEDIA_ATTACHING,(l,{media:u})=>{this.removeMediaListeners(),this.mediaAttached=u,this.interstitial.playoutLimit&&(u.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&a.on(E.BUFFER_APPENDED,()=>{const p=this.bufferedEnd;this.reachedPlayout(p)&&(this._bufferedEosTime=p,a.trigger(E.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Eu(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset,a=ae.bufferInfo(e,n,0);return this.getAssetTime(a.end)>=s-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}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=ae.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;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}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 s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}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&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var n;(n=this.hls)==null||n.on(e,t)}once(e,t,s){var n;(n=this.hls)==null||n.once(e,t)}off(e,t,s){var n;(n=this.hls)==null||n.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${es(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Oh=.033;class _x extends xt{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((s,n)=>e<=n.startOffset&&t>n.startOffset?(delete n.error,s+1):s,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 s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const n=this.items;if(n)for(n[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(a=n[s])!=null&&a.event;){var a;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let n=0;n<s.length;n++){let a=s[n];if(t&&t!=="primary"&&(a=a[t]),e===a.start||e>a.start&&e<a.end)return n}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let n=e;n<=t&&s[n];n++){const a=s[n].event;if(a!=null&&a.restrictions.jump&&!a.appendInPlace)return n}return-1}findEventIndex(e){const t=this.items;if(t)for(let n=t.length;n--;){var s;if(((s=t[n].event)==null?void 0:s.identifier)===e)return n}return-1}findAssetIndex(e,t){const s=e.assetList,n=s.length;if(n>1)for(let a=0;a<n;a++){const h=s[a];if(!h.error){const l=h.timelineStart;if(t===l||t>l&&(t<l+(h.duration||0)||a===n-1))return a}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,n=s[s.length-1];if(n)return n.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:n}=s,a=this.events,h=this.parseDateRanges(n,{url:s.url},t),l=Object.keys(n),u=a?a.filter(d=>!l.includes(d.identifier)):[];h.length&&h.sort((d,p)=>{const g=d.cue.pre,y=d.cue.post,x=p.cue.pre,v=p.cue.post;if(g&&!x)return-1;if(x&&!g||y&&!v)return 1;if(v&&!y)return-1;if(!g&&!x&&!y&&!v){const _=d.startTime,o=p.startTime;if(_!==o)return _-o}return d.dateRange.tagOrder-p.dateRange.tagOrder}),this.events=h,u.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(e,u)}updateSchedule(e,t=[],s=!1){const n=this.events||[];if(n.length||t.length||this.length<2){const a=this.items,h=this.parseSchedule(n,e);(s||t.length||(a==null?void 0:a.length)!==h.length||h.some((u,d)=>Math.abs(u.playout.start-a[d].playout.start)>.005||Math.abs(u.playout.end-a[d].playout.end)>.005))&&(this.items=h,this.onScheduleUpdate(t,a))}}parseDateRanges(e,t,s){const n=[],a=Object.keys(e);for(let h=0;h<a.length;h++){const l=a[h],u=e[l];if(u.isInterstitial){let d=this.eventMap[l];d?d.setDateRange(u):(d=new vx(u,t),this.eventMap[l]=d,s===!1&&(d.appendInPlace=s)),n.push(d)}}return n}parseSchedule(e,t){const s=[],n=t.main.details,a=n.live?1/0:n.edge;let h=0;if(e=e.filter(u=>!u.error&&!(u.cue.once&&u.hasPlayed)),e.length){this.resolveOffsets(e,t);let u=0,d=0;if(e.forEach((p,g)=>{const y=p.cue.pre,x=p.cue.post,v=e[g-1]||null,_=p.appendInPlace,o=x?a:p.startOffset,c=p.duration,f=p.timelineOccupancy===ar.Range?c:0,m=p.resumptionOffset,S=(v==null?void 0:v.startTime)===o,T=o+p.cumulativeDuration;let b=_?T+c:o+m;if(y||!x&&o<=0){const I=d;d+=f,p.timelineStart=T;const L=h;h+=c,s.push({event:p,start:T,end:b,playout:{start:L,end:h},integrated:{start:I,end:d}})}else if(o<=a){if(!S){const w=o-u;if(w>Oh){const R=u,M=d;d+=w;const k=h;h+=w;const z={previousEvent:e[g-1]||null,nextEvent:p,start:R,end:R+w,playout:{start:k,end:h},integrated:{start:M,end:d}};s.push(z)}else w>0&&v&&(v.cumulativeDuration+=w,s[s.length-1].end=o)}x&&(b=T),p.timelineStart=T;const I=d;d+=f;const L=h;h+=c,s.push({event:p,start:T,end:b,playout:{start:L,end:h},integrated:{start:I,end:d}})}else return;const A=p.resumeTime;x||A>a?u=a:u=A}),u<a){var l;const p=u,g=d,y=a-u;d+=y;const x=h;h+=y,s.push({previousEvent:((l=s[s.length-1])==null?void 0:l.event)||null,nextEvent:null,start:u,end:p+y,playout:{start:x,end:h},integrated:{start:g,end:d}})}this.setDurations(a,h,d)}else s.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,n=s.live?1/0:s.edge;let a=0,h=-1;e.forEach((l,u)=>{const d=l.cue.pre,p=l.cue.post,g=d?0:p?n:l.startTime;this.updateAssetDurations(l),h===g?l.cumulativeDuration=a:(a=0,h=g),!p&&l.snapOptions.in&&(l.resumeAnchor=zi(null,s.fragments,l.startOffset+l.resumptionOffset,0,0)||void 0),l.appendInPlace&&!l.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(l,t)||(l.appendInPlace=!1)),!l.appendInPlace&&u+1<e.length&&e[u+1].startTime-e[u].resumeTime<Oh&&(e[u+1].appendInPlace=!1,e[u+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${l}`));const x=q(l.resumeOffset)?l.resumeOffset:l.duration;a+=x})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(s-n)>ds?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${n}`),!1):!Object.keys(t).some(h=>{const l=t[h].details,u=l.edge;if(s>=u)return this.log(`"${e.identifier}" resumption ${s} past ${h} playlist end ${u}`),!1;const d=zi(null,l.fragments,s);if(!d)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${h} playlist (${l.fragStart}-${l.fragmentEnd})`),!0;const p=h==="audio"?.175:0;return Math.abs(d.start-s)<ds+p||Math.abs(d.end-s)<ds+p?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${h} fragment bounds (${d.start}-${d.end} sn: ${d.sn} cc: ${d.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,n=!1,a=!1;for(let h=0;h<e.assetList.length;h++){const l=e.assetList[h],u=t+s;l.startOffset=s,l.timelineStart=u,n||(n=l.duration===null),a||(a=!!l.error);const d=l.error?0:l.duration||0;s+=d}n&&!a?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function _t(r){return`[${r.event?'"'+r.event.identifier+'"':"primary"}: ${r.start.toFixed(2)}-${r.end.toFixed(2)}]`}class Ex{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let n;try{n=Eu(s,this.hls.sessionId,e.baseUrl)}catch(y){const x=this.assignAssetListError(e,D.ASSET_LIST_LOAD_ERROR,y,s);this.hls.trigger(E.ERROR,x);return}t&&n.protocol!=="data:"&&n.searchParams.set("_HLS_start_offset",""+t);const a=this.hls.config,h=a.loader,l=new h(a),u={responseType:"json",url:n.href},d=a.interstitialAssetListLoadPolicy.default,p={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(y,x,v,_)=>{const o=y.data,c=o==null?void 0:o.ASSETS;if(!Array.isArray(c)){const f=this.assignAssetListError(e,D.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),v.url,x,_);this.hls.trigger(E.ERROR,f);return}e.assetListResponse=o,this.hls.trigger(E.ASSET_LIST_LOADED,{event:e,assetListResponse:o,networkDetails:_})},onError:(y,x,v,_)=>{const o=this.assignAssetListError(e,D.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${y.code} ${y.text} (${x.url})`),x.url,_,v);this.hls.trigger(E.ERROR,o)},onTimeout:(y,x,v)=>{const _=this.assignAssetListError(e,D.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${x.url})`),x.url,y,v);this.hls.trigger(E.ERROR,_)}};return l.load(u,p,g),this.hls.trigger(E.ASSET_LIST_LOADING,{event:e}),l}assignAssetListError(e,t,s,n,a,h){return e.error=s,{type:Z.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:s,networkDetails:h,stats:a}}}function Bh(r){r==null||r.play().catch(()=>{})}function En(r,e){return`[${r}] Advancing timeline position to ${e}`}class Tx extends xt{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 s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const n=s-this.timelinePos;if(Math.abs(n)<1/7056e5)return;const h=n<=-.01;this.timelinePos=s,this.bufferedPos=s;const l=this.playingItem;if(!l){this.checkBuffer();return}if(h&&this.schedule.resetErrorsInRange(s,s-n)&&this.updateSchedule(!0),this.checkBuffer(),h&&s<l.start||s>=l.end){var u;const x=this.findItemIndex(l);let v=this.schedule.findItemIndexAtTime(s);if(v===-1&&(v=x+(h?-1:1),this.log(`seeked ${h?"back ":""}to position not covered by schedule ${s} (resolving from ${x} to ${v})`)),!this.isInterstitial(l)&&(u=this.media)!=null&&u.paused&&(this.shouldPlay=!1),!h&&v>x){const _=this.schedule.findJumpRestrictedIndex(x+1,v);if(_>x){this.setSchedulePosition(_);return}}this.setSchedulePosition(v);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(l)){const x=l.event.assetList[0];x&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,x))}return}const p=d.timelineStart,g=d.duration||0;if(h&&s<p||s>=p+g){var y;(y=l.event)!=null&&y.appendInPlace&&(this.clearInterstitial(l.event,l),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,d)}},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const n=this.playingItem;if(!n||this.playingLastItem)return;if(s>=n.end){this.timelinePos=n.end;const l=this.findItemIndex(n);this.setSchedulePosition(l+1)}const a=this.playingAsset;if(!a)return;const h=a.timelineStart+(a.duration||0);s>=h&&this.setScheduleToAssetAtTime(s,a)},this.onScheduleUpdate=(s,n)=>{const a=this.schedule;if(!a)return;const h=this.playingItem,l=a.events||[],u=a.items||[],d=a.durations,p=s.map(_=>_.identifier),g=!!(l.length||p.length);(g||n)&&this.log(`INTERSTITIALS_UPDATED (${l.length}): ${l}
|
|
133
|
+
Schedule: ${u.map(_=>_t(_))} pos: ${this.timelinePos}`),p.length&&this.log(`Removed events ${p}`);let y=null,x=null;h&&(y=this.updateItem(h,this.timelinePos),this.itemsMatch(h,y)?this.playingItem=y:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const v=this.bufferingItem;if(v&&(x=this.updateItem(v,this.bufferedPos),this.itemsMatch(v,x)?this.bufferingItem=x:v.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(v.event,null))),s.forEach(_=>{_.assetList.forEach(o=>{this.clearAssetPlayer(o.identifier,null)})}),this.playerQueue.forEach(_=>{if(_.interstitial.appendInPlace){const o=_.assetItem.timelineStart,c=_.timelineOffset-o;if(c)try{_.timelineOffset=o}catch(f){Math.abs(c)>ds&&this.warn(`${f} ("${_.assetId}" ${_.timelineOffset}->${o})`)}}}),g||n){if(this.hls.trigger(E.INTERSTITIALS_UPDATED,{events:l.slice(0),schedule:u.slice(0),durations:d,removedIds:p}),this.isInterstitial(h)&&p.includes(h.event.identifier)){this.warn(`Interstitial "${h.event.identifier}" removed while playing`),this.primaryFallback(h.event);return}h&&this.trimInPlace(y,h),v&&x!==y&&this.trimInPlace(x,v),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Ex(e),this.schedule=new _x(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(E.MEDIA_ENDED,this.onMediaEnded,this),e.on(E.ERROR,this.onError,this),e.on(E.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(E.MEDIA_ENDED,this.onMediaEnded,this),e.off(E.ERROR,this.onError,this),e.off(E.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){it(e,"play",this.onPlay),it(e,"pause",this.onPause),it(e,"seeking",this.onSeeking),it(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;Je(s,"seeking",this.onSeeking),Je(s,"timeupdate",this.onTimeupdate),Je(s,"play",this.onPlay),Je(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!n){this.clearScheduleState();const a=this.findItemIndex(s);this.setSchedulePosition(a)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,n=this.media;if(this.media=null,!s&&(n&&this.removeMediaListeners(n),this.detachedData)){const a=this.getBufferingPlayer();a&&(this.log(`Removing schedule state for detachedData and ${a}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,a.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=g=>g&&e.getAssetPlayer(g.identifier),n=(g,y,x,v,_)=>{if(g){let o=g[y].start;const c=g.event;if(c){if(y==="playout"||c.timelineOccupancy!==ar.Point){const f=s(x);(f==null?void 0:f.interstitial)===c&&(o+=f.assetItem.startOffset+f[_])}}else{const f=v==="bufferedPos"?h():e[v];o+=f-g.start}return o}return 0},a=(g,y)=>{var x;if(g!==0&&y!=="primary"&&(x=e.schedule)!=null&&x.length){var v;const _=e.schedule.findItemIndexAtTime(g),o=(v=e.schedule.items)==null?void 0:v[_];if(o){const c=o[y].start-o.start;return g+c}}return g},h=()=>{const g=e.bufferedPos;return g===Number.MAX_VALUE?l("primary"):Math.max(g,0)},l=g=>{var y,x;return(y=e.primaryDetails)!=null&&y.live?e.primaryDetails.edge:((x=e.schedule)==null?void 0:x.durations[g])||0},u=(g,y)=>{var x,v;const _=e.effectivePlayingItem;if(_!=null&&(x=_.event)!=null&&x.restrictions.skip||!e.schedule)return;e.log(`seek to ${g} "${y}"`);const o=e.effectivePlayingItem,c=e.schedule.findItemIndexAtTime(g,y),f=(v=e.schedule.items)==null?void 0:v[c],m=e.getBufferingPlayer(),S=m==null?void 0:m.interstitial,T=S==null?void 0:S.appendInPlace,b=o&&e.itemsMatch(o,f);if(o&&(T||b)){const A=s(e.playingAsset),I=(A==null?void 0:A.media)||e.primaryMedia;if(I){const L=y==="primary"?I.currentTime:n(o,y,e.playingAsset,"timelinePos","currentTime"),w=g-L,R=(T?L:I.currentTime)+w;if(R>=0&&(!A||T||R<=A.duration)){I.currentTime=R;return}}}if(f){let A=g;if(y!=="primary"){const L=f[y].start,w=g-L;A=f.start+w}const I=!e.isInterstitial(f);if((!e.isInterstitial(o)||o.event.appendInPlace)&&(I||f.event.appendInPlace)){const L=e.media||(T?m==null?void 0:m.media:null);L&&(L.currentTime=A)}else if(o){const L=e.findItemIndex(o);if(c>L){const R=e.schedule.findJumpRestrictedIndex(L+1,c);if(R>L){e.setSchedulePosition(R);return}}let w=0;if(I)e.timelinePos=A,e.checkBuffer();else{const R=f.event.assetList,M=g-(f[y]||f).start;for(let k=R.length;k--;){const z=R[k];if(z.duration&&M>=z.startOffset&&M<z.startOffset+z.duration){w=k;break}}}e.setSchedulePosition(c,w)}}},d=()=>{const g=e.effectivePlayingItem;if(e.isInterstitial(g))return g;const y=t();return e.isInterstitial(y)?y:null},p={get bufferedEnd(){const g=t(),y=e.bufferingItem;if(y&&y===g){var x;return n(y,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-y.playout.start||((x=e.bufferingAsset)==null?void 0:x.startOffset)||0}return 0},get currentTime(){const g=d(),y=e.effectivePlayingItem;return y&&y===g?n(y,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-y.playout.start:0},set currentTime(g){const y=d(),x=e.effectivePlayingItem;x&&x===y&&u(g+x.playout.start,"playout")},get duration(){const g=d();return g?g.playout.end-g.playout.start:0},get assetPlayers(){var g;const y=(g=d())==null?void 0:g.event.assetList;return y?y.map(x=>e.getAssetPlayer(x.identifier)):[]},get playingIndex(){var g;const y=(g=d())==null?void 0:g.event;return y&&e.effectivePlayingAsset?y.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var g;return((g=e.schedule)==null||(g=g.events)==null?void 0:g.slice(0))||[]},get schedule(){var g;return((g=e.schedule)==null||(g=g.items)==null?void 0:g.slice(0))||[]},get interstitialPlayer(){return d()?p:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const g=t();return e.findItemIndex(g)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const g=e.effectivePlayingItem;return e.findItemIndex(g)},primary:{get bufferedEnd(){return h()},get currentTime(){const g=e.timelinePos;return g>0?g:0},set currentTime(g){u(g,"primary")},get duration(){return l("primary")},get seekableStart(){var g;return((g=e.primaryDetails)==null?void 0:g.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(g){u(g,"integrated")},get duration(){return l("integrated")},get seekableStart(){var g;return a(((g=e.primaryDetails)==null?void 0:g.fragmentStart)||0,"integrated")}},skip:()=>{const g=e.effectivePlayingItem,y=g==null?void 0:g.event;if(y&&!y.restrictions.skip){const x=e.findItemIndex(g);if(y.appendInPlace){const v=g.playout.start+g.event.duration;u(v+.001,"playout")}else e.advanceAfterAssetEnded(y,x,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);const a=(t=n)==null?void 0:t.currentTime;if(!(a===void 0||!q(a)))return a}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 s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,n=e.media;if(s&&n===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&n){this.detachedData={media:n};return}const a=e.transferMedia();this.log(`transfer MediaSource from ${e} ${be(a)}`),this.detachedData=a}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(e,t){var s,n;if(e.media===t)return;let a=null;const h=this.hls,l=e!==h,u=l&&e.interstitial.appendInPlace,d=(s=this.detachedData)==null?void 0:s.mediaSource;let p;if(h.media)u&&(a=h.transferMedia(),this.detachedData=a),p="Primary";else if(d){const v=this.getBufferingPlayer();v?(a=v.transferMedia(),p=`${v}`):p="detached MediaSource"}else p="detached media";if(!a){if(d)a=this.detachedData,this.log(`using detachedData: MediaSource ${be(a)}`);else if(!this.detachedData||h.media===t){const v=this.playerQueue;v.length>1&&v.forEach(_=>{if(l&&_.interstitial.appendInPlace!==u){const o=_.interstitial;this.clearInterstitial(_.interstitial,null),o.appendInPlace=!1,o.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${o}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const g=a&&"mediaSource"in a&&((n=a.mediaSource)==null?void 0:n.readyState)!=="closed",y=g&&a?a:t;this.log(`${g?"transfering MediaSource":"attaching media"} to ${l?e:"Primary"} from ${p} (media.currentTime: ${t.currentTime})`);const x=this.schedule;if(y===a&&x){const v=l&&e.assetId===x.assetIdAtEnd;y.overrides={duration:x.duration,endOfStream:!l||v,cueRemoval:!l}}e.attachMedia(y)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e==null?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const s=this.timelinePos,n=this.effectivePlayingItem;if(s===-1){const a=this.hls.startPosition;if(this.log(En("checkStart",a)),this.timelinePos=a,t.length&&t[0].cue.pre){const h=e.findEventIndex(t[0].identifier);this.setSchedulePosition(h)}else if(a>=0||!this.primaryLive){const h=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(h);this.setSchedulePosition(l)}}else if(n&&!this.playingItem){const a=e.findItemIndex(n);this.setSchedulePosition(a)}}advanceAssetBuffering(e,t){const s=e.event,n=s.findAssetIndex(t),a=ma(s,n);if(!s.isAssetPastPlayoutLimit(a))this.bufferedToEvent(e,a);else if(this.schedule){var h;const l=(h=this.schedule.items)==null?void 0:h[this.findItemIndex(e)+1];l&&this.bufferedToItem(l)}}advanceAfterAssetEnded(e,t,s){const n=ma(e,s);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){const a=this.schedule.items;if(a){const h=t+1,l=a.length;if(h>=l){this.setSchedulePosition(-1);return}const u=e.resumeTime;this.timelinePos<u&&(this.log(En("advanceAfterAssetEnded",u)),this.timelinePos=u,e.appendInPlace&&this.advanceInPlace(u),this.checkBuffer(this.bufferedPos<u)),this.setSchedulePosition(h)}}}else{if(e.appendInPlace){const a=e.assetList[n];a&&this.advanceInPlace(a.timelineStart)}this.setSchedulePosition(t,n)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const n=t.parentIdentifier,a=s.getEvent(n);if(a){const h=s.findEventIndex(n),l=s.findAssetIndex(a,e);this.advanceAfterAssetEnded(a,h,l-1)}}setSchedulePosition(e,t){var s;const n=(s=this.schedule)==null?void 0:s.items;if(!n||this.playbackDisabled)return;const a=e>=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${a&&_t(a)}) pos: ${this.timelinePos}`);const h=this.waitingItem||this.playingItem,l=this.playingLastItem;if(this.isInterstitial(h)){const p=h.event,g=this.playingAsset,y=g==null?void 0:g.identifier,x=y?this.getAssetPlayer(y):null;if(x&&y&&(!this.eventItemsMatch(h,a)||t!==void 0&&y!==p.assetList[t].identifier)){var u;const v=p.findAssetIndex(g);if(this.log(`INTERSTITIAL_ASSET_ENDED ${v+1}/${p.assetList.length} ${es(g)}`),this.endedAsset=g,this.playingAsset=null,this.hls.trigger(E.INTERSTITIAL_ASSET_ENDED,{asset:g,assetListIndex:v,event:p,schedule:n.slice(0),scheduleIndex:e,player:x}),h!==this.playingItem){this.itemsMatch(h,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(p,this.findItemIndex(this.playingItem),v);return}this.retreiveMediaSource(y,a),x.media&&!((u=this.detachedData)!=null&&u.mediaSource)&&x.detachMedia()}if(!this.eventItemsMatch(h,a)&&(this.endedItem=h,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${p} ${_t(h)}`),p.hasPlayed=!0,this.hls.trigger(E.INTERSTITIAL_ENDED,{event:p,schedule:n.slice(0),scheduleIndex:e}),p.cue.once)){var d;this.updateSchedule();const v=(d=this.schedule)==null?void 0:d.items;if(a&&v){const _=this.findItemIndex(a);this.advanceSchedule(_,v,t,h,l)}return}}this.advanceSchedule(e,n,t,h,l)}advanceSchedule(e,t,s,n,a){const h=this.schedule;if(!h)return;const l=t[e]||null,u=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(p=>{const g=p.interstitial,y=h.findEventIndex(g.identifier);(y<e||y>e+1)&&this.clearInterstitial(g,l)}),this.isInterstitial(l)){this.timelinePos=Math.min(Math.max(this.timelinePos,l.start),l.end);const p=l.event;if(s===void 0){s=h.findAssetIndex(p,this.timelinePos);const v=ma(p,s-1);if(p.isAssetPastPlayoutLimit(v)||p.appendInPlace&&this.timelinePos===l.end){this.advanceAfterAssetEnded(p,e,s);return}s=v}const g=this.waitingItem;this.assetsBuffered(l,u)||this.setBufferingItem(l);let y=this.preloadAssets(p,s);if(this.eventItemsMatch(l,g||n)||(this.waitingItem=l,this.log(`INTERSTITIAL_STARTED ${_t(l)} ${p.appendInPlace?"append in place":""}`),this.hls.trigger(E.INTERSTITIAL_STARTED,{event:p,schedule:t.slice(0),scheduleIndex:e})),!p.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${p}`);return}if(p.assetListLoader&&(p.assetListLoader.destroy(),p.assetListLoader=void 0),!u){this.log(`Waiting for attachMedia to start Interstitial ${p}`);return}this.waitingItem=this.endedItem=null,this.playingItem=l;const x=p.assetList[s];if(!x){this.advanceAfterAssetEnded(p,e,s||0);return}if(y||(y=this.getAssetPlayer(x.identifier)),y===null||y.destroyed){const v=p.assetList.length;this.warn(`asset ${s+1}/${v} player destroyed ${p}`),y=this.createAssetPlayer(p,x,s),y.loadSource()}if(!this.eventItemsMatch(l,this.bufferingItem)&&p.appendInPlace&&this.isAssetBuffered(x))return;this.startAssetPlayer(y,s,t,e,u),this.shouldPlay&&Bh(y.media)}else l?(this.resumePrimary(l,e,n),this.shouldPlay&&Bh(this.hls.media)):a&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(h.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,s){var n,a;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${_t(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let l=this.timelinePos;(l<e.start||l>=e.end)&&(l=this.getPrimaryResumption(e,t),this.log(En("resumePrimary",l)),this.timelinePos=l),this.attachPrimary(l,e)}if(!s)return;const h=(a=this.schedule)==null?void 0:a.items;h&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${_t(e)}`),this.hls.trigger(E.INTERSTITIALS_PRIMARY_RESUMED,{schedule:h.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const n=this.primaryDetails;if(t===0)return this.hls.startPosition;if(n&&(s<n.fragmentStart||s>n.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:ae.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const n=this.primaryMedia;if(!n)return;const a=this.hls;a.media?this.checkBuffer():(this.transferMediaTo(a,n),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(En("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs((((s=n.mainForwardBufferInfo)==null?void 0:s.start)||n.media.currentTime)-e)>.5?n.startLoad(e,t):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.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(E.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(E.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const n=xe(xe({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=xe(xe({},this.altSelection),{},{audio:s});return}const a=xe(xe({},n),{},{audio:s});this.mediaSelection=a}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=xe(xe({},this.altSelection),{},{subtitles:s});return}const a=xe(xe({},n),{},{subtitles:s});this.mediaSelection=a}onAudioTrackSwitching(e,t){const s=Wl(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setAudioOption(t)||n.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Wl(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setSubtitleOption(t)||t.id!==-1&&n.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const n=this.timelinePos;this.bufferedPos=n,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let n=0;n<t.length;n++){const a=t[n];if(a.cue.post){var s;const h=this.schedule.findEventIndex(a.identifier),l=(s=this.schedule.items)==null?void 0:s[h];this.isInterstitial(l)&&this.eventItemsMatch(l,this.bufferingItem)&&this.bufferedToItem(l,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const n=(s=this.schedule)==null?void 0:s.items;if(e&&n){const a=this.findItemIndex(e,t);return n[a]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((a,h)=>{e.event.isAssetPastPlayoutLimit(h)&&this.clearAssetPlayer(a.identifier,null)});const s=e.end+.25,n=ae.bufferInfo(this.primaryMedia,s,0);(n.end>s||(n.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${_t(e)} (was ${_t(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}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 s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s)return;const n=ae.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=n.len<1),this.updateBufferedPos(n.end,s,e)}updateBufferedPos(e,t,s){const n=this.schedule,a=this.bufferingItem;if(this.bufferedPos>e||!n)return;if(t.length===1&&this.itemsMatch(t[0],a)){this.bufferedPos=e;return}const h=this.playingItem,l=this.findItemIndex(h);let u=n.findItemIndexAtTime(e);if(this.bufferedPos<e){var d;const p=this.findItemIndex(a),g=Math.min(p+1,t.length-1),y=t[g];if((u===-1&&a&&e>=a.end||(d=y.event)!=null&&d.appendInPlace&&e+.01>=y.start)&&(u=g),this.isInterstitial(a)){const x=a.event;if(g-l>1&&x.appendInPlace===!1||x.assetList.length===0&&x.assetListLoader)return}if(this.bufferedPos=e,u>p&&u>l)this.bufferedToItem(y);else{const x=this.primaryDetails;this.primaryLive&&x&&e>x.edge-x.targetduration&&y.start<x.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(y)&&this.preloadAssets(y.event,0)}}else s&&h&&!this.itemsMatch(h,a)&&(u===l?this.bufferedToItem(h):u===l+1&&this.bufferedToItem(t[u]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(n=>{const a=this.getAssetPlayer(n.identifier);return!(a!=null&&a.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:n,events:a}=s;if(!n||!a)return t;const h=this.isInterstitial(e),l=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const u=l?l.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${_t(e)}`+(t?` (${u.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(h){const d=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((p,g)=>{const y=this.getAssetPlayer(p.identifier);y&&(g===d&&y.loadSource(),y.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(E.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:a.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==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),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,n=s.assetList.length===0&&!s.assetListLoader,a=s.cue.once;if(n||!a){const h=this.preloadAssets(s,t);if(h!=null&&h.interstitial.appendInPlace){const l=this.primaryMedia;l&&this.bufferAssetPlayer(h,l)}}}preloadAssets(e,t){const s=e.assetUrl,n=e.assetList.length,a=n===0&&!e.assetListLoader,h=e.cue.once;if(a){const u=e.timelineStart;if(e.appendInPlace){var l;const y=this.playingItem;!this.isInterstitial(y)&&(y==null||(l=y.nextEvent)==null?void 0:l.identifier)===e.identifier&&this.flushFrontBuffer(u+.25)}let d,p=0;if(!this.playingItem&&this.primaryLive&&(p=this.hls.startPosition,p===-1&&(p=this.hls.liveSyncPosition||0)),p&&!(e.cue.pre||e.cue.post)){const y=p-u;y>0&&(d=Math.round(y*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:n} ${e}${d?` live-start: ${p} start-offset: ${d}`:""}`),s)return this.createAsset(e,0,0,u,e.duration,s);const g=this.assetListLoader.loadAssetList(e,d);g&&(e.assetListLoader=g)}else if(!h&&n){for(let d=t;d<n;d++){const p=e.assetList[d],g=this.getAssetPlayerQueueIndex(p.identifier);(g===-1||this.playerQueue[g].destroyed)&&!p.error&&this.createAssetPlayer(e,p,d)}const u=e.assetList[t];if(u){const d=this.getAssetPlayer(u.identifier);return d&&d.loadSource(),d}}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(E.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;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 s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,n,a,h){const l={parentIdentifier:e.identifier,identifier:yx(e,h,t),duration:a,startOffset:s,timelineStart:n,uri:h};return this.createAssetPlayer(e,l,t)}createAssetPlayer(e,t,s){const n=this.hls,a=n.userConfig;let h=a.videoPreference;const l=n.loadLevelObj||n.levels[n.currentLevel];(h||l)&&(h=Ee({},h),l.videoCodec&&(h.videoCodec=l.videoCodec),l.videoRange&&(h.allowedVideoRanges=[l.videoRange]));const u=n.audioTracks[n.audioTrack],d=n.subtitleTracks[n.subtitleTrack];let p=0;if(this.primaryLive||e.appendInPlace){const S=this.timelinePos-t.timelineStart;if(S>1){const T=t.duration;T&&S<T&&(p=S)}}const g=t.identifier,y=xe(xe({},a),{},{maxMaxBufferLength:Math.min(180,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:g,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:p,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:h,audioPreference:u||a.audioPreference,subtitlePreference:d||a.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(y.timelineOffset=t.timelineStart));const x=y.cmcd;x!=null&&x.sessionId&&x.contentId&&(y.cmcd=Ee({},x,{contentId:Us(t.uri)})),this.getAssetPlayer(g)&&this.warn(`Duplicate date range identifier ${e} and asset ${g}`);const v=new Sx(this.HlsPlayerClass,y,e,t);this.playerQueue.push(v),e.assetList[s]=t;let _=!0;const o=S=>{if(S.live){var T;const I=new Error(`Interstitials MUST be VOD assets ${e}`),L={fatal:!0,type:Z.OTHER_ERROR,details:D.INTERSTITIAL_ASSET_ITEM_ERROR,error:I},w=((T=this.schedule)==null?void 0:T.findEventIndex(e.identifier))||-1;this.handleAssetItemError(L,e,w,s,I.message);return}const b=S.edge-S.fragmentStart,A=t.duration;(_||A===null||b>A)&&(_=!1,this.log(`Interstitial asset "${g}" duration change ${A} > ${b}`),t.duration=b,this.updateSchedule())};v.on(E.LEVEL_UPDATED,(S,{details:T})=>o(T)),v.on(E.LEVEL_PTS_UPDATED,(S,{details:T})=>o(T)),v.on(E.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const c=(S,T)=>{const b=this.getAssetPlayer(g);if(b&&T.tracks){b.off(E.BUFFER_CODECS,c),b.tracks=T.tracks;const A=this.primaryMedia;this.bufferingAsset===b.assetItem&&A&&!b.media&&this.bufferAssetPlayer(b,A)}};v.on(E.BUFFER_CODECS,c);const f=()=>{var S;const T=this.getAssetPlayer(g);if(this.log(`buffered to end of asset ${T}`),!T||!this.schedule)return;const b=this.schedule.findEventIndex(e.identifier),A=(S=this.schedule.items)==null?void 0:S[b];this.isInterstitial(A)&&this.advanceAssetBuffering(A,t)};v.on(E.BUFFERED_TO_END,f);const m=S=>()=>{if(!this.getAssetPlayer(g)||!this.schedule)return;this.shouldPlay=!0;const b=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,b,S)};return v.once(E.MEDIA_ENDED,m(s)),v.once(E.PLAYOUT_LIMIT_REACHED,m(1/0)),v.on(E.ERROR,(S,T)=>{if(!this.schedule)return;const b=this.getAssetPlayer(g);if(T.details===D.BUFFER_STALLED_ERROR){if(b!=null&&b.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(T,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${T.error} ${e}`)}),v.on(E.DESTROYING,()=>{if(!this.getAssetPlayer(g)||!this.schedule)return;const T=new Error(`Asset player destroyed unexpectedly ${g}`),b={fatal:!0,type:Z.OTHER_ERROR,details:D.INTERSTITIAL_ASSET_ITEM_ERROR,error:T};this.handleAssetItemError(b,e,this.schedule.findEventIndex(e.identifier),s,T.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${es(t)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:v}),v}clearInterstitial(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)}),e.reset()}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){const n=this.playerQueue[s];this.log(`clear ${n} toSegment: ${t&&_t(t)}`),this.transferMediaFromPlayer(n,t),this.playerQueue.splice(s,1),n.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,n,a){const{interstitial:h,assetItem:l,assetId:u}=e,d=h.assetList.length,p=this.playingAsset;this.endedAsset=null,this.playingAsset=l,(!p||p.identifier!==u)&&(p&&(this.clearAssetPlayer(p.identifier,s[n]),delete p.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${es(l)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_STARTED,{asset:l,assetListIndex:t,event:h,schedule:s.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,a)}bufferAssetPlayer(e,t){var s,n;if(!this.schedule)return;const{interstitial:a,assetItem:h}=e,l=this.schedule.findEventIndex(a.identifier),u=(s=this.schedule.items)==null?void 0:s[l];if(!u)return;e.loadSource(),this.setBufferingItem(u),this.bufferingAsset=h;const d=this.getBufferingPlayer();if(d===e)return;const p=a.appendInPlace;if(p&&(d==null?void 0:d.interstitial.appendInPlace)===!1)return;const g=(d==null?void 0:d.tracks)||((n=this.detachedData)==null?void 0:n.tracks)||this.requiredTracks;if(p&&h!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(g&&!nd(g,e.tracks)){const y=new Error(`Asset ${es(h)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(g)}')`),x={fatal:!0,type:Z.OTHER_ERROR,details:D.INTERSTITIAL_ASSET_ITEM_ERROR,error:y},v=a.findAssetIndex(h);this.handleAssetItemError(x,a,l,v,y.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const n=s.currentTime,a=t.findAssetIndex(e,n),h=e.assetList[a];if(h){const l=this.getAssetPlayer(h.identifier);if(l){const u=l.currentTime||n-h.timelineStart,d=l.duration-u;if(this.warn(`Stalled at ${u} of ${u+d} in ${l} ${e} (media.currentTime: ${n})`),u&&(d/s.playbackRate<.5||l.bufferedInPlaceToEnd(s))&&l.hls){const p=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,p,a)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,n,a){if(e.details===D.BUFFER_STALLED_ERROR)return;const h=t.assetList[n]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${h&&es(h)} ${e.error}`),!this.schedule)return;const l=(h==null?void 0:h.identifier)||"",u=this.getAssetPlayerQueueIndex(l),d=this.playerQueue[u]||null,p=this.schedule.items,g=Ee({},e,{fatal:!1,errorAction:ls(!0),asset:h,assetListIndex:n,event:t,schedule:p,scheduleIndex:s,player:d});if(this.hls.trigger(E.INTERSTITIAL_ASSET_ERROR,g),!e.fatal)return;const y=this.playingAsset,x=this.bufferingAsset,v=new Error(a);if(h&&(this.clearAssetPlayer(l,null),h.error=v),!t.assetList.some(_=>!_.error))t.error=v;else for(let _=n;_<t.assetList.length;_++)this.resetAssetPlayer(t.assetList[_].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):y&&y.identifier===l?this.advanceAfterAssetEnded(t,s,n):x&&x.identifier===l&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,x)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${_t(s)} error: ${e.error}`);let n=this.timelinePos;n===-1&&(n=this.hls.startPosition);const a=this.updateItem(s,n);if(this.itemsMatch(s,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;const h=this.schedule.findItemIndexAtTime(n);this.setSchedulePosition(h)}else this.checkStart()}onAssetListLoaded(e,t){var s,n;const a=t.event,h=a.identifier,l=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(h)))return;const u=a.timelineStart,d=a.duration;let p=0;l.forEach((_,o)=>{const c=parseFloat(_.DURATION);this.createAsset(a,o,p,u+p,c,_.URI),p+=c}),a.duration=p,this.log(`Loaded asset-list with duration: ${p} (was: ${d}) ${a}`);const g=this.waitingItem,y=(g==null?void 0:g.event.identifier)===h;this.updateSchedule();const x=(n=this.bufferingItem)==null?void 0:n.event;if(y){var v;const _=this.schedule.findEventIndex(h),o=(v=this.schedule.items)==null?void 0:v[_];if(o){if(!this.playingItem&&this.timelinePos>o.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==_){a.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${a}`),this.updateSchedule(!0),this.primaryFallback(a);return}this.setBufferingItem(o)}this.setSchedulePosition(_)}else if((x==null?void 0:x.identifier)===h){const _=a.assetList[0];if(_){const o=this.getAssetPlayer(_.identifier);if(x.appendInPlace){const c=this.primaryMedia;o&&c&&this.bufferAssetPlayer(o,c)}else o&&o.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case D.ASSET_LIST_PARSING_ERROR:case D.ASSET_LIST_LOAD_ERROR:case D.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case D.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const Nh=500;class bx extends Oo{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",X.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(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=F.IDLE,this.setInterval(Nh),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:s,success:n}=t;if(this.fragContextChanged(s)||(Pe(s)&&(this.fragPrevious=s),this.state=F.IDLE),!n)return;const a=this.tracksBuffered[this.currentTrackId];if(!a)return;let h;const l=s.start;for(let d=0;d<a.length;d++)if(l>=a[d].start&&l<=a[d].end){h=a[d];break}const u=s.start+s.duration;h?h.end=u:(h={start:l,end:u},a.push(h)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:n}=t;if(s===0&&n!==Number.POSITIVE_INFINITY){const a=n-1;if(a<=0)return;t.endOffsetSubtitles=Math.max(0,a),this.tracksBuffered.forEach(h=>{for(let l=0;l<h.length;){if(h[l].end<=a){h.shift();continue}else if(h[l].start<a)h[l].start=a;else break;l++}}),this.fragmentTracker.removeFragmentsInRange(s,a,X.SUBTITLE)}}onError(e,t){const s=t.frag;(s==null?void 0:s.type)===X.SUBTITLE&&(t.details===D.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==F.STOPPED&&(this.state=F.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&ou(this.levels,t)){this.levels=t.map(s=>new Hs(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const n=new Hs(s);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,X.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.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!==F.STOPPED&&this.setInterval(Nh)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:n,levels:a}=this,{details:h,id:l}=t;if(!a){this.warn(`Subtitle tracks were reset while loading level ${l}`);return}const u=a[l];if(l>=a.length||!u)return;this.log(`Subtitle track ${l} loaded [${h.startSN},${h.endSN}]${h.lastPartSn?`[part-${h.lastPartSn}-${h.lastPartIndex}]`:""},duration:${h.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(h.live||(s=u.details)!=null&&s.live){if(h.deltaUpdateFailed)return;const g=this.mainDetails;if(!g){this.startFragRequested=!1;return}const y=g.fragments[0];if(!u.details)h.hasProgramDateTime&&g.hasProgramDateTime?(nr(h,g),d=h.fragmentStart):y&&(d=y.start,qa(h,d));else{var p;d=this.alignPlaylists(h,u.details,(p=this.levelLastLoaded)==null?void 0:p.details),d===0&&y&&(d=y.start,qa(h,d))}g&&!this.startFragRequested&&this.setStartPosition(g,d)}u.details=h,this.levelLastLoaded=u,l===n&&(this.hls.trigger(E.SUBTITLE_TRACK_UPDATED,{details:h,id:l,groupId:t.groupId}),this.tick(),h.live&&!this.fragCurrent&&this.media&&this.state===F.IDLE&&(zi(null,h.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),u.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,n=t.decryptdata,a=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&n!=null&&n.key&&n.iv&&hs(n.method)){const h=performance.now();this.decrypter.decrypt(new Uint8Array(s),n.key.buffer,n.iv.buffer,Fo(n.method)).catch(l=>{throw a.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:t}),l}).then(l=>{const u=performance.now();a.trigger(E.FRAG_DECRYPTED,{frag:t,payload:l,stats:{tstart:h,tdecrypt:u}})}).catch(l=>{this.warn(`${l.name}: ${l.message}`),this.state=F.IDLE})}}doTick(){if(!this.media){this.state=F.IDLE;return}if(this.state===F.IDLE){const{currentTrackId:e,levels:t}=this,s=t==null?void 0:t[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:n}=this,a=this.getLoadPosition(),h=ae.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],a,n.maxBufferHole),{end:l,len:u}=h,d=s.details,p=this.hls.maxBufferLength+d.levelTargetDuration;if(u>p)return;const g=d.fragments,y=g.length,x=d.edge;let v=null;const _=this.fragPrevious;if(l<x){const f=n.maxFragLookUpTolerance,m=l>x-f?0:f;v=zi(_,g,Math.max(g[0].start,l),m),!v&&_&&_.start<g[0].start&&(v=g[0])}else v=g[y-1];if(v=this.filterReplacedPrimary(v,s.details),!v)return;const o=v.sn-d.startSN,c=g[o-1];if(c&&c.cc===v.cc&&this.fragmentTracker.getState(c)===Fe.NOT_LOADED&&(v=c),this.fragmentTracker.getState(v)===Fe.NOT_LOADED){const f=this.mapToInitFragWhenRequired(v);f&&this.loadFragment(f,s,l)}}}loadFragment(e,t,s){Pe(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Ax(this.tracksBuffered[this.currentTrackId]||[])}}class Ax{constructor(e){this.buffered=void 0;const t=(s,n,a)=>{if(n=n>>>0,n>a-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${a})`);return e[n][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}const Ix={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},Tu=r=>String.fromCharCode(Ix[r]||r),Et=15,Yt=100,wx={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Lx={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Rx={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Cx={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Px=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Dx{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;_e.log(`${this.time} [${e}] ${s}`)}}}const Pi=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class bu{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 s=0;s<t.length;s++){const n=t[s];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 kx{constructor(){this.uchar=" ",this.penState=new bu}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 Mx{constructor(e){this.chars=[],this.pos=0,this.currPenState=new bu,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Yt;t++)this.chars.push(new kx);this.logger=e}equals(e){for(let t=0;t<Yt;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Yt;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Yt;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>Yt&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Yt)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].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=Tu(e);if(this.pos>=Yt){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<Yt;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 s=0;s<Yt;s++){const n=this.chars[s].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 ya{constructor(e){this.rows=[],this.currRow=Et-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Et;t++)this.rows.push(new Mx(e));this.logger=e}reset(){for(let e=0;e<Et;e++)this.rows[e].clear();this.currRow=Et-1}equals(e){let t=!0;for(let s=0;s<Et;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<Et;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Et;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 = "+be(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let l=0;l<Et;l++)this.rows[l].clear();const a=this.currRow+1-this.nrRollUpRows,h=this.lastOutputScreen;if(h){const l=h.rows[a].cueStartTime,u=this.logger.time;if(l!==null&&u!==null&&l<u)for(let d=0;d<this.nrRollUpRows;d++)this.rows[t-this.nrRollUpRows+d+1].copy(h.rows[a+d])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const a=e.indent,h=Math.max(a-1,0);s.setCursor(e.indent),e.color=s.chars[h].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 = "+be(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 s="",n=-1;for(let a=0;a<Et;a++){const h=this.rows[a].getTextString();h&&(n=a+1,e?t.push("Row "+n+": '"+h+"'"):t.push(h.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
|
|
134
|
+
`)),s}getTextAndFormat(){return this.rows}}class $h{constructor(e,t,s){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 ya(s),this.nonDisplayedMemory=new ya(s),this.lastOutputScreen=new ya(s),this.currRollUpRow=this.displayedMemory.rows[Et-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Et-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 s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);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 s=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[s]}this.logger.log(2,"MIDROW: "+be(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 Gh{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Ux(),this.logger=void 0;const n=this.logger=new Dx;this.channels=[null,new $h(e,t,n),new $h(e+1,s,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 s=0;s<t.length;s+=2){const n=t[s]&127,a=t[s+1]&127;let h=!1,l=null;if(n===0&&a===0)continue;this.logger.log(3,()=>"["+Pi([t[s],t[s+1]])+"] -> ("+Pi([n,a])+")");const u=this.cmdHistory;if(n>=16&&n<=31){if(Fx(n,a,u)){Tn(null,null,u),this.logger.log(3,()=>"Repeated command ("+Pi([n,a])+") is dropped");continue}Tn(n,a,this.cmdHistory),h=this.parseCmd(n,a),h||(h=this.parseMidrow(n,a)),h||(h=this.parsePAC(n,a)),h||(h=this.parseBackgroundAttributes(n,a))}else Tn(null,null,u);if(!h&&(l=this.parseChars(n,a),l)){const p=this.currentChannel;p&&p>0?this.channels[p].insertChars(l):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!h&&!l&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Pi([n,a])+" orig: "+Pi([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(s||n))return!1;const a=e===20||e===21||e===23?1:2,h=this.channels[a];return e===20||e===21||e===28||e===29?t===32?h.ccRCL():t===33?h.ccBS():t===34?h.ccAOF():t===35?h.ccAON():t===36?h.ccDER():t===37?h.ccRU(2):t===38?h.ccRU(3):t===39?h.ccRU(4):t===40?h.ccFON():t===41?h.ccRDC():t===42?h.ccTR():t===43?h.ccRTD():t===44?h.ccEDM():t===45?h.ccCR():t===46?h.ccENM():t===47&&h.ccEOC():h.ccTO(t-32),this.currentChannel=a,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[s];return n?(n.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Pi([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const n=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,a=(e===16||e===24)&&t>=64&&t<=95;if(!(n||a))return!1;const h=e<=23?1:2;t>=64&&t<=95?s=h===1?wx[e]:Rx[e]:s=h===1?Lx[e]:Cx[e];const l=this.channels[h];return l?(l.setPAC(this.interpretPAC(s,t)),this.currentChannel=h,!0):!1}interpretPAC(e,t){let s;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,n.underline=(s&1)===1,s<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(n.italics=!0,n.color="white"):n.indent=Math.floor((s-16)/2)*4,n}parseChars(e,t){let s,n=null,a=null;if(e>=25?(s=2,a=e-8):(s=1,a=e),a>=17&&a<=19){let h;a===17?h=t+80:a===18?h=t+112:h=t+144,this.logger.log(2,()=>"Special char '"+Tu(h)+"' in channel "+s),n=[h]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+Pi(n).join(",")),n}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=45&&t<=47;if(!(s||n))return!1;let a;const h={};e===16||e===24?(a=Math.floor((t-32)/2),h.background=Px[a],t%2===1&&(h.background=h.background+"_semi")):t===45?h.background="transparent":(h.foreground="black",t===47&&(h.underline=!0));const l=e<=23?1:2;return this.channels[l].setBkgData(h),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Tn(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function Tn(r,e,t){t.a=r,t.b=e}function Fx(r,e,t){return t.a===r&&t.b===e}function Ux(){return{a:null,b:null}}var qo=function(){if(sr!=null&&sr.VTTCue)return self.VTTCue;const r=["","lr","rl"],e=["start","middle","end","left","right"];function t(l,u){if(typeof u!="string"||!Array.isArray(l))return!1;const d=u.toLowerCase();return~l.indexOf(d)?d:!1}function s(l){return t(r,l)}function n(l){return t(e,l)}function a(l,...u){let d=1;for(;d<arguments.length;d++){const p=arguments[d];for(const g in p)l[g]=p[g]}return l}function h(l,u,d){const p=this,g={enumerable:!0};p.hasBeenReset=!1;let y="",x=!1,v=l,_=u,o=d,c=null,f="",m=!0,S="auto",T="start",b=50,A="middle",I=50,L="middle";Object.defineProperty(p,"id",a({},g,{get:function(){return y},set:function(w){y=""+w}})),Object.defineProperty(p,"pauseOnExit",a({},g,{get:function(){return x},set:function(w){x=!!w}})),Object.defineProperty(p,"startTime",a({},g,{get:function(){return v},set:function(w){if(typeof w!="number")throw new TypeError("Start time must be set to a number.");v=w,this.hasBeenReset=!0}})),Object.defineProperty(p,"endTime",a({},g,{get:function(){return _},set:function(w){if(typeof w!="number")throw new TypeError("End time must be set to a number.");_=w,this.hasBeenReset=!0}})),Object.defineProperty(p,"text",a({},g,{get:function(){return o},set:function(w){o=""+w,this.hasBeenReset=!0}})),Object.defineProperty(p,"region",a({},g,{get:function(){return c},set:function(w){c=w,this.hasBeenReset=!0}})),Object.defineProperty(p,"vertical",a({},g,{get:function(){return f},set:function(w){const R=s(w);if(R===!1)throw new SyntaxError("An invalid or illegal string was specified.");f=R,this.hasBeenReset=!0}})),Object.defineProperty(p,"snapToLines",a({},g,{get:function(){return m},set:function(w){m=!!w,this.hasBeenReset=!0}})),Object.defineProperty(p,"line",a({},g,{get:function(){return S},set:function(w){if(typeof w!="number"&&w!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=w,this.hasBeenReset=!0}})),Object.defineProperty(p,"lineAlign",a({},g,{get:function(){return T},set:function(w){const R=n(w);if(!R)throw new SyntaxError("An invalid or illegal string was specified.");T=R,this.hasBeenReset=!0}})),Object.defineProperty(p,"position",a({},g,{get:function(){return b},set:function(w){if(w<0||w>100)throw new Error("Position must be between 0 and 100.");b=w,this.hasBeenReset=!0}})),Object.defineProperty(p,"positionAlign",a({},g,{get:function(){return A},set:function(w){const R=n(w);if(!R)throw new SyntaxError("An invalid or illegal string was specified.");A=R,this.hasBeenReset=!0}})),Object.defineProperty(p,"size",a({},g,{get:function(){return I},set:function(w){if(w<0||w>100)throw new Error("Size must be between 0 and 100.");I=w,this.hasBeenReset=!0}})),Object.defineProperty(p,"align",a({},g,{get:function(){return L},set:function(w){const R=n(w);if(!R)throw new SyntaxError("An invalid or illegal string was specified.");L=R,this.hasBeenReset=!0}})),p.displayState=void 0}return h.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},h}();class Ox{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Au(r){function e(s,n,a,h){return(s|0)*3600+(n|0)*60+(a|0)+parseFloat(h||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 Bx{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let n=0;n<s.length;++n)if(t===s[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 s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function Iu(r,e,t,s){const n=s?r.split(s):[r];for(const a in n){if(typeof n[a]!="string")continue;const h=n[a].split(t);if(h.length!==2)continue;const l=h[0],u=h[1];e(l,u)}}const so=new qo(0,0,""),bn=so.align==="middle"?"middle":"center";function Nx(r,e,t){const s=r;function n(){const l=Au(r);if(l===null)throw new Error("Malformed timestamp: "+s);return r=r.replace(/^[^\sa-zA-Z-]+/,""),l}function a(l,u){const d=new Bx;Iu(l,function(y,x){let v;switch(y){case"region":for(let _=t.length-1;_>=0;_--)if(t[_].id===x){d.set(y,t[_].region);break}break;case"vertical":d.alt(y,x,["rl","lr"]);break;case"line":v=x.split(","),d.integer(y,v[0]),d.percent(y,v[0])&&d.set("snapToLines",!1),d.alt(y,v[0],["auto"]),v.length===2&&d.alt("lineAlign",v[1],["start",bn,"end"]);break;case"position":v=x.split(","),d.percent(y,v[0]),v.length===2&&d.alt("positionAlign",v[1],["start",bn,"end","line-left","line-right","auto"]);break;case"size":d.percent(y,x);break;case"align":d.alt(y,x,["start",bn,"end","left","right"]);break}},/:/,/\s/),u.region=d.get("region",null),u.vertical=d.get("vertical","");let p=d.get("line","auto");p==="auto"&&so.line===-1&&(p=-1),u.line=p,u.lineAlign=d.get("lineAlign","start"),u.snapToLines=d.get("snapToLines",!0),u.size=d.get("size",100),u.align=d.get("align",bn);let g=d.get("position","auto");g==="auto"&&so.position===50&&(g=u.align==="start"||u.align==="left"?0:u.align==="end"||u.align==="right"?100:50),u.position=g}function h(){r=r.replace(/^\s+/,"")}if(h(),e.startTime=n(),h(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);r=r.slice(3),h(),e.endTime=n(),h(),a(r,e)}function wu(r){return r.replace(/<br(?: \/)?>/gi,`
|
|
135
|
+
`)}class $x{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Ox,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function s(){let a=t.buffer,h=0;for(a=wu(a);h<a.length&&a[h]!=="\r"&&a[h]!==`
|
|
136
136
|
`;)++h;const l=a.slice(0,h);return a[h]==="\r"&&++h,a[h]===`
|
|
137
|
-
`&&++h,t.buffer=a.slice(h),l}function n(a){
|
|
137
|
+
`&&++h,t.buffer=a.slice(h),l}function n(a){Iu(a,function(h,l){},/:/)}try{let a="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;a=s();const l=a.match(/^()?WEBVTT([ \t].*)?$/);if(!(l!=null&&l[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let h=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(h?h=!1:a=s(),t.state){case"HEADER":/:/.test(a)?n(a):a||(t.state="ID");continue;case"NOTE":a||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(a)){t.state="NOTE";break}if(!a)continue;if(t.cue=new qo(0,0,""),t.state="CUE",a.indexOf("-->")===-1){t.cue.id=a;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Nx(a,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const l=a.indexOf("-->")!==-1;if(!a||l&&(h=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
|
|
138
138
|
`),t.cue.text+=a}continue;case"BADCUE":a||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
|
|
139
139
|
|
|
140
|
-
`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const
|
|
140
|
+
`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const Gx=/\r\n|\n\r|\n|\r/g,va=function(e,t,s=0){return e.slice(s,s+t.length)===t},zx=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),n=parseInt(e.slice(-9,-7)),a=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!q(t)||!q(s)||!q(n)||!q(a))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*n,t+=60*60*1e3*a,t};function Xo(r,e,t){return Us(r.toString())+Us(e.toString())+Us(t)}const Hx=function(e,t,s){let n=e[t],a=e[n.prevCC];if(!a||!a.new&&n.new){e.ccOffset=e.presentationOffset=n.start,n.new=!1;return}for(;(h=a)!=null&&h.new;){var h;e.ccOffset+=n.start-a.start,n.new=!1,n=a,a=e[n.prevCC]}e.presentationOffset=s};function Vx(r,e,t,s,n,a,h){const l=new $x,u=dt(new Uint8Array(r)).trim().replace(Gx,`
|
|
141
141
|
`).split(`
|
|
142
|
-
`),d=[],p=e?
|
|
143
|
-
`)}),l.flush()}const
|
|
144
|
-
`:(a=s.childNodes)!=null&&a.length?su(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function ov(r,e,t){const s="http://www.w3.org/ns/ttml#styling";let n=null;const a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],h=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return h&&t.hasOwnProperty(h)&&(n=t[h]),a.reduce((l,u)=>{const d=da(e,s,u)||da(r,s,u)||da(n,s,u);return d&&(l[u]=d),l},{})}function da(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function Ih(r){return new Error(`Could not parse ttml timestamp ${r}`)}function ua(r,e){if(!r)return null;let t=Zd(r);return t===null&&(tu.test(r)?t=lv(r,e):iu.test(r)&&(t=hv(r,e))),t}function lv(r,e){const t=tu.exec(r),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function hv(r,e){const t=iu.exec(r),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}class gn{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class cv{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Lh(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(_.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(_.FRAG_LOADING,this.onFragLoading,this),e.on(_.FRAG_LOADED,this.onFragLoaded,this),e.on(_.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(_.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(_.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(_.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(_.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(_.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(_.FRAG_LOADING,this.onFragLoading,this),e.off(_.FRAG_LOADED,this.onFragLoaded,this),e.off(_.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(_.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(_.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(_.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(_.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new gn(this,"textTrack1"),t=new gn(this,"textTrack2"),s=new gn(this,"textTrack3"),n=new gn(this,"textTrack4");this.cea608Parser1=new Th(1,e,t),this.cea608Parser2=new Th(3,s,n)}addCues(e,t,s,n,a){let h=!1;for(let l=a.length;l--;){const u=a[l],d=dv(u[0],u[1],t,s);if(d>=0&&(u[0]=Math.min(u[0],t),u[1]=Math.max(u[1],s),h=!0,d/(s-t)>.5))return}if(h||a.push([t,s]),this.config.renderTextTracksNatively){const l=this.captionsTracks[e];this.Cues.newCue(l,t,s,n)}else{const l=this.Cues.newCue(null,t,s,n);this.hls.trigger(_.CUES_PARSED,{type:"captions",cues:l,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:n,timescale:a}){const{unparsedVttFrags:h}=this;s===X.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:a}),h.length&&(this.unparsedVttFrags=[],h.forEach(l=>{this.onFragLoaded(_.FRAG_LOADED,l)}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let n=0;n<s.textTracks.length;n++){const a=s.textTracks[n];if(wh(a,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return a}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:n}=this,{label:a,languageCode:h}=t[e],l=this.getExistingTrack(a,h);if(l)s[e]=l,Wi(s[e]),Wd(s[e],n);else{const u=this.createTextTrack("captions",a,h);u&&(u[e]=!0,s[e]=u)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,n={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(_.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}createTextTrack(e,t,s){const n=this.media;if(n)return n.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:n}=this;Object.keys(n).forEach(a=>{Wi(n[a]),delete n[a]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Lh(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let s=0;s<t.length;s++)Wi(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],n=s.some(a=>a.textCodec===ha);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if($d(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const h=this.media,l=h?Rn(h.textTracks):null;if(this.tracks.forEach((u,d)=>{let p;if(l){let g=null;for(let y=0;y<l.length;y++)if(l[y]&&wh(l[y],u)){g=l[y],l[y]=null;break}g&&(p=g)}if(p)Wi(p);else{const g=nu(u);p=this.createTextTrack(g,u.name,u.lang),p&&(p.mode="disabled")}p&&this.textTracks.push(p)}),l!=null&&l.length){const u=l.filter(d=>d!==null).map(d=>d.label);u.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${u.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const h=this.tracks.map(l=>({label:l.name,kind:l.type.toLowerCase(),default:l.default,subtitleTrack:l}));this.hls.trigger(_.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:h})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const n=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!n)return;const a=`textTrack${n[1]}`,h=this.captionsProperties[a];h&&(h.label=s.name,s.lang&&(h.languageCode=s.lang),h.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===X.MAIN){var s,n;const{cea608Parser1:a,cea608Parser2:h,lastSn:l}=this,{cc:u,sn:d}=t.frag,p=(s=(n=t.part)==null?void 0:n.index)!=null?s:-1;a&&h&&(d!==l+1||d===l&&p!==this.lastPartIndex+1||u!==this.lastCc)&&(a.reset(),h.reset()),this.lastCc=u,this.lastSn=d,this.lastPartIndex=p}}onFragLoaded(e,t){const{frag:s,payload:n}=t;if(s.type===X.SUBTITLE)if(n.byteLength){const a=s.decryptdata,h="stats"in t;if(a==null||!a.encrypted||h){const l=this.tracks[s.level],u=this.vttCCs;u[s.cc]||(u[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),l&&l.textCodec===ha?this._parseIMSC1(s,n):this._parseVTTs(t)}}else this.hls.trigger(_.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;bh(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),s.trigger(_.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{s.logger.log(`Failed to parse IMSC1: ${n}`),s.trigger(_.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:s,payload:n}=e,{initPTS:a,unparsedVttFrags:h}=this,l=a.length-1;if(!a[s.cc]&&l===-1){h.push(e);return}const u=this.hls,d=(t=s.initSegment)!=null&&t.data?ct(s.initSegment.data,new Uint8Array(n)).buffer:n;nv(d,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,p=>{this._appendCues(p,s.level),u.trigger(_.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},p=>{const g=p.message==="Missing initPTS for VTT MPEGTS";g?h.push(e):this._fallbackToIMSC1(s,n),u.logger.log(`Failed to parse VTT cue: ${p}`),!(g&&l>s.cc)&&u.trigger(_.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:p})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||bh(t,this.initPTS[e.cc],()=>{s.textCodec=ha,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||n.mode==="disabled")return;e.forEach(a=>jd(n,a))}else{const n=this.tracks[t];if(!n)return;const a=n.default?"default":"subtitles"+t;s.trigger(_.CUES_PARSED,{type:"subtitles",cues:e,track:a})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===X.SUBTITLE&&this.onFragLoaded(_.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:n}=t;if(!(s.type===X.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let a=0;a<n.length;a++){const h=n[a].bytes;if(h){this.cea608Parser1||this.initCea608Parsers();const l=this.extractCea608Data(h);this.cea608Parser1.addData(n[a].pts,l[0]),this.cea608Parser2.addData(n[a].pts,l[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:n,type:a}){const{media:h}=this;if(!(!h||h.currentTime<s)){if(!a||a==="video"){const{captionsTracks:l}=this;Object.keys(l).forEach(u=>za(l[u],t,s))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:l}=this;Object.keys(l).forEach(u=>za(l[u],t,n))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let n=2;for(let a=0;a<s;a++){const h=e[n++],l=127&e[n++],u=127&e[n++];if(l===0&&u===0)continue;if((4&h)!==0){const p=3&h;(p===0||p===1)&&(t[p].push(l),t[p].push(u))}}return t}}function nu(r){return r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function wh(r,e){return!!r&&r.kind===nu(e)&&Na(e,r)}function dv(r,e,t,s){return Math.min(e,s)-Math.max(r,t)}function Lh(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const uv=/\s/,fv={newCue(r,e,t,s){const n=[];let a,h,l,u,d;const p=self.VTTCue||self.TextTrackCue;for(let y=0;y<s.rows.length;y++)if(a=s.rows[y],l=!0,u=0,d="",!a.isEmpty()){var g;for(let E=0;E<a.chars.length;E++)uv.test(a.chars[E].uchar)&&l?u++:(d+=a.chars[E].uchar,l=!1);a.cueStartTime=e,e===t&&(t+=1e-4),u>=16?u--:u++;const v=eu(d.trim()),x=Fo(e,t,v);r!=null&&(g=r.cues)!=null&&g.getCueById(x)||(h=new p(e,t,v),h.id=x,h.line=y+1,h.align="left",h.position=10+Math.min(80,Math.floor(u*8/32)*10),n.push(h))}return r&&n.length&&(n.sort((y,v)=>y.line==="auto"||v.line==="auto"?0:y.line>8&&v.line>8?v.line-y.line:y.line-v.line),n.forEach(y=>jd(r,y))),n}};function pv(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const gv=/(\d+)-(\d+)\/(\d+)/;class Rh{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||vv,this.controller=new self.AbortController,this.stats=new go}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const a=mv(e,this.controller.signal),h=e.responseType==="arraybuffer",l=h?"byteLength":"length",{maxTimeToFirstByteMs:u,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,a),self.clearTimeout(this.requestTimeout),t.timeout=u&&K(u)?u:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(Os(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(g=>{var y;this.response=this.loader=g;const v=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},d-(v-n.loading.start)),!g.ok){const{status:E,statusText:o}=g;throw new Sv(o||"fetch, bad network response",E,g)}n.loading.first=v,n.total=xv(g.headers)||n.total;const x=(y=this.callbacks)==null?void 0:y.onProgress;return x&&K(t.highWaterMark)?this.loadProgressively(g,n,e,t.highWaterMark,x):h?g.arrayBuffer():e.responseType==="json"?g.json():g.text()}).then(g=>{var y,v;const x=this.response;if(!x)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const E=g[l];E&&(n.loaded=n.total=E);const o={url:x.url,data:g,code:x.status},c=(y=this.callbacks)==null?void 0:y.onProgress;c&&!K(t.highWaterMark)&&c(n,e,g,x),(v=this.callbacks)==null||v.onSuccess(o,n,e,x)}).catch(g=>{var y;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const v=g&&g.code||0,x=g?g.message:null;(y=this.callbacks)==null||y.onError({code:v,text:x},e,g?g.details:null,n)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,n=0,a){const h=new vd,l=e.body.getReader(),u=()=>l.read().then(d=>{if(d.done)return h.dataLength&&a(t,s,h.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const p=d.value,g=p.length;return t.loaded+=g,g<n||h.dataLength?(h.push(p),h.dataLength>=n&&a(t,s,h.flush().buffer,e)):a(t,s,p.buffer,e),u()}).catch(()=>Promise.reject());return u()}}function mv(r,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Te({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function yv(r){const e=gv.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function xv(r){const e=r.get("Content-Range");if(e){const s=yv(e);if(K(s))return s}const t=r.get("Content-Length");if(t)return parseInt(t)}function vv(r,e){return new self.Request(r.url,e)}class Sv extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const _v=/^age:\s*[\d.]+\s*$/im;class ru{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new go,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const a=this.xhrSetup;a?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return a(s,t.url)}).catch(h=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),a(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(h=>{var l;(l=this.callbacks)==null||l.onError({code:s.status,text:h.message},t,s,n)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const n=t.headers,{maxTimeToFirstByteMs:a,maxLoadTimeMs:h}=s.loadPolicy;if(n)for(const l in n)e.setRequestHeader(l,n[l]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=a&&K(a)?a:h,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const n=t.readyState,a=this.config;if(!s.aborted&&n>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),a.timeout!==a.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),a.timeout=a.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),a.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),n===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const d=t.status,p=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){const x=p??t.response;if(x!=null){var h,l;s.loading.end=Math.max(self.performance.now(),s.loading.first);const E=t.responseType==="arraybuffer"?x.byteLength:x.length;s.loaded=s.total=E,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const o=(h=this.callbacks)==null?void 0:h.onProgress;o&&o(s,e,x,t);const c={url:t.responseURL,data:x,code:d};(l=this.callbacks)==null||l.onSuccess(c,s,e,t);return}}const g=a.loadPolicy.errorRetry,y=s.retry,v={url:e.url,data:void 0,code:d};if(Kn(g,y,!1,v))this.retry(g);else{var u;pe.error(`${d} while loading ${e.url}`),(u=this.callbacks)==null||u.onError({code:d,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Kn(e,t,!0))this.retry(e);else{var s;pe.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=xo(e,s.retry),s.retry++,pe.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&_v.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const Ev={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Tv=xe(xe({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:ru,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:K0,bufferController:Oy,capLevelController:Po,errorController:Q0,fpsController:wx,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:ld,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,certLoadPolicy:{default:Ev},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},bv()),{},{subtitleStreamController:Bx,subtitleTrackController:Cx,timelineController:cv,audioStreamController:ky,audioTrackController:My,emeController:Ji,cmcdController:bx,contentSteeringController:Ix,interstitialsController:Ox});function bv(){return{cueHandler:fv,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Av(r,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=Ka(r),n=["manifest","level","frag"],a=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(h=>{const l=`${h==="level"?"playlist":h}LoadPolicy`,u=e[l]===void 0,d=[];a.forEach(p=>{const g=`${h}Loading${p}`,y=e[g];if(y!==void 0&&u){d.push(g);const v=s[l].default;switch(e[l]={default:v},p){case"TimeOut":v.maxLoadTimeMs=y,v.maxTimeToFirstByteMs=y;break;case"MaxRetry":v.errorRetry.maxNumRetry=y,v.timeoutRetry.maxNumRetry=y;break;case"RetryDelay":v.errorRetry.retryDelayMs=y,v.timeoutRetry.retryDelayMs=y;break;case"MaxRetryTimeout":v.errorRetry.maxRetryDelayMs=y,v.timeoutRetry.maxRetryDelayMs=y;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${l}": ${Ae(e[l])}`)}),xe(xe({},s),e)}function Ka(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(Ka):Object.keys(r).reduce((e,t)=>(e[t]=Ka(r[t]),e),{}):r}function Iv(r,e){const t=r.loader;t!==Rh&&t!==ru?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):pv()&&(r.loader=Rh,r.progressive=!0,r.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Cn=2,wv=.1,Lv=.05,Rv=100;class Cv extends rd{constructor(e,t){super("gap-controller",e.logger),this.hls=null,this.fragmentTracker=null,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(_.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(_.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(_.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(Rv),this.mediaSource=t.mediaSource;const s=this.media=t.media;Yt(s,"playing",this.onMediaPlaying),Yt(s,"waiting",this.onMediaWaiting),Yt(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(Rt(s,"playing",this.onMediaPlaying),Rt(s,"waiting",this.onMediaWaiting),Rt(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,n;const a=(s=this.hls)==null?void 0:s.config;if(!a)return;const{media:h,stalled:l}=this;if(!h)return;const{seeking:u}=h,d=this.seeking&&!u,p=!this.seeking&&u,g=h.paused&&!u||h.ended||h.playbackRate===0;if(this.seeking=u,e!==t){t&&(this.ended=0),this.moved=!0,u||(this.nudgeRetry=0,a.nudgeOnVideoHole&&!g&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(p||d){d&&this.stallResolved(e);return}if(g){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&h.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(_.MEDIA_ENDED,{stalled:!1}));return}if(!ce.getBuffered(h).length){this.nudgeRetry=0;return}const y=ce.bufferInfo(h,e,0),v=y.nextStart||0,x=this.fragmentTracker;if(u&&x&&this.hls){const b=Ch(this.hls.inFlightFragments,e),A=y.len>Cn,I=!v||b||v-e>Cn&&!x.getPartialFragment(e);if(A||I)return;this.moved=!1}const E=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&x){if(!(y.len>0)&&!v)return;const A=Math.max(v,y.start||0)-e,L=!!(E!=null&&E.live)?E.targetduration*2:Cn,w=x.getPartialFragment(e);if(A>0&&(A<=L||w)){h.paused||this._trySkipBufferHole(w);return}}const o=a.detectStallWithCurrentTimeMs,c=self.performance.now(),f=this.waiting;if(l===null){f>0&&c-f<o?this.stalled=f:this.stalled=c;return}const m=c-l;if(!u&&(m>=o||f)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(E!=null&&E.live)&&Math.abs(e-((E==null?void 0:E.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(_.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(y),!this.media||!this.hls)return}const T=ce.bufferInfo(h,e,a.maxBufferHole);this._tryFixBufferStall(T,m)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(_.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&n&&n.length>1&&e>n.end(0)){const a=ce.bufferedInfo(ce.timeRangesToArray(this.buffered.audio),e,0);if(a.len>1&&t>=a.start){const h=ce.timeRangesToArray(n),l=ce.bufferedInfo(h,t,0).bufferedIndex;if(l>-1&&l<h.length-1){const u=ce.bufferedInfo(h,e,0).bufferedIndex,d=h[l].end,p=h[l+1].start;if((u===-1||u>l)&&p-d<1&&e-d<2){const g=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${p} buffered index: ${u}`);this.warn(g.message),this.media.currentTime+=1e-6;const y=this.fragmentTracker.getPartialFragment(e)||void 0,v=ce.bufferInfo(this.media,e,0);this.hls.trigger(_.ERROR,{type:Q.MEDIA_ERROR,details:P.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:g,reason:g.message,frag:y,buffer:v.len,bufferInfo:v})}}}}}_tryFixBufferStall(e,t){var s,n;const{fragmentTracker:a,media:h}=this,l=(s=this.hls)==null?void 0:s.config;if(!h||!a||!l)return;const u=h.currentTime,d=(n=this.hls)==null?void 0:n.latestLevelDetails,p=a.getPartialFragment(u);if((p||d!=null&&d.live&&u<d.fragmentStart)&&(this._trySkipBufferHole(p)||!this.media))return;const g=e.buffered;(g&&g.length>1&&e.len>l.maxBufferHole||e.nextStart&&e.nextStart-u<l.maxBufferHole)&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}_reportStall(e){const{hls:t,media:s,stallReported:n,stalled:a}=this;if(!n&&a!==null&&s&&t){this.stallReported=!0;const h=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${Ae(e)})`);this.warn(h.message),t.trigger(_.ERROR,{type:Q.MEDIA_ERROR,details:P.BUFFER_STALLED_ERROR,fatal:!1,error:h,buffer:e.len,bufferInfo:e,stalled:{start:a}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:n}=this,a=(t=this.hls)==null?void 0:t.config;if(!n||!s||!a)return 0;const h=n.currentTime,l=ce.bufferInfo(n,h,0),u=h<l.start?l.start:l.nextStart;if(u&&this.hls){const p=l.len<=a.maxBufferHole,g=l.len>0&&l.len<1&&n.readyState<3,y=u-h;if(y>0&&(p||g)){if(y>a.maxBufferHole){let x=!1;if(h===0){const E=s.getAppendedFrag(0,X.MAIN);E&&u<E.end&&(x=!0)}if(!x){const E=e||s.getAppendedFrag(h,X.MAIN);if(E){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||Ch(this.hls.inFlightFragments,u))return 0;let c=!1,f=E.end;for(;f<u;){const m=s.getPartialFragment(f);if(m)f+=m.duration;else{c=!0;break}}if(c)return 0}}}const v=Math.max(u+Lv,h+wv);if(this.warn(`skipping hole, adjusting currentTime from ${h} to ${v}`),this.moved=!0,n.currentTime=v,!(e!=null&&e.gap)){const x=new Error(`fragment loaded with buffer holes, seeking from ${h} to ${v}`);this.hls.trigger(_.ERROR,{type:Q.MEDIA_ERROR,details:P.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:x,reason:x.message,frag:e||void 0,buffer:l.len,bufferInfo:l})}return v}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:n}=this,a=t==null?void 0:t.config;if(!s||!a)return 0;const h=s.currentTime;if(this.nudgeRetry++,n<a.nudgeMaxRetry){const l=h+(n+1)*a.nudgeOffset,u=new Error(`Nudging 'currentTime' from ${h} to ${l}`);this.warn(u.message),s.currentTime=l,t.trigger(_.ERROR,{type:Q.MEDIA_ERROR,details:P.BUFFER_NUDGE_ON_STALL,error:u,fatal:!1,buffer:e.len,bufferInfo:e})}else{const l=new Error(`Playhead still not moving while enough data buffered @${h} after ${a.nudgeMaxRetry} nudges`);this.error(l.message),t.trigger(_.ERROR,{type:Q.MEDIA_ERROR,details:P.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Ch(r,e){const t=Dh(r.main);if(t&&t.start<=e)return t;const s=Dh(r.audio);return s&&s.start<=e?s:null}function Dh(r){if(!r)return null;switch(r.state){case M.IDLE:case M.STOPPED:case M.ENDED:case M.ERROR:return null}return r.frag}const Dv=.25;function Ya(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Ph(r,e,t,s,n){let a=new r(e,t,"");try{a.value=s,n&&(a.type=n)}catch{a=new r(e,t,Ae(n?xe({type:n},s):s))}return a}const mn=(()=>{const r=Ya();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Pv(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class kv{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(_.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e.on(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(_.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(_.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(_.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(_.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(_.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(_.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){const e=this.hls.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Wi(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return Wd(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:s,enableID3MetadataCues:n}}}=this;if(!s&&!n)return;const{samples:a}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const h=Ya();if(h)for(let l=0;l<a.length;l++){const u=a[l].type;if(u===it.emsg&&!s||!n)continue;const d=wd(a[l].data);if(d){const p=a[l].pts;let g=p+a[l].duration;g>mn&&(g=mn),g-p<=0&&(g=p+Dv);for(let v=0;v<d.length;v++){const x=d[v];if(!Ld(x)){this.updateId3CueEnds(p,u);const E=Ph(h,p,g,x,u);E&&this.id3Track.addCue(E)}}}}}updateId3CueEnds(e,t){var s;const n=(s=this.id3Track)==null?void 0:s.cues;if(n)for(let a=n.length;a--;){const h=n[a];h.type===t&&h.startTime<e&&h.endTime===mn&&(h.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:n}){const{id3Track:a,hls:h}=this;if(!h)return;const{config:{enableEmsgMetadataCues:l,enableID3MetadataCues:u}}=h;if(a&&(l||u)){let d;n==="audio"?d=p=>p.type===it.audioId3&&u:n==="video"?d=p=>p.type===it.emsg&&l:d=p=>p.type===it.audioId3&&u||p.type===it.emsg&&l,za(a,t,s,d)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{id3Track:s}=this,{dateRanges:n}=e,a=Object.keys(n);let h=this.dateRangeCuesAppended;if(s&&t){var l;if((l=s.cues)!=null&&l.length){const p=Object.keys(h).filter(g=>!a.includes(g));for(let g=p.length;g--;){const y=p[g],v=h[y].cues;delete h[y],Object.keys(v).forEach(x=>{try{const E=v[x];E.removeEventListener("enter",this.onEventCueEnter),s.removeCue(E)}catch{}})}}else h=this.dateRangeCuesAppended={}}const u=e.fragments[e.fragments.length-1];if(a.length===0||!K(u==null?void 0:u.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const d=Ya();for(let p=0;p<a.length;p++){const g=a[p],y=n[g],v=y.startTime,x=h[g],E=(x==null?void 0:x.cues)||{};let o=(x==null?void 0:x.durationKnown)||!1,c=mn;const{duration:f,endDate:m}=y;if(m&&f!==null)c=v+f,o=!0;else if(y.endOnNext&&!o){const T=a.reduce((b,A)=>{if(A!==y.id){const I=n[A];if(I.class===y.class&&I.startDate>y.startDate&&(!b||y.startDate<b.startDate))return I}return b},null);T&&(c=T.startTime,o=!0)}const S=Object.keys(y.attr);for(let T=0;T<S.length;T++){const b=S[T];if(!cm(b))continue;const A=E[b];if(A)o&&!x.durationKnown?A.endTime=c:Math.abs(A.startTime-v)>.01&&(A.startTime=v,A.endTime=c);else if(d){let I=y.attr[b];dm(b)&&(I=Pv(I));const w=Ph(d,v,c,{key:b,data:I},it.dateRange);w&&(w.id=g,this.id3Track.addCue(w),E[b]=w,this.hls.config.interstitialsController&&(b==="X-ASSET-LIST"||b==="X-ASSET-URL")&&w.addEventListener("enter",this.onEventCueEnter))}}h[g]={cues:E,dateRange:y,durationKnown:o}}}}class Mv{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:a,maxLiveSyncPlaybackRate:h}=this.config;if(!a||h===1||!s.live)return;const l=this.targetLatency;if(l===null)return;const u=n-l,d=Math.min(this.maxLatency,l+s.targetduration);if(u<d&&u>.05&&this.forwardBufferLength>1){const g=Math.min(2,Math.max(1,h)),y=Math.round(2/(1+Math.exp(-.75*u-this.edgeStalled))*20)/20,v=Math.min(g,Math.max(1,y));this.changeMediaPlaybackRate(t,v)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:s,targetduration:n}=e,{liveSyncDuration:a,liveSyncDurationCount:h,lowLatencyMode:l}=this.config,u=this.hls.userConfig;let d=l&&s||t;(this._targetLatencyUpdated||u.liveSyncDuration||u.liveSyncDurationCount||d===0)&&(d=a!==void 0?a:h*n);const p=n;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,p)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const s=this.levelDetails;if(s===null)return null;const n=s.edge,a=e-t-this.edgeStalled,h=n-s.totalduration,l=n-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(h,a),l)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(_.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(_.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===P.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,n;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(n=this.targetLatency)==null?void 0:n.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class Fv extends Do{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(_.LEVEL_LOADED,this.onLevelLoaded,this),e.on(_.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(_.FRAG_BUFFERED,this.onFragBuffered,this),e.on(_.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(_.LEVEL_LOADED,this.onLevelLoaded,this),e.off(_.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(_.FRAG_BUFFERED,this.onFragBuffered,this),e.off(_.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,n=[],a={},h={};let l=!1,u=!1,d=!1;t.levels.forEach(p=>{var g;const y=p.attrs;let{audioCodec:v,videoCodec:x}=p;v&&(p.audioCodec=v=Gn(v,s)||void 0),((g=x)==null?void 0:g.indexOf("avc1"))===0&&(x=p.videoCodec=D0(x));const{width:E,height:o,unknownCodecs:c}=p;let f=c?c.length:0;if(c)for(let C=f;C--;){const k=c[C];this.isAudioSupported(k)?(p.audioCodec=v=v?`${v},${k}`:k,f--,rs.audio[v.substring(0,4)]=2):this.isVideoSupported(k)&&(p.videoCodec=x=x?`${x},${k}`:k,f--,rs.video[x.substring(0,4)]=2)}if(l||(l=!!(E&&o)),u||(u=!!x),d||(d=!!v),f||v&&!this.isAudioSupported(v)||x&&!this.isVideoSupported(x)){this.log(`Some or all CODECS not supported "${y.CODECS}"`);return}const{CODECS:m,"FRAME-RATE":S,"HDCP-LEVEL":T,"PATHWAY-ID":b,RESOLUTION:A,"VIDEO-RANGE":I}=y,w=`${`${b||"."}-`}${p.bitrate}-${A}-${S}-${m}-${I}-${T}`;if(a[w])if(a[w].uri!==p.url&&!p.attrs["PATHWAY-ID"]){const C=h[w]+=1;p.attrs["PATHWAY-ID"]=new Array(C+1).join(".");const k=this.createLevel(p);a[w]=k,n.push(k)}else a[w].addGroupId("audio",y.AUDIO),a[w].addGroupId("text",y.SUBTITLES);else{const C=this.createLevel(p);a[w]=C,h[w]=1,n.push(C)}}),this.filterAndSortMediaOptions(n,t,l,u,d)}createLevel(e){const t=new Ps(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const n=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(n.message),t.supportedResult=td(n,[])}return t}isAudioSupported(e){return Da(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Da(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,n,a){let h=[],l=[],u=e;if((s||n)&&a&&(u=u.filter(({videoCodec:o,videoRange:c,width:f,height:m})=>(!!o||!!(f&&m))&&U0(c))),u.length===0){Promise.resolve().then(()=>{if(this.hls){let o="no level with compatible codecs found in manifest",c=o;t.levels.length&&(c=`one or more CODECS in variant not supported: ${Ae(t.levels.map(m=>m.attrs.CODECS).filter((m,S,T)=>T.indexOf(m)===S))}`,this.warn(c),o+=` (${c})`);const f=new Error(o);this.hls.trigger(_.ERROR,{type:Q.MEDIA_ERROR,details:P.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:f,reason:c})}});return}t.audioTracks&&(h=t.audioTracks.filter(o=>!o.audioCodec||this.isAudioSupported(o.audioCodec)),kh(h)),t.subtitles&&(l=t.subtitles,kh(l));const d=u.slice(0);u.sort((o,c)=>{if(o.attrs["HDCP-LEVEL"]!==c.attrs["HDCP-LEVEL"])return(o.attrs["HDCP-LEVEL"]||"")>(c.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&o.height!==c.height)return o.height-c.height;if(o.frameRate!==c.frameRate)return o.frameRate-c.frameRate;if(o.videoRange!==c.videoRange)return zn.indexOf(o.videoRange)-zn.indexOf(c.videoRange);if(o.videoCodec!==c.videoCodec){const f=Il(o.videoCodec),m=Il(c.videoCodec);if(f!==m)return m-f}if(o.uri===c.uri&&o.codecSet!==c.codecSet){const f=$n(o.codecSet),m=$n(c.codecSet);if(f!==m)return m-f}return o.averageBitrate!==c.averageBitrate?o.averageBitrate-c.averageBitrate:0});let p=d[0];if(this.steering&&(u=this.steering.filterParsedLevels(u),u.length!==d.length)){for(let o=0;o<d.length;o++)if(d[o].pathwayId===u[0].pathwayId){p=d[o];break}}this._levels=u;for(let o=0;o<u.length;o++)if(u[o]===p){var g;this._firstLevel=o;const c=p.bitrate,f=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${u.length} level(s) found, first bitrate: ${c}`),((g=this.hls.userConfig)==null?void 0:g.abrEwmaDefaultEstimate)===void 0){const m=Math.min(c,this.hls.config.abrEwmaDefaultEstimateMax);m>f&&f===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=m)}break}const y=a&&!n,v=this.hls.config,x=!!(v.audioStreamController&&v.audioTrackController),E={levels:u,audioTracks:h,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:a,video:n,altAudio:x&&!y&&h.some(o=>!!o.url)};this.hls.trigger(_.MANIFEST_PARSED,E)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const p=new Error("invalid level idx"),g=e<0;if(this.hls.trigger(_.ERROR,{type:Q.OTHER_ERROR,details:P.LEVEL_SWITCH_ERROR,level:e,fatal:g,error:p,reason:p.message}),g)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,n=this.currentLevel,a=n?n.attrs["PATHWAY-ID"]:void 0,h=t[e],l=h.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=h,s===e&&n&&a===l)return;this.log(`Switching to level ${e} (${h.height?h.height+"p ":""}${h.videoRange?h.videoRange+" ":""}${h.codecSet?h.codecSet+" ":""}@${h.bitrate})${l?" with Pathway "+l:""} from level ${s}${a?" with Pathway "+a:""}`);const u={level:e,attrs:h.attrs,details:h.details,bitrate:h.bitrate,averageBitrate:h.averageBitrate,maxBitrate:h.maxBitrate,realBitrate:h.realBitrate,width:h.width,height:h.height,codecSet:h.codecSet,audioCodec:h.audioCodec,videoCodec:h.videoCodec,audioGroups:h.audioGroups,subtitleGroups:h.subtitleGroups,loaded:h.loaded,loadError:h.loadError,fragmentError:h.fragmentError,name:h.name,id:h.id,uri:h.uri,url:h.url,urlId:0,audioGroupIds:h.audioGroupIds,textGroupIds:h.textGroupIds};this.hls.trigger(_.LEVEL_SWITCHING,u);const d=h.details;if(!d||d.live){const p=this.switchParams(h.uri,n==null?void 0:n.details,d);this.loadPlaylist(p)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(n=>t.indexOf(n)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===ue.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===X.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(a=>!!s[a]))return;const n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var s;const{level:n,details:a}=t,h=t.levelInfo;if(!h){var l;this.warn(`Invalid level index ${n}`),(l=t.deliveryDirectives)!=null&&l.skip&&(a.deltaUpdateFailed=!0);return}if(h===this.currentLevel||t.withoutMultiVariant){h.fragmentError===0&&(h.loadError=0);let u=h.details;u===t.details&&u.advanced&&(u=void 0),this.playlistLoaded(n,t,u)}else(s=t.deliveryDirectives)!=null&&s.skip&&(a.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),n=this.currentLevelIndex,a=e.attrs["PATHWAY-ID"],h=e.details,l=h==null?void 0:h.age;this.log(`Loading level index ${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${a?" Pathway "+a:""}${l&&h.live?" age "+l.toFixed(1)+(h.type&&" "+h.type||""):""} ${s}`),this.hls.trigger(_.LEVEL_LOADING,{url:s,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const s=this._levels.filter((a,h)=>h!==e?!0:(this.steering&&this.steering.removeLevel(a),a===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,a.details&&a.details.fragments.forEach(l=>l.level=-1)),!1));md(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const n=s.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(_.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(_.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function kh(r){const e={};r.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function au(){return self.SourceBuffer||self.WebKitSourceBuffer}function ou(){if(!pi())return!1;const e=au();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Uv(){if(!ou())return!1;const r=pi();return typeof(r==null?void 0:r.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>r.isTypeSupported(Ds(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(Ds(e,"audio"))))}function Ov(){var r;const e=au();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}const Bv=100;class Nv extends To{constructor(e,t,s){super(e,t,s,"stream-controller",X.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const n=this.media,a=n?n.currentTime:null;if(a===null||!K(a)||(this.log(`Media seeked to ${a.toFixed(3)}`),!this.getBufferedFrag(a)))return;const h=this.getFwdBufferInfoAtPos(n,a,X.MAIN,0);if(h===null||h.len===0){this.warn(`Main forward buffer length at ${a} on "seeked" event ${h?h.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(_.MANIFEST_PARSED,this.onManifestParsed,this),e.on(_.LEVEL_LOADING,this.onLevelLoading,this),e.on(_.LEVEL_LOADED,this.onLevelLoaded,this),e.on(_.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(_.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(_.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(_.BUFFER_CREATED,this.onBufferCreated,this),e.on(_.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(_.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(_.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(_.MANIFEST_PARSED,this.onManifestParsed,this),e.off(_.LEVEL_LOADED,this.onLevelLoaded,this),e.off(_.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(_.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(_.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(_.BUFFER_CREATED,this.onBufferCreated,this),e.off(_.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(_.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(_.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:n}=this;if(this.stopLoad(),this.setInterval(Bv),this.level=-1,!this.startFragRequested){let a=n.startLevel;a===-1&&(n.config.testBandwidth&&this.levels.length>1?(a=0,this.bitrateTest=!0):a=n.firstAutoLevel),n.nextLoadLevel=a,this.level=n.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=M.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=M.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case M.WAITING_LEVEL:{const{levels:t,level:s}=this,n=t==null?void 0:t[s],a=n==null?void 0:n.details;if(a&&(!a.live||this.levelLastLoaded===n&&!this.waitForLive(n))){if(this.waitForCdnTuneIn(a))break;this.state=M.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=M.IDLE;break}break}case M.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),s=this.retryDate;if(!s||t>=s||(e=this.media)!=null&&e.seeking){const{levels:n,level:a}=this,h=n==null?void 0:n[a];this.resetStartWhenNotLoaded(h||null),this.state=M.IDLE}}break}this.state===M.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:n}=this;if(t===null||!n&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const a=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[a]))return;const h=s[a],l=this.getMainFwdBufferInfo();if(l===null)return;const u=this.getLevelDetails();if(u&&this._streamEnded(l,u)){const E={};this.altAudio===2&&(E.type="video"),this.hls.trigger(_.BUFFER_EOS,E),this.state=M.ENDED;return}if(!this.buffering)return;e.loadLevel!==a&&e.manualLevel===-1&&this.log(`Adapting to level ${a} from level ${this.level}`),this.level=e.nextLoadLevel=a;const d=h.details;if(!d||this.state===M.WAITING_LEVEL||this.waitForLive(h)){this.level=a,this.state=M.WAITING_LEVEL,this.startFragRequested=!1;return}const p=l.len,g=this.getMaxBufferLength(h.maxBitrate);if(p>=g)return;this.backtrackFragment&&this.backtrackFragment.start>l.end&&(this.backtrackFragment=null);const y=this.backtrackFragment?this.backtrackFragment.start:l.end;let v=this.getNextFragment(y,d);if(this.couldBacktrack&&!this.fragPrevious&&v&&Ne(v)&&this.fragmentTracker.getState(v)!==ke.OK){var x;const o=((x=this.backtrackFragment)!=null?x:v).sn-d.startSN,c=d.fragments[o-1];c&&v.cc===c.cc&&(v=c,this.fragmentTracker.removeFragment(c))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(v&&this.isLoopLoading(v,y)){if(!v.gap){const o=this.audioOnly&&!this.altAudio?Ee.AUDIO:Ee.VIDEO,c=(o===Ee.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;c&&this.afterBufferFlushed(c,o,X.MAIN)}v=this.getNextFragmentLoopLoading(v,d,l,X.MAIN,g)}v&&(v.initSegment&&!v.initSegment.data&&!this.bitrateTest&&(v=v.initSegment),this.loadFragment(v,h,y))}loadFragment(e,t,s){const n=this.fragmentTracker.getState(e);n===ke.NOT_LOADED||n===ke.PARTIAL?Ne(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,X.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const a=this.getLevelDetails();if(a!=null&&a.live){const l=this.getMainFwdBufferInfo();if(!l||l.len<a.targetduration*2)return}if(!t.paused&&e){const l=this.hls.nextLoadLevel,u=e[l],d=this.fragLastKbps;d&&this.fragCurrent?s=this.fragCurrent.duration*u.maxBitrate/(1e3*d)+1:s=0}else s=0;const h=this.getBufferedFrag(t.currentTime+s);if(h){const l=this.followingBufferedFrag(h);if(l){this.abortCurrentFrag();const u=l.maxStartPTS?l.maxStartPTS:l.start,d=l.duration,p=Math.max(h.end,u+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(p,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case M.KEY_LOADING:case M.FRAG_LOADING:case M.FRAG_LOADING_WAITING_RETRY:case M.PARSING:case M.PARSED:this.state=M.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;Yt(s,"playing",this.onMediaPlaying),Yt(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(Rt(s,"playing",this.onMediaPlaying),Rt(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(_.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,n=!1;t.levels.forEach(a=>{const h=a.audioCodec;h&&(s=s||h.indexOf("mp4a.40.2")!==-1,n=n||h.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=s&&n&&!Ov(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==M.IDLE)return;const n=t.levelInfo;(!n.details||n.details.live&&(this.levelLastLoaded!==n||n.details.expired)||this.waitForCdnTuneIn(n.details))&&(this.state=M.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:n,startFragRequested:a}=this,h=t.level,l=t.details,u=l.totalduration;if(!n){this.warn(`Levels were reset while loading level ${h}`);return}this.log(`Level ${h} loaded [${l.startSN},${l.endSN}]${l.lastPartSn?`[part-${l.lastPartSn}-${l.lastPartIndex}]`:""}, cc [${l.startCC}, ${l.endCC}] duration:${u}`);const d=t.levelInfo,p=this.fragCurrent;p&&(this.state===M.FRAG_LOADING||this.state===M.FRAG_LOADING_WAITING_RETRY)&&p.level!==t.level&&p.loader&&this.abortCurrentFrag();let g=0;if(l.live||(s=d.details)!=null&&s.live){var y;if(this.checkLiveUpdate(l),l.deltaUpdateFailed)return;g=this.alignPlaylists(l,d.details,(y=this.levelLastLoaded)==null?void 0:y.details)}if(d.details=l,this.levelLastLoaded=d,a||this.setStartPosition(l,g),this.hls.trigger(_.LEVEL_UPDATED,{details:l,level:h}),this.state===M.WAITING_LEVEL){if(this.waitForCdnTuneIn(l))return;this.state=M.IDLE}a&&l.live&&this.synchronizeToLiveEdge(l),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const n=this.hls.liveSyncPosition,a=this.getLoadPosition(),h=e.fragmentStart,l=e.edge,u=a>=h-t.maxFragLookUpTolerance&&a<=l;if(n!==null&&s.duration>n&&(a<n||!u)){const d=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!u&&s.readyState<4||a<l-d)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),s.readyState&&(this.warn(`Playback: ${a.toFixed(3)} is located too far from the end of live sliding playlist: ${l}, reset currentTime to : ${n.toFixed(3)}`),s.currentTime=n))}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:n,payload:a}=e,{levels:h}=this;if(!h){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const l=h[s.level];if(!l){this.warn(`Level ${s.level} not found on progress`);return}const u=l.details;if(!u){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const d=l.videoCodec,p=u.PTSKnown||!u.live,g=(t=s.initSegment)==null?void 0:t.data,y=this._getAudioCodec(l),v=this.transmuxer=this.transmuxer||new Nd(this.hls,X.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),x=n?n.index:-1,E=x!==-1,o=new So(s.level,s.sn,s.stats.chunkCount,a.byteLength,x,E),c=this.initPTS[s.cc];v.push(a,g,y,d,s,n,u.totalduration,p,o,c)}onAudioTrackSwitching(e,t){const s=this.hls,n=this.altAudio===2;if(Hn(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const h=this.fragCurrent;h&&(this.log("Switching to main audio track, cancel main fragment load"),h.abortRequests(),this.fragmentTracker.removeFragment(h)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n){this.fragmentTracker.removeAllFragments(),s.once(_.BUFFER_FLUSHED,()=>{var h;(h=this.hls)==null||h.trigger(_.AUDIO_TRACK_SWITCHED,t)}),s.trigger(_.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(_.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=Hn(t.url,this.hls);if(s){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let n,a,h=!1;for(const l in s){const u=s[l];if(u.id==="main"){if(a=l,n=u,l==="video"){const d=s[l];d&&(this.videoBuffer=d.buffer)}}else h=!0}h&&n?(this.log(`Alternate track found, use ${a}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:n}=t,a=s.type===X.MAIN;if(a){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${n?" p: "+n.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===M.PARSED&&(this.state=M.IDLE);return}const l=n?n.stats:s.stats;this.fragLastKbps=Math.round(8*l.total/(l.buffering.end-l.loading.first)),Ne(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,n)}const h=this.media;h&&(!this._hasEnoughToStart&&ce.getBuffered(h).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),a&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=M.ERROR;return}switch(t.details){case P.FRAG_GAP:case P.FRAG_PARSING_ERROR:case P.FRAG_DECRYPT_ERROR:case P.FRAG_LOAD_ERROR:case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_ERROR:case P.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(X.MAIN,t);break;case P.LEVEL_LOAD_ERROR:case P.LEVEL_LOAD_TIMEOUT:case P.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===M.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===ue.LEVEL&&(this.state=M.IDLE);break;case P.BUFFER_ADD_CODEC_ERROR:case P.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.resetLoadingState();break;case P.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case P.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=M.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Ee.AUDIO||!this.altAudio){const s=(t===Ee.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,X.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const n=this.timelineOffset;n&&s&&(s+=n);const a=this.getLevelDetails(),h=ce.getBuffered(e),l=h.length?h.start(0):0,u=l-s,d=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);u>0&&(u<d||this.loadingParts&&u<2*((a==null?void 0:a.partTarget)||0))&&(this.log(`adjusting start position by ${u} to match buffer start`),s+=u,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${l}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:n}=this,a=s==null?void 0:s.frag;if(!a||this.fragContextChanged(a))return;t.fragmentError=0,this.state=M.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const h=a.stats;h.parsing.start=h.parsing.end=h.buffering.start=h.buffering.end=self.performance.now(),n.trigger(_.FRAG_LOADED,s),a.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const s=this.playlistType,{hls:n}=this,{remuxResult:a,chunkMeta:h}=e,l=this.getCurrentContext(h);if(!l){this.resetWhenMissingContext(h);return}const{frag:u,part:d,level:p}=l,{video:g,text:y,id3:v,initSegment:x}=a,{details:E}=p,o=this.altAudio?void 0:a.audio;if(this.fragContextChanged(u)){this.fragmentTracker.removeFragment(u);return}if(this.state=M.PARSING,x){if(x!=null&&x.tracks){const m=u.initSegment||u;this._bufferInitSegment(p,x.tracks,m,h),n.trigger(_.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:s,tracks:x.tracks})}const c=x.initPTS,f=x.timescale;K(c)&&(this.initPTS[u.cc]={baseTime:c,timescale:f},n.trigger(_.INIT_PTS_FOUND,{frag:u,id:s,initPTS:c,timescale:f}))}if(g&&E){o&&g.type==="audiovideo"&&this.logMuxedErr(u);const c=E.fragments[u.sn-1-E.startSN],f=u.sn===E.startSN,m=!c||u.cc>c.cc;if(a.independent!==!1){const{startPTS:S,endPTS:T,startDTS:b,endDTS:A}=g;if(d)d.elementaryStreams[g.type]={startPTS:S,endPTS:T,startDTS:b,endDTS:A};else if(g.firstKeyFrame&&g.independent&&h.id===1&&!m&&(this.couldBacktrack=!0),g.dropped&&g.independent){const I=this.getMainFwdBufferInfo(),L=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,w=g.firstKeyFramePTS?g.firstKeyFramePTS:S;if(!f&&L<w-this.config.maxBufferHole&&!m){this.backtrack(u);return}else m&&(u.gap=!0);u.setElementaryStreamInfo(g.type,u.start,T,u.start,A,!0)}else f&&S-(E.appliedTimelineOffset||0)>Cn&&(u.gap=!0);u.setElementaryStreamInfo(g.type,S,T,b,A),this.backtrackFragment&&(this.backtrackFragment=u),this.bufferFragmentData(g,u,d,h,f||m)}else if(f||m)u.gap=!0;else{this.backtrack(u);return}}if(o){const{startPTS:c,endPTS:f,startDTS:m,endDTS:S}=o;d&&(d.elementaryStreams[Ee.AUDIO]={startPTS:c,endPTS:f,startDTS:m,endDTS:S}),u.setElementaryStreamInfo(Ee.AUDIO,c,f,m,S),this.bufferFragmentData(o,u,d,h)}if(E&&v!=null&&(t=v.samples)!=null&&t.length){const c={id:s,frag:u,details:E,samples:v.samples};n.trigger(_.FRAG_PARSING_METADATA,c)}if(E&&y){const c={id:s,frag:u,details:E,samples:y.samples};n.trigger(_.FRAG_PARSING_USERDATA,c)}}logMuxedErr(e){this.warn(`${Ne(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,n){if(this.state!==M.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:a,video:h,audiovideo:l}=t;if(a){let d=bn(a.codec,e.audioCodec);d==="mp4a"&&(d="mp4a.40.5");const p=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){d&&(d.indexOf("mp4a.40.5")!==-1?d="mp4a.40.2":d="mp4a.40.5");const g=a.metadata;g&&"channelCount"in g&&(g.channelCount||1)!==1&&p.indexOf("firefox")===-1&&(d="mp4a.40.5")}d&&d.indexOf("mp4a.40.5")!==-1&&p.indexOf("android")!==-1&&a.container!=="audio/mpeg"&&(d="mp4a.40.2",this.log(`Android: force audio codec to ${d}`)),e.audioCodec&&e.audioCodec!==d&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${d}"`),a.levelCodec=d,a.id=X.MAIN,this.log(`Init audio buffer, container:${a.container}, codecs[selected/level/parsed]=[${d||""}/${e.audioCodec||""}/${a.codec}]`),delete t.audiovideo}if(h){h.levelCodec=e.videoCodec,h.id=X.MAIN;const d=h.codec;if((d==null?void 0:d.length)===4)switch(d){case"hvc1":case"hev1":h.codec="hvc1.1.6.L120.90";break;case"av01":h.codec="av01.0.04M.08";break;case"avc1":h.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${h.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${h.codec!==d?" parsed-corrected="+h.codec:""}${h.supplemental?" supplemental="+h.supplemental:""}`),delete t.audiovideo}l&&(this.log(`Init audiovideo buffer, container:${l.container}, codecs[level/parsed]=[${e.codecs}/${l.codec}]`),delete t.video,delete t.audio);const u=Object.keys(t);if(u.length){if(this.hls.trigger(_.BUFFER_CODECS,t),!this.hls)return;u.forEach(d=>{const g=t[d].initSegment;g!=null&&g.byteLength&&this.hls.trigger(_.BUFFER_APPENDING,{type:d,data:g,frag:s,part:null,chunkMeta:n,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,X.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e==null?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=M.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(ce.isBuffered(e,s)?t=this.getAppendedFrag(s):ce.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const n=this.fragPlaying,a=t.level;(!n||t.sn!==n.sn||n.level!==a)&&(this.fragPlaying=t,this.hls.trigger(_.FRAG_CHANGED,{frag:t}),(!n||n.level!==a)&&this.hls.trigger(_.LEVEL_SWITCHED,{level:a}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return K(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(K(t)){const s=this.getLevelDetails(),n=this.currentFrag||(s?ki(null,s.fragments,t):null);if(n){const a=n.programDateTime;if(a!==null){const h=a+(t-n.start)*1e3;return new Date(h)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class $v{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyUriToKeyInfo){const n=this.keyUriToKeyInfo[s].loader;if(n){var t;if(e&&e!==((t=n.context)==null?void 0:t.frag.type))return;n.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=P.KEY_LOAD_ERROR,s,n,a){return new Gt({type:Q.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:a,error:s,networkDetails:n})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:n}=e;for(let a=0;a<t.length;a++){const h=t[a];if(n<=h.cc&&(s==="initSegment"||h.sn==="initSegment"||s<h.sn)){this.emeController.selectKeySystemFormat(h).then(l=>{h.setKeyFormat(l)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,n;t&&e.setKeyFormat(t);const a=e.decryptdata;if(!a){const d=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,P.KEY_LOAD_ERROR,d))}const h=a.uri;if(!h)return Promise.reject(this.createKeyLoadError(e,P.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${h}"`)));let l=this.keyUriToKeyInfo[h];if((s=l)!=null&&s.decryptdata.key)return a.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if((n=l)!=null&&n.keyLoadPromise){var u;switch((u=l.mediaKeySessionContext)==null?void 0:u.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return l.keyLoadPromise.then(d=>(a.key=d.keyInfo.decryptdata.key,{frag:e,keyInfo:l}))}}switch(l=this.keyUriToKeyInfo[h]={decryptdata:a,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},a.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return a.keyFormat==="identity"?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,P.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${a.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const n=this.emeController.loadKey(s);if(n)return(e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,s))).catch(a=>{throw e.keyLoadPromise=null,a})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,n=s.loader,a=new n(s);return t.keyLoader=e.loader=a,e.keyLoadPromise=new Promise((h,l)=>{const u={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=s.keyLoadPolicy.default,p={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(y,v,x,E)=>{const{frag:o,keyInfo:c,url:f}=x;if(!o.decryptdata||c!==this.keyUriToKeyInfo[f])return l(this.createKeyLoadError(o,P.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),E));c.decryptdata.key=o.decryptdata.key=new Uint8Array(y.data),o.keyLoader=null,c.loader=null,h({frag:o,keyInfo:c})},onError:(y,v,x,E)=>{this.resetLoader(v),l(this.createKeyLoadError(t,P.KEY_LOAD_ERROR,new Error(`HTTP Error ${y.code} loading key ${y.text}`),x,xe({url:u.url,data:void 0},y)))},onTimeout:(y,v,x)=>{this.resetLoader(v),l(this.createKeyLoadError(t,P.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),x))},onAbort:(y,v,x)=>{this.resetLoader(v),l(this.createKeyLoadError(t,P.INTERNAL_ABORTED,new Error("key loading aborted"),x))}};a.load(u,p,g)})}resetLoader(e){const{frag:t,keyInfo:s,url:n}=e,a=s.loader;t.keyLoader===a&&(t.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[n],a&&a.destroy()}}function Mh(r){const{type:e}=r;switch(e){case ue.AUDIO_TRACK:return X.AUDIO;case ue.SUBTITLE_TRACK:return X.SUBTITLE;default:return X.MAIN}}function fa(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Gv{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.LEVEL_LOADING,this.onLevelLoading,this),e.on(_.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(_.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(_.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.LEVEL_LOADING,this.onLevelLoading,this),e.off(_.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(_.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(_.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,n=t.loader,a=s||n,h=new a(t);return this.loaders[e.type]=h,h}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ue.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:n,pathwayId:a,url:h,deliveryDirectives:l,levelInfo:u}=t;this.load({id:s,level:n,pathwayId:a,responseType:"text",type:ue.LEVEL,url:h,deliveryDirectives:l,levelOrTrack:u})}onAudioTrackLoading(e,t){const{id:s,groupId:n,url:a,deliveryDirectives:h,track:l}=t;this.load({id:s,groupId:n,level:null,responseType:"text",type:ue.AUDIO_TRACK,url:a,deliveryDirectives:h,levelOrTrack:l})}onSubtitleTrackLoading(e,t){const{id:s,groupId:n,url:a,deliveryDirectives:h,track:l}=t;this.load({id:s,groupId:n,level:null,responseType:"text",type:ue.SUBTITLE_TRACK,url:a,deliveryDirectives:h,levelOrTrack:l})}onLevelsUpdated(e,t){const s=this.loaders[ue.LEVEL];if(s){const n=s.context;n&&!t.levels.some(a=>a===n.levelOrTrack)&&(s.abort(),delete this.loaders[ue.LEVEL])}}load(e){var t;const s=this.hls.config;let n=this.getInternalLoader(e);if(n){const d=this.hls.logger,p=n.context;if(p&&p.levelOrTrack===e.levelOrTrack&&(p.url===e.url||p.deliveryDirectives&&!e.deliveryDirectives)){p.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${p.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let a;if(e.type===ue.MANIFEST?a=s.manifestLoadPolicy.default:a=Te({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),K((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===ue.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===ue.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===ue.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){const p=d.partTarget,g=d.targetduration;if(p&&g){const y=Math.max(p*3,g*.8)*1e3;a=Te({},a,{maxTimeToFirstByteMs:Math.min(y,a.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(y,a.maxTimeToFirstByteMs)})}}}const h=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:h.maxNumRetry||0,retryDelay:h.retryDelayMs||0,maxRetryDelay:h.maxRetryDelayMs||0},u={onSuccess:(d,p,g,y)=>{const v=this.getInternalLoader(g);this.resetInternalLoader(g.type);const x=d.data;if(x.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(d,g,new Error("no EXTM3U delimiter"),y||null,p);return}p.parsing.start=performance.now(),Lt.isMediaPlaylist(x)||g.type!==ue.MANIFEST?this.handleTrackOrLevelPlaylist(d,p,g,y||null,v):this.handleMasterPlaylist(d,p,g,y)},onError:(d,p,g,y)=>{this.handleNetworkError(p,g,!1,d,y)},onTimeout:(d,p,g)=>{this.handleNetworkError(p,g,!0,void 0,d)}};n.load(e,l,u)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,n){const a=this.hls,h=e.data,l=fa(e,s),u=Lt.parseMasterPlaylist(h,l);if(u.playlistParsingError){this.handleManifestParsingError(e,s,u.playlistParsingError,n,t);return}const{contentSteering:d,levels:p,sessionData:g,sessionKeys:y,startTimeOffset:v,variableList:x}=u;this.variableList=x;const{AUDIO:E=[],SUBTITLES:o,"CLOSED-CAPTIONS":c}=Lt.parseMasterPlaylistMedia(h,l,u);E.length&&!E.some(m=>!m.url)&&p[0].audioCodec&&!p[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),E.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ie({}),bitrate:0,url:""})),a.trigger(_.MANIFEST_LOADED,{levels:p,audioTracks:E,subtitles:o,captions:c,contentSteering:d,url:l,stats:t,networkDetails:n,sessionData:g,sessionKeys:y,startTimeOffset:v,variableList:x})}handleTrackOrLevelPlaylist(e,t,s,n,a){const h=this.hls,{id:l,level:u,type:d}=s,p=fa(e,s),g=K(u)?u:K(l)?l:0,y=Mh(s),v=Lt.parseLevelPlaylist(e.data,p,g,y,0,this.variableList);if(d===ue.MANIFEST){const x={attrs:new Ie({}),bitrate:0,details:v,name:"",url:p};v.requestScheduled=t.loading.start+fd(v,0),h.trigger(_.MANIFEST_LOADED,{levels:[x],audioTracks:[],url:p,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=v,this.handlePlaylistLoaded(v,e,t,s,n,a)}handleManifestParsingError(e,t,s,n,a){this.hls.trigger(_.ERROR,{type:Q.NETWORK_ERROR,details:P.MANIFEST_PARSING_ERROR,fatal:t.type===ue.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:n,stats:a})}handleNetworkError(e,t,s=!1,n,a){let h=`A network ${s?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===ue.LEVEL?h+=`: ${e.level} id: ${e.id}`:(e.type===ue.AUDIO_TRACK||e.type===ue.SUBTITLE_TRACK)&&(h+=` id: ${e.id} group-id: "${e.groupId}"`);const l=new Error(h);this.hls.logger.warn(`[playlist-loader]: ${h}`);let u=P.UNKNOWN,d=!1;const p=this.getInternalLoader(e);switch(e.type){case ue.MANIFEST:u=s?P.MANIFEST_LOAD_TIMEOUT:P.MANIFEST_LOAD_ERROR,d=!0;break;case ue.LEVEL:u=s?P.LEVEL_LOAD_TIMEOUT:P.LEVEL_LOAD_ERROR,d=!1;break;case ue.AUDIO_TRACK:u=s?P.AUDIO_TRACK_LOAD_TIMEOUT:P.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case ue.SUBTITLE_TRACK:u=s?P.SUBTITLE_TRACK_LOAD_TIMEOUT:P.SUBTITLE_LOAD_ERROR,d=!1;break}p&&this.resetInternalLoader(e.type);const g={type:Q.NETWORK_ERROR,details:u,fatal:d,url:e.url,loader:p,context:e,error:l,networkDetails:t,stats:a};if(n){const y=(t==null?void 0:t.url)||e.url;g.response=xe({url:y,data:void 0},n)}this.hls.trigger(_.ERROR,g)}handlePlaylistLoaded(e,t,s,n,a,h){const l=this.hls,{type:u,level:d,id:p,groupId:g,deliveryDirectives:y}=n,v=fa(t,n),x=Mh(n),E=typeof n.level=="number"&&x===X.MAIN?d:void 0;if(!e.fragments.length){const c=e.playlistParsingError=new Error("No Segments found in Playlist");l.trigger(_.ERROR,{type:Q.NETWORK_ERROR,details:P.LEVEL_EMPTY_ERROR,fatal:!1,url:v,error:c,reason:c.message,response:t,context:n,level:E,parent:x,networkDetails:a,stats:s});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const o=e.playlistParsingError;if(o){if(this.hls.logger.warn(o),!l.config.ignorePlaylistParsingErrors){l.trigger(_.ERROR,{type:Q.NETWORK_ERROR,details:P.LEVEL_PARSING_ERROR,fatal:!1,url:v,error:o,reason:o.message,response:t,context:n,level:E,parent:x,networkDetails:a,stats:s});return}e.playlistParsingError=null}switch(e.live&&h&&(h.getCacheAge&&(e.ageHeader=h.getCacheAge()||0),(!h.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),u){case ue.MANIFEST:case ue.LEVEL:l.trigger(_.LEVEL_LOADED,{details:e,levelInfo:n.levelOrTrack||l.levels[0],level:E||0,id:p||0,stats:s,networkDetails:a,deliveryDirectives:y,withoutMultiVariant:u===ue.MANIFEST});break;case ue.AUDIO_TRACK:l.trigger(_.AUDIO_TRACK_LOADED,{details:e,track:n.levelOrTrack,id:p||0,groupId:g||"",stats:s,networkDetails:a,deliveryDirectives:y});break;case ue.SUBTITLE_TRACK:l.trigger(_.SUBTITLE_TRACK_LOADED,{details:e,track:n.levelOrTrack,id:p||0,groupId:g||"",stats:s,networkDetails:a,deliveryDirectives:y});break}}}class oi{static get version(){return Fs}static isMSESupported(){return ou()}static isSupported(){return Uv()}static getMediaSource(){return pi()}static get Events(){return _}static get MetadataSchema(){return it}static get ErrorTypes(){return Q}static get ErrorDetails(){return P}static get DefaultConfig(){return oi.defaultConfig?oi.defaultConfig:Tv}static set DefaultConfig(e){oi.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new bo,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=a0(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=Av(oi.DefaultConfig,e,t);this.userConfig=e,s.progressive&&Iv(s,t);const{abrController:n,bufferController:a,capLevelController:h,errorController:l,fpsController:u}=s,d=new l(this),p=this.abrController=new n(this),g=new Z0(this),y=s.interstitialsController,v=y?this.interstitialsController=new y(this,oi):null,x=this.bufferController=new a(this,g),E=this.capLevelController=new h(this),o=new u(this),c=new Gv(this),f=s.contentSteeringController,m=f?new f(this):null,S=this.levelController=new Fv(this,m),T=new kv(this),b=new $v(this.config),A=this.streamController=new Nv(this,g,b),I=this.gapController=new Cv(this,g);E.setStreamController(A),o.setStreamController(A);const L=[c,S,A];v&&L.splice(1,0,v),m&&L.splice(1,0,m),this.networkControllers=L;const w=[p,x,I,E,o,T,g];this.audioTrackController=this.createController(s.audioTrackController,L);const C=s.audioStreamController;C&&L.push(this.audioStreamController=new C(this,g,b)),this.subtitleTrackController=this.createController(s.subtitleTrackController,L);const k=s.subtitleStreamController;k&&L.push(this.subtititleStreamController=new k(this,g,b)),this.createController(s.timelineController,w),b.emeController=this.emeController=this.createController(s.emeController,w),this.cmcdController=this.createController(s.cmcdController,w),this.latencyController=this.createController(Mv,w),this.coreComponents=w,L.push(d);const U=d.onErrorOut;typeof U=="function"&&this.on(_.ERROR,U,d),this.on(_.MANIFEST_LOADED,c.onManifestLoaded,c)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,n){this._emitter.off(e,t,s,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const n=e===_.ERROR;this.trigger(_.ERROR,{type:Q.OTHER_ERROR,details:P.INTERNAL_EXCEPTION,fatal:n,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(_.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const a=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(_.ERROR,{type:Q.OTHER_ERROR,details:P.ATTACH_MEDIA_ERROR,fatal:!0,error:a});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,n=t?e:{media:s};this._media=s,this.trigger(_.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(_.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(_.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,n=this._url=po.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),t&&s&&(s!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(_.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[X.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[X.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[X.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=Xm()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){F0(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let n=0;n<s;n++)if(e[n].maxBitrate>=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let n;if(t===-1&&e!=null&&e.length?n=e.length-1:n=t,s)for(let a=n;a--;){const h=e[a].attrs["HDCP-LEVEL"];if(h&&h<=s)return a}return n}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const s=sd(t);return id(e,s,navigator.mediaCapabilities)}}oi.defaultConfig=void 0;var Xn={};(function(r){var e=function(){var o=new Date,c=4,f=3,m=2,S=1,T=c,b={setLogLevel:function(A){A==this.debug?T=S:A==this.info?T=m:A==this.warn?T=f:(A==this.error,T=c)},debug:function(A,I){console.debug===void 0&&(console.debug=console.log),S>=T&&console.debug("["+e.getDurationString(new Date-o,1e3)+"]","["+A+"]",I)},log:function(A,I){this.debug(A.msg)},info:function(A,I){m>=T&&console.info("["+e.getDurationString(new Date-o,1e3)+"]","["+A+"]",I)},warn:function(A,I){f>=T&&console.warn("["+e.getDurationString(new Date-o,1e3)+"]","["+A+"]",I)},error:function(A,I){c>=T&&console.error("["+e.getDurationString(new Date-o,1e3)+"]","["+A+"]",I)}};return b}();e.getDurationString=function(o,c){var f;function m(L,w){for(var C=""+L,k=C.split(".");k[0].length<w;)k[0]="0"+k[0];return k.join(".")}o<0?(f=!0,o=-o):f=!1;var S=c||1,T=o/S,b=Math.floor(T/3600);T-=b*3600;var A=Math.floor(T/60);T-=A*60;var I=T*1e3;return T=Math.floor(T),I-=T*1e3,I=Math.floor(I),(f?"-":"")+b+":"+m(A,2)+":"+m(T,2)+"."+m(I,3)},e.printRanges=function(o){var c=o.length;if(c>0){for(var f="",m=0;m<c;m++)m>0&&(f+=","),f+="["+e.getDurationString(o.start(m))+","+e.getDurationString(o.end(m))+"]";return f}else return"(empty)"},r.Log=e;var t=function(o){if(o instanceof ArrayBuffer)this.buffer=o,this.dataview=new DataView(o);else throw"Needs an array buffer";this.position=0};t.prototype.getPosition=function(){return this.position},t.prototype.getEndPosition=function(){return this.buffer.byteLength},t.prototype.getLength=function(){return this.buffer.byteLength},t.prototype.seek=function(o){var c=Math.max(0,Math.min(this.buffer.byteLength,o));return this.position=isNaN(c)||!isFinite(c)?0:c,!0},t.prototype.isEos=function(){return this.getPosition()>=this.getEndPosition()},t.prototype.readAnyInt=function(o,c){var f=0;if(this.position+o<=this.buffer.byteLength){switch(o){case 1:c?f=this.dataview.getInt8(this.position):f=this.dataview.getUint8(this.position);break;case 2:c?f=this.dataview.getInt16(this.position):f=this.dataview.getUint16(this.position);break;case 3:if(c)throw"No method for reading signed 24 bits values";f=this.dataview.getUint8(this.position)<<16,f|=this.dataview.getUint8(this.position+1)<<8,f|=this.dataview.getUint8(this.position+2);break;case 4:c?f=this.dataview.getInt32(this.position):f=this.dataview.getUint32(this.position);break;case 8:if(c)throw"No method for reading signed 64 bits values";f=this.dataview.getUint32(this.position)<<32,f|=this.dataview.getUint32(this.position+4);break;default:throw"readInt method not implemented for size: "+o}return this.position+=o,f}else throw"Not enough bytes in buffer"},t.prototype.readUint8=function(){return this.readAnyInt(1,!1)},t.prototype.readUint16=function(){return this.readAnyInt(2,!1)},t.prototype.readUint24=function(){return this.readAnyInt(3,!1)},t.prototype.readUint32=function(){return this.readAnyInt(4,!1)},t.prototype.readUint64=function(){return this.readAnyInt(8,!1)},t.prototype.readString=function(o){if(this.position+o<=this.buffer.byteLength){for(var c="",f=0;f<o;f++)c+=String.fromCharCode(this.readUint8());return c}else throw"Not enough bytes in buffer"},t.prototype.readCString=function(){for(var o=[];;){var c=this.readUint8();if(c!==0)o.push(c);else break}return String.fromCharCode.apply(null,o)},t.prototype.readInt8=function(){return this.readAnyInt(1,!0)},t.prototype.readInt16=function(){return this.readAnyInt(2,!0)},t.prototype.readInt32=function(){return this.readAnyInt(4,!0)},t.prototype.readInt64=function(){return this.readAnyInt(8,!1)},t.prototype.readUint8Array=function(o){for(var c=new Uint8Array(o),f=0;f<o;f++)c[f]=this.readUint8();return c},t.prototype.readInt16Array=function(o){for(var c=new Int16Array(o),f=0;f<o;f++)c[f]=this.readInt16();return c},t.prototype.readUint16Array=function(o){for(var c=new Int16Array(o),f=0;f<o;f++)c[f]=this.readUint16();return c},t.prototype.readUint32Array=function(o){for(var c=new Uint32Array(o),f=0;f<o;f++)c[f]=this.readUint32();return c},t.prototype.readInt32Array=function(o){for(var c=new Int32Array(o),f=0;f<o;f++)c[f]=this.readInt32();return c},r.MP4BoxStream=t;var s=function(o,c,f){this._byteOffset=c||0,o instanceof ArrayBuffer?this.buffer=o:typeof o=="object"?(this.dataView=o,c&&(this._byteOffset+=c)):this.buffer=new ArrayBuffer(o||0),this.position=0,this.endianness=f??s.LITTLE_ENDIAN};s.prototype={},s.prototype.getPosition=function(){return this.position},s.prototype._realloc=function(o){if(this._dynamicSize){var c=this._byteOffset+this.position+o,f=this._buffer.byteLength;if(c<=f){c>this._byteLength&&(this._byteLength=c);return}for(f<1&&(f=1);c>f;)f*=2;var m=new ArrayBuffer(f),S=new Uint8Array(this._buffer),T=new Uint8Array(m,0,S.length);T.set(S),this.buffer=m,this._byteLength=c}},s.prototype._trimAlloc=function(){if(this._byteLength!=this._buffer.byteLength){var o=new ArrayBuffer(this._byteLength),c=new Uint8Array(o),f=new Uint8Array(this._buffer,0,c.length);c.set(f),this.buffer=o}},s.BIG_ENDIAN=!1,s.LITTLE_ENDIAN=!0,s.prototype._byteLength=0,Object.defineProperty(s.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}}),Object.defineProperty(s.prototype,"buffer",{get:function(){return this._trimAlloc(),this._buffer},set:function(o){this._buffer=o,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(s.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(o){this._byteOffset=o,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(s.prototype,"dataView",{get:function(){return this._dataView},set:function(o){this._byteOffset=o.byteOffset,this._buffer=o.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+o.byteLength}}),s.prototype.seek=function(o){var c=Math.max(0,Math.min(this.byteLength,o));this.position=isNaN(c)||!isFinite(c)?0:c},s.prototype.isEof=function(){return this.position>=this._byteLength},s.prototype.mapUint8Array=function(o){this._realloc(o*1);var c=new Uint8Array(this._buffer,this.byteOffset+this.position,o);return this.position+=o*1,c},s.prototype.readInt32Array=function(o,c){o=o??this.byteLength-this.position/4;var f=new Int32Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readInt16Array=function(o,c){o=o??this.byteLength-this.position/2;var f=new Int16Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readInt8Array=function(o){o=o??this.byteLength-this.position;var c=new Int8Array(o);return s.memcpy(c.buffer,0,this.buffer,this.byteOffset+this.position,o*c.BYTES_PER_ELEMENT),this.position+=c.byteLength,c},s.prototype.readUint32Array=function(o,c){o=o??this.byteLength-this.position/4;var f=new Uint32Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readUint16Array=function(o,c){o=o??this.byteLength-this.position/2;var f=new Uint16Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readUint8Array=function(o){o=o??this.byteLength-this.position;var c=new Uint8Array(o);return s.memcpy(c.buffer,0,this.buffer,this.byteOffset+this.position,o*c.BYTES_PER_ELEMENT),this.position+=c.byteLength,c},s.prototype.readFloat64Array=function(o,c){o=o??this.byteLength-this.position/8;var f=new Float64Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readFloat32Array=function(o,c){o=o??this.byteLength-this.position/4;var f=new Float32Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readInt32=function(o){var c=this._dataView.getInt32(this.position,o??this.endianness);return this.position+=4,c},s.prototype.readInt16=function(o){var c=this._dataView.getInt16(this.position,o??this.endianness);return this.position+=2,c},s.prototype.readInt8=function(){var o=this._dataView.getInt8(this.position);return this.position+=1,o},s.prototype.readUint32=function(o){var c=this._dataView.getUint32(this.position,o??this.endianness);return this.position+=4,c},s.prototype.readUint16=function(o){var c=this._dataView.getUint16(this.position,o??this.endianness);return this.position+=2,c},s.prototype.readUint8=function(){var o=this._dataView.getUint8(this.position);return this.position+=1,o},s.prototype.readFloat32=function(o){var c=this._dataView.getFloat32(this.position,o??this.endianness);return this.position+=4,c},s.prototype.readFloat64=function(o){var c=this._dataView.getFloat64(this.position,o??this.endianness);return this.position+=8,c},s.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>0,s.memcpy=function(o,c,f,m,S){var T=new Uint8Array(o,c,S),b=new Uint8Array(f,m,S);T.set(b)},s.arrayToNative=function(o,c){return c==this.endianness?o:this.flipArrayEndianness(o)},s.nativeToEndian=function(o,c){return this.endianness==c?o:this.flipArrayEndianness(o)},s.flipArrayEndianness=function(o){for(var c=new Uint8Array(o.buffer,o.byteOffset,o.byteLength),f=0;f<o.byteLength;f+=o.BYTES_PER_ELEMENT)for(var m=f+o.BYTES_PER_ELEMENT-1,S=f;m>S;m--,S++){var T=c[S];c[S]=c[m],c[m]=T}return o},s.prototype.failurePosition=0,String.fromCharCodeUint8=function(o){for(var c=[],f=0;f<o.length;f++)c[f]=o[f];return String.fromCharCode.apply(null,c)},s.prototype.readString=function(o,c){return c==null||c=="ASCII"?String.fromCharCodeUint8.apply(null,[this.mapUint8Array(o??this.byteLength-this.position)]):new TextDecoder(c).decode(this.mapUint8Array(o))},s.prototype.readCString=function(o){var c=this.byteLength-this.position,f=new Uint8Array(this._buffer,this._byteOffset+this.position),m=c;o!=null&&(m=Math.min(o,c));for(var S=0;S<m&&f[S]!==0;S++);var T=String.fromCharCodeUint8.apply(null,[this.mapUint8Array(S)]);return o!=null?this.position+=m-S:S!=c&&(this.position+=1),T};var n=Math.pow(2,32);s.prototype.readInt64=function(){return this.readInt32()*n+this.readUint32()},s.prototype.readUint64=function(){return this.readUint32()*n+this.readUint32()},s.prototype.readInt64=function(){return this.readUint32()*n+this.readUint32()},s.prototype.readUint24=function(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()},r.DataStream=s,s.prototype.save=function(o){var c=new Blob([this.buffer]);if(window.URL&&URL.createObjectURL){var f=window.URL.createObjectURL(c),m=document.createElement("a");document.body.appendChild(m),m.setAttribute("href",f),m.setAttribute("download",o),m.setAttribute("target","_self"),m.click(),window.URL.revokeObjectURL(f)}else throw"DataStream.save: Can't create object URL."},s.prototype._dynamicSize=!0,Object.defineProperty(s.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(o){o||this._trimAlloc(),this._dynamicSize=o}}),s.prototype.shift=function(o){var c=new ArrayBuffer(this._byteLength-o),f=new Uint8Array(c),m=new Uint8Array(this._buffer,o,f.length);f.set(m),this.buffer=c,this.position-=o},s.prototype.writeInt32Array=function(o,c){if(this._realloc(o.length*4),o instanceof Int32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt32Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeInt32(o[f],c)},s.prototype.writeInt16Array=function(o,c){if(this._realloc(o.length*2),o instanceof Int16Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt16Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeInt16(o[f],c)},s.prototype.writeInt8Array=function(o){if(this._realloc(o.length*1),o instanceof Int8Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt8Array(o.length);else for(var c=0;c<o.length;c++)this.writeInt8(o[c])},s.prototype.writeUint32Array=function(o,c){if(this._realloc(o.length*4),o instanceof Uint32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint32Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeUint32(o[f],c)},s.prototype.writeUint16Array=function(o,c){if(this._realloc(o.length*2),o instanceof Uint16Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint16Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeUint16(o[f],c)},s.prototype.writeUint8Array=function(o){if(this._realloc(o.length*1),o instanceof Uint8Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint8Array(o.length);else for(var c=0;c<o.length;c++)this.writeUint8(o[c])},s.prototype.writeFloat64Array=function(o,c){if(this._realloc(o.length*8),o instanceof Float64Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapFloat64Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeFloat64(o[f],c)},s.prototype.writeFloat32Array=function(o,c){if(this._realloc(o.length*4),o instanceof Float32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapFloat32Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeFloat32(o[f],c)},s.prototype.writeInt32=function(o,c){this._realloc(4),this._dataView.setInt32(this.position,o,c??this.endianness),this.position+=4},s.prototype.writeInt16=function(o,c){this._realloc(2),this._dataView.setInt16(this.position,o,c??this.endianness),this.position+=2},s.prototype.writeInt8=function(o){this._realloc(1),this._dataView.setInt8(this.position,o),this.position+=1},s.prototype.writeUint32=function(o,c){this._realloc(4),this._dataView.setUint32(this.position,o,c??this.endianness),this.position+=4},s.prototype.writeUint16=function(o,c){this._realloc(2),this._dataView.setUint16(this.position,o,c??this.endianness),this.position+=2},s.prototype.writeUint8=function(o){this._realloc(1),this._dataView.setUint8(this.position,o),this.position+=1},s.prototype.writeFloat32=function(o,c){this._realloc(4),this._dataView.setFloat32(this.position,o,c??this.endianness),this.position+=4},s.prototype.writeFloat64=function(o,c){this._realloc(8),this._dataView.setFloat64(this.position,o,c??this.endianness),this.position+=8},s.prototype.writeUCS2String=function(o,c,f){f==null&&(f=o.length);for(var m=0;m<o.length&&m<f;m++)this.writeUint16(o.charCodeAt(m),c);for(;m<f;m++)this.writeUint16(0)},s.prototype.writeString=function(o,c,f){var m=0;if(c==null||c=="ASCII")if(f!=null){var S=Math.min(o.length,f);for(m=0;m<S;m++)this.writeUint8(o.charCodeAt(m));for(;m<f;m++)this.writeUint8(0)}else for(m=0;m<o.length;m++)this.writeUint8(o.charCodeAt(m));else this.writeUint8Array(new TextEncoder(c).encode(o.substring(0,f)))},s.prototype.writeCString=function(o,c){var f=0;if(c!=null){var m=Math.min(o.length,c);for(f=0;f<m;f++)this.writeUint8(o.charCodeAt(f));for(;f<c;f++)this.writeUint8(0)}else{for(f=0;f<o.length;f++)this.writeUint8(o.charCodeAt(f));this.writeUint8(0)}},s.prototype.writeStruct=function(o,c){for(var f=0;f<o.length;f+=2){var m=o[f+1];this.writeType(m,c[o[f]],c)}},s.prototype.writeType=function(o,c,f){var m;if(typeof o=="function")return o(this,c);if(typeof o=="object"&&!(o instanceof Array))return o.set(this,c,f);var S=null,T="ASCII",b=this.position;switch(typeof o=="string"&&/:/.test(o)&&(m=o.split(":"),o=m[0],S=parseInt(m[1])),typeof o=="string"&&/,/.test(o)&&(m=o.split(","),o=m[0],T=parseInt(m[1])),o){case"uint8":this.writeUint8(c);break;case"int8":this.writeInt8(c);break;case"uint16":this.writeUint16(c,this.endianness);break;case"int16":this.writeInt16(c,this.endianness);break;case"uint32":this.writeUint32(c,this.endianness);break;case"int32":this.writeInt32(c,this.endianness);break;case"float32":this.writeFloat32(c,this.endianness);break;case"float64":this.writeFloat64(c,this.endianness);break;case"uint16be":this.writeUint16(c,s.BIG_ENDIAN);break;case"int16be":this.writeInt16(c,s.BIG_ENDIAN);break;case"uint32be":this.writeUint32(c,s.BIG_ENDIAN);break;case"int32be":this.writeInt32(c,s.BIG_ENDIAN);break;case"float32be":this.writeFloat32(c,s.BIG_ENDIAN);break;case"float64be":this.writeFloat64(c,s.BIG_ENDIAN);break;case"uint16le":this.writeUint16(c,s.LITTLE_ENDIAN);break;case"int16le":this.writeInt16(c,s.LITTLE_ENDIAN);break;case"uint32le":this.writeUint32(c,s.LITTLE_ENDIAN);break;case"int32le":this.writeInt32(c,s.LITTLE_ENDIAN);break;case"float32le":this.writeFloat32(c,s.LITTLE_ENDIAN);break;case"float64le":this.writeFloat64(c,s.LITTLE_ENDIAN);break;case"cstring":this.writeCString(c,S);break;case"string":this.writeString(c,T,S);break;case"u16string":this.writeUCS2String(c,this.endianness,S);break;case"u16stringle":this.writeUCS2String(c,s.LITTLE_ENDIAN,S);break;case"u16stringbe":this.writeUCS2String(c,s.BIG_ENDIAN,S);break;default:if(o.length==3){for(var A=o[1],I=0;I<c.length;I++)this.writeType(A,c[I]);break}else{this.writeStruct(o,c);break}}S!=null&&(this.position=b,this._realloc(S),this.position=b+S)},s.prototype.writeUint64=function(o){var c=Math.floor(o/n);this.writeUint32(c),this.writeUint32(o&4294967295)},s.prototype.writeUint24=function(o){this.writeUint8((o&16711680)>>16),this.writeUint8((o&65280)>>8),this.writeUint8(o&255)},s.prototype.adjustUint32=function(o,c){var f=this.position;this.seek(o),this.writeUint32(c),this.seek(f)},s.prototype.mapInt32Array=function(o,c){this._realloc(o*4);var f=new Int32Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*4,f},s.prototype.mapInt16Array=function(o,c){this._realloc(o*2);var f=new Int16Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*2,f},s.prototype.mapInt8Array=function(o){this._realloc(o*1);var c=new Int8Array(this._buffer,this.byteOffset+this.position,o);return this.position+=o*1,c},s.prototype.mapUint32Array=function(o,c){this._realloc(o*4);var f=new Uint32Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*4,f},s.prototype.mapUint16Array=function(o,c){this._realloc(o*2);var f=new Uint16Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*2,f},s.prototype.mapFloat64Array=function(o,c){this._realloc(o*8);var f=new Float64Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*8,f},s.prototype.mapFloat32Array=function(o,c){this._realloc(o*4);var f=new Float32Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*4,f};var a=function(o){this.buffers=[],this.bufferIndex=-1,o&&(this.insertBuffer(o),this.bufferIndex=0)};a.prototype=new s(new ArrayBuffer,0,s.BIG_ENDIAN),a.prototype.initialized=function(){var o;return this.bufferIndex>-1?!0:this.buffers.length>0?(o=this.buffers[0],o.fileStart===0?(this.buffer=o,this.bufferIndex=0,e.debug("MultiBufferStream","Stream ready for parsing"),!0):(e.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1)):(e.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1)},ArrayBuffer.concat=function(o,c){e.debug("ArrayBuffer","Trying to create a new buffer of size: "+(o.byteLength+c.byteLength));var f=new Uint8Array(o.byteLength+c.byteLength);return f.set(new Uint8Array(o),0),f.set(new Uint8Array(c),o.byteLength),f.buffer},a.prototype.reduceBuffer=function(o,c,f){var m;return m=new Uint8Array(f),m.set(new Uint8Array(o,c,f)),m.buffer.fileStart=o.fileStart+c,m.buffer.usedBytes=0,m.buffer},a.prototype.insertBuffer=function(o){for(var c=!0,f=0;f<this.buffers.length;f++){var m=this.buffers[f];if(o.fileStart<=m.fileStart){if(o.fileStart===m.fileStart)if(o.byteLength>m.byteLength){this.buffers.splice(f,1),f--;continue}else e.warn("MultiBufferStream","Buffer (fileStart: "+o.fileStart+" - Length: "+o.byteLength+") already appended, ignoring");else o.fileStart+o.byteLength<=m.fileStart||(o=this.reduceBuffer(o,0,m.fileStart-o.fileStart)),e.debug("MultiBufferStream","Appending new buffer (fileStart: "+o.fileStart+" - Length: "+o.byteLength+")"),this.buffers.splice(f,0,o),f===0&&(this.buffer=o);c=!1;break}else if(o.fileStart<m.fileStart+m.byteLength){var S=m.fileStart+m.byteLength-o.fileStart,T=o.byteLength-S;if(T>0)o=this.reduceBuffer(o,S,T);else{c=!1;break}}}c&&(e.debug("MultiBufferStream","Appending new buffer (fileStart: "+o.fileStart+" - Length: "+o.byteLength+")"),this.buffers.push(o),f===0&&(this.buffer=o))},a.prototype.logBufferLevel=function(o){var c,f,m,S,T=[],b,A="";for(m=0,S=0,c=0;c<this.buffers.length;c++)f=this.buffers[c],c===0?(b={},T.push(b),b.start=f.fileStart,b.end=f.fileStart+f.byteLength,A+="["+b.start+"-"):b.end===f.fileStart?b.end=f.fileStart+f.byteLength:(b={},b.start=f.fileStart,A+=T[T.length-1].end-1+"], ["+b.start+"-",b.end=f.fileStart+f.byteLength,T.push(b)),m+=f.usedBytes,S+=f.byteLength;T.length>0&&(A+=b.end-1+"]");var I=o?e.info:e.debug;this.buffers.length===0?I("MultiBufferStream","No more buffer in memory"):I("MultiBufferStream",""+this.buffers.length+" stored buffer(s) ("+m+"/"+S+" bytes), continuous ranges: "+A)},a.prototype.cleanBuffers=function(){var o,c;for(o=0;o<this.buffers.length;o++)c=this.buffers[o],c.usedBytes===c.byteLength&&(e.debug("MultiBufferStream","Removing buffer #"+o),this.buffers.splice(o,1),o--)},a.prototype.mergeNextBuffer=function(){var o;if(this.bufferIndex+1<this.buffers.length)if(o=this.buffers[this.bufferIndex+1],o.fileStart===this.buffer.fileStart+this.buffer.byteLength){var c=this.buffer.byteLength,f=this.buffer.usedBytes,m=this.buffer.fileStart;return this.buffers[this.bufferIndex]=ArrayBuffer.concat(this.buffer,o),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=f,this.buffer.fileStart=m,e.debug("ISOFile","Concatenating buffer for box parsing (length: "+c+"->"+this.buffer.byteLength+")"),!0}else return!1;else return!1},a.prototype.findPosition=function(o,c,f){var m,S=null,T=-1;for(o===!0?m=0:m=this.bufferIndex;m<this.buffers.length&&(S=this.buffers[m],S.fileStart<=c);){T=m,f&&(S.fileStart+S.byteLength<=c?S.usedBytes=S.byteLength:S.usedBytes=c-S.fileStart,this.logBufferLevel());m++}return T!==-1?(S=this.buffers[T],S.fileStart+S.byteLength>=c?(e.debug("MultiBufferStream","Found position in existing buffer #"+T),T):-1):-1},a.prototype.findEndContiguousBuf=function(o){var c,f,m,S=o!==void 0?o:this.bufferIndex;if(f=this.buffers[S],this.buffers.length>S+1)for(c=S+1;c<this.buffers.length&&(m=this.buffers[c],m.fileStart===f.fileStart+f.byteLength);c++)f=m;return f.fileStart+f.byteLength},a.prototype.getEndFilePositionAfter=function(o){var c=this.findPosition(!0,o,!1);return c!==-1?this.findEndContiguousBuf(c):o},a.prototype.addUsedBytes=function(o){this.buffer.usedBytes+=o,this.logBufferLevel()},a.prototype.setAllUsedBytes=function(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()},a.prototype.seek=function(o,c,f){var m;return m=this.findPosition(c,o,f),m!==-1?(this.buffer=this.buffers[m],this.bufferIndex=m,this.position=o-this.buffer.fileStart,e.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(e.debug("MultiBufferStream","Position "+o+" not found in buffered data"),!1)},a.prototype.getPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.position},a.prototype.getLength=function(){return this.byteLength},a.prototype.getEndPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.byteLength},r.MultiBufferStream=a;var h=function(){var o=3,c=4,f=5,m=6,S=[];S[o]="ES_Descriptor",S[c]="DecoderConfigDescriptor",S[f]="DecoderSpecificInfo",S[m]="SLConfigDescriptor",this.getDescriptorName=function(A){return S[A]};var T=this,b={};return this.parseOneDescriptor=function(A){var I=0,L,w,C;for(L=A.readUint8(),C=A.readUint8();C&128;)I=(I<<7)+(C&127),C=A.readUint8();return I=(I<<7)+(C&127),e.debug("MPEG4DescriptorParser","Found "+(S[L]||"Descriptor "+L)+", size "+I+" at position "+A.getPosition()),S[L]?w=new b[S[L]](I):w=new b.Descriptor(I),w.parse(A),w},b.Descriptor=function(A,I){this.tag=A,this.size=I,this.descs=[]},b.Descriptor.prototype.parse=function(A){this.data=A.readUint8Array(this.size)},b.Descriptor.prototype.findDescriptor=function(A){for(var I=0;I<this.descs.length;I++)if(this.descs[I].tag==A)return this.descs[I];return null},b.Descriptor.prototype.parseRemainingDescriptors=function(A){for(var I=A.position;A.position<I+this.size;){var L=T.parseOneDescriptor(A);this.descs.push(L)}},b.ES_Descriptor=function(A){b.Descriptor.call(this,o,A)},b.ES_Descriptor.prototype=new b.Descriptor,b.ES_Descriptor.prototype.parse=function(A){if(this.ES_ID=A.readUint16(),this.flags=A.readUint8(),this.size-=3,this.flags&128?(this.dependsOn_ES_ID=A.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,this.flags&64){var I=A.readUint8();this.URL=A.readString(I),this.size-=I+1}else this.URL="";this.flags&32?(this.OCR_ES_ID=A.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(A)},b.ES_Descriptor.prototype.getOTI=function(A){var I=this.findDescriptor(c);return I?I.oti:0},b.ES_Descriptor.prototype.getAudioConfig=function(A){var I=this.findDescriptor(c);if(!I)return null;var L=I.findDescriptor(f);if(L&&L.data){var w=(L.data[0]&248)>>3;return w===31&&L.data.length>=2&&(w=32+((L.data[0]&7)<<3)+((L.data[1]&224)>>5)),w}else return null},b.DecoderConfigDescriptor=function(A){b.Descriptor.call(this,c,A)},b.DecoderConfigDescriptor.prototype=new b.Descriptor,b.DecoderConfigDescriptor.prototype.parse=function(A){this.oti=A.readUint8(),this.streamType=A.readUint8(),this.upStream=(this.streamType>>1&1)!==0,this.streamType=this.streamType>>>2,this.bufferSize=A.readUint24(),this.maxBitrate=A.readUint32(),this.avgBitrate=A.readUint32(),this.size-=13,this.parseRemainingDescriptors(A)},b.DecoderSpecificInfo=function(A){b.Descriptor.call(this,f,A)},b.DecoderSpecificInfo.prototype=new b.Descriptor,b.SLConfigDescriptor=function(A){b.Descriptor.call(this,m,A)},b.SLConfigDescriptor.prototype=new b.Descriptor,this};r.MPEG4DescriptorParser=h;var l={ERR_INVALID_DATA:-1,ERR_NOT_ENOUGH_DATA:0,OK:1,BASIC_BOXES:[{type:"mdat",name:"MediaDataBox"},{type:"idat",name:"ItemDataBox"},{type:"free",name:"FreeSpaceBox"},{type:"skip",name:"FreeSpaceBox"},{type:"meco",name:"AdditionalMetadataContainerBox"},{type:"strk",name:"SubTrackBox"}],FULL_BOXES:[{type:"hmhd",name:"HintMediaHeaderBox"},{type:"nmhd",name:"NullMediaHeaderBox"},{type:"iods",name:"ObjectDescriptorBox"},{type:"xml ",name:"XMLBox"},{type:"bxml",name:"BinaryXMLBox"},{type:"ipro",name:"ItemProtectionBox"},{type:"mere",name:"MetaboxRelationBox"}],CONTAINER_BOXES:[[{type:"moov",name:"CompressedMovieBox"},["trak","pssh"]],[{type:"trak",name:"TrackBox"}],[{type:"edts",name:"EditBox"}],[{type:"mdia",name:"MediaBox"}],[{type:"minf",name:"MediaInformationBox"}],[{type:"dinf",name:"DataInformationBox"}],[{type:"stbl",name:"SampleTableBox"},["sgpd","sbgp"]],[{type:"mvex",name:"MovieExtendsBox"},["trex"]],[{type:"moof",name:"CompressedMovieFragmentBox"},["traf"]],[{type:"traf",name:"TrackFragmentBox"},["trun","sgpd","sbgp"]],[{type:"vttc",name:"VTTCueBox"}],[{type:"tref",name:"TrackReferenceBox"}],[{type:"iref",name:"ItemReferenceBox"}],[{type:"mfra",name:"MovieFragmentRandomAccessBox"},["tfra"]],[{type:"meco",name:"AdditionalMetadataContainerBox"}],[{type:"hnti",name:"trackhintinformation"}],[{type:"hinf",name:"hintstatisticsbox"}],[{type:"strk",name:"SubTrackBox"}],[{type:"strd",name:"SubTrackDefinitionBox"}],[{type:"sinf",name:"ProtectionSchemeInfoBox"}],[{type:"rinf",name:"RestrictedSchemeInfoBox"}],[{type:"schi",name:"SchemeInformationBox"}],[{type:"trgr",name:"TrackGroupBox"}],[{type:"udta",name:"UserDataBox"},["kind"]],[{type:"iprp",name:"ItemPropertiesBox"},["ipma"]],[{type:"ipco",name:"ItemPropertyContainerBox"}],[{type:"grpl",name:"GroupsListBox"}],[{type:"j2kH",name:"J2KHeaderInfoBox"}],[{type:"etyp",name:"ExtendedTypeBox"},["tyco"]]],boxCodes:[],fullBoxCodes:[],containerBoxCodes:[],sampleEntryCodes:{},sampleGroupEntryCodes:[],trackGroupTypes:[],UUIDBoxes:{},UUIDs:[],initialize:function(){l.FullBox.prototype=new l.Box,l.ContainerBox.prototype=new l.Box,l.SampleEntry.prototype=new l.Box,l.TrackGroupTypeBox.prototype=new l.FullBox,l.BASIC_BOXES.forEach(function(o){l.createBoxCtor(o.type,o.name)}),l.FULL_BOXES.forEach(function(o){l.createFullBoxCtor(o.type,o.name)}),l.CONTAINER_BOXES.forEach(function(o){l.createContainerBoxCtor(o[0].type,o[0].name,null,o[1])})},Box:function(o,c,f,m){this.type=o,this.box_name=f,this.size=c,this.uuid=m},FullBox:function(o,c,f,m){l.Box.call(this,o,c,f,m),this.flags=0,this.version=0},ContainerBox:function(o,c,f,m){l.Box.call(this,o,c,f,m),this.boxes=[]},SampleEntry:function(o,c,f,m){l.ContainerBox.call(this,o,c),this.hdr_size=f,this.start=m},SampleGroupEntry:function(o){this.grouping_type=o},TrackGroupTypeBox:function(o,c){l.FullBox.call(this,o,c)},createBoxCtor:function(o,c,f){l.boxCodes.push(o),l[o+"Box"]=function(m){l.Box.call(this,o,m,c)},l[o+"Box"].prototype=new l.Box,f&&(l[o+"Box"].prototype.parse=f)},createFullBoxCtor:function(o,c,f){l[o+"Box"]=function(m){l.FullBox.call(this,o,m,c)},l[o+"Box"].prototype=new l.FullBox,l[o+"Box"].prototype.parse=function(m){this.parseFullHeader(m),f&&f.call(this,m)}},addSubBoxArrays:function(o){if(o){this.subBoxNames=o;for(var c=o.length,f=0;f<c;f++)this[o[f]+"s"]=[]}},createContainerBoxCtor:function(o,c,f,m){l[o+"Box"]=function(S){l.ContainerBox.call(this,o,S,c),l.addSubBoxArrays.call(this,m)},l[o+"Box"].prototype=new l.ContainerBox,f&&(l[o+"Box"].prototype.parse=f)},createMediaSampleEntryCtor:function(o,c,f){l.sampleEntryCodes[o]=[],l[o+"SampleEntry"]=function(m,S){l.SampleEntry.call(this,m,S),l.addSubBoxArrays.call(this,f)},l[o+"SampleEntry"].prototype=new l.SampleEntry,c&&(l[o+"SampleEntry"].prototype.parse=c)},createSampleEntryCtor:function(o,c,f,m){l.sampleEntryCodes[o].push(c),l[c+"SampleEntry"]=function(S){l[o+"SampleEntry"].call(this,c,S),l.addSubBoxArrays.call(this,m)},l[c+"SampleEntry"].prototype=new l[o+"SampleEntry"],f&&(l[c+"SampleEntry"].prototype.parse=f)},createEncryptedSampleEntryCtor:function(o,c,f){l.createSampleEntryCtor.call(this,o,c,f,["sinf"])},createSampleGroupCtor:function(o,c){l[o+"SampleGroupEntry"]=function(f){l.SampleGroupEntry.call(this,o,f)},l[o+"SampleGroupEntry"].prototype=new l.SampleGroupEntry,c&&(l[o+"SampleGroupEntry"].prototype.parse=c)},createTrackGroupCtor:function(o,c){l[o+"TrackGroupTypeBox"]=function(f){l.TrackGroupTypeBox.call(this,o,f)},l[o+"TrackGroupTypeBox"].prototype=new l.TrackGroupTypeBox,c&&(l[o+"TrackGroupTypeBox"].prototype.parse=c)},createUUIDBox:function(o,c,f,m,S){l.UUIDs.push(o),l.UUIDBoxes[o]=function(T){f?l.FullBox.call(this,"uuid",T,c,o):m?l.ContainerBox.call(this,"uuid",T,c,o):l.Box.call(this,"uuid",T,c,o)},l.UUIDBoxes[o].prototype=f?new l.FullBox:m?new l.ContainerBox:new l.Box,S&&(f?l.UUIDBoxes[o].prototype.parse=function(T){this.parseFullHeader(T),S&&S.call(this,T)}:l.UUIDBoxes[o].prototype.parse=S)}};l.initialize(),l.TKHD_FLAG_ENABLED=1,l.TKHD_FLAG_IN_MOVIE=2,l.TKHD_FLAG_IN_PREVIEW=4,l.TFHD_FLAG_BASE_DATA_OFFSET=1,l.TFHD_FLAG_SAMPLE_DESC=2,l.TFHD_FLAG_SAMPLE_DUR=8,l.TFHD_FLAG_SAMPLE_SIZE=16,l.TFHD_FLAG_SAMPLE_FLAGS=32,l.TFHD_FLAG_DUR_EMPTY=65536,l.TFHD_FLAG_DEFAULT_BASE_IS_MOOF=131072,l.TRUN_FLAGS_DATA_OFFSET=1,l.TRUN_FLAGS_FIRST_FLAG=4,l.TRUN_FLAGS_DURATION=256,l.TRUN_FLAGS_SIZE=512,l.TRUN_FLAGS_FLAGS=1024,l.TRUN_FLAGS_CTS_OFFSET=2048,l.Box.prototype.add=function(o){return this.addBox(new l[o+"Box"])},l.Box.prototype.addBox=function(o){return this.boxes.push(o),this[o.type+"s"]?this[o.type+"s"].push(o):this[o.type]=o,o},l.Box.prototype.set=function(o,c){return this[o]=c,this},l.Box.prototype.addEntry=function(o,c){var f=c||"entries";return this[f]||(this[f]=[]),this[f].push(o),this},r.BoxParser=l,l.parseUUID=function(o){return l.parseHex16(o)},l.parseHex16=function(o){for(var c="",f=0;f<16;f++){var m=o.readUint8().toString(16);c+=m.length===1?"0"+m:m}return c},l.parseOneBox=function(o,c,f){var m,S=o.getPosition(),T=0,b,A;if(o.getEndPosition()-S<8)return e.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:l.ERR_NOT_ENOUGH_DATA};if(f&&f<8)return e.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:l.ERR_NOT_ENOUGH_DATA};var I=o.readUint32(),L=o.readString(4),w=L;if(e.debug("BoxParser","Found box of type '"+L+"' and size "+I+" at position "+S),T=8,L=="uuid"){if(o.getEndPosition()-o.getPosition()<16||f-T<16)return o.seek(S),e.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:l.ERR_NOT_ENOUGH_DATA};A=l.parseUUID(o),T+=16,w=A}if(I==1){if(o.getEndPosition()-o.getPosition()<8||f&&f-T<8)return o.seek(S),e.warn("BoxParser",'Not enough data in stream to parse the extended size of the "'+L+'" box'),{code:l.ERR_NOT_ENOUGH_DATA};I=o.readUint64(),T+=8}else if(I===0){if(f)I=f;else if(L!=="mdat")return e.error("BoxParser","Unlimited box size not supported for type: '"+L+"'"),m=new l.Box(L,I),{code:l.OK,box:m,size:m.size}}return I!==0&&I<T?(e.error("BoxParser","Box of type "+L+" has an invalid size "+I+" (too small to be a box)"),{code:l.ERR_NOT_ENOUGH_DATA,type:L,size:I,hdr_size:T,start:S}):I!==0&&f&&I>f?(e.error("BoxParser","Box of type '"+L+"' has a size "+I+" greater than its container size "+f),{code:l.ERR_NOT_ENOUGH_DATA,type:L,size:I,hdr_size:T,start:S}):I!==0&&S+I>o.getEndPosition()?(o.seek(S),e.info("BoxParser","Not enough data in stream to parse the entire '"+L+"' box"),{code:l.ERR_NOT_ENOUGH_DATA,type:L,size:I,hdr_size:T,start:S}):c?{code:l.OK,type:L,size:I,hdr_size:T,start:S}:(l[L+"Box"]?m=new l[L+"Box"](I):L!=="uuid"?(e.warn("BoxParser","Unknown box type: '"+L+"'"),m=new l.Box(L,I),m.has_unparsed_data=!0):l.UUIDBoxes[A]?m=new l.UUIDBoxes[A](I):(e.warn("BoxParser","Unknown uuid type: '"+A+"'"),m=new l.Box(L,I),m.uuid=A,m.has_unparsed_data=!0),m.hdr_size=T,m.start=S,m.write===l.Box.prototype.write&&m.type!=="mdat"&&(e.info("BoxParser","'"+w+"' box writing not yet implemented, keeping unparsed data in memory for later write"),m.parseDataAndRewind(o)),m.parse(o),b=o.getPosition()-(m.start+m.size),b<0?(e.warn("BoxParser","Parsing of box '"+w+"' did not read the entire indicated box data size (missing "+-b+" bytes), seeking forward"),o.seek(m.start+m.size)):b>0&&(e.error("BoxParser","Parsing of box '"+w+"' read "+b+" more bytes than the indicated box data size, seeking backwards"),m.size!==0&&o.seek(m.start+m.size)),{code:l.OK,box:m,size:m.size})},l.Box.prototype.parse=function(o){this.type!="mdat"?this.data=o.readUint8Array(this.size-this.hdr_size):this.size===0?o.seek(o.getEndPosition()):o.seek(this.start+this.size)},l.Box.prototype.parseDataAndRewind=function(o){this.data=o.readUint8Array(this.size-this.hdr_size),o.position-=this.size-this.hdr_size},l.FullBox.prototype.parseDataAndRewind=function(o){this.parseFullHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,o.position-=this.size-this.hdr_size},l.FullBox.prototype.parseFullHeader=function(o){this.version=o.readUint8(),this.flags=o.readUint24(),this.hdr_size+=4},l.FullBox.prototype.parse=function(o){this.parseFullHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size)},l.ContainerBox.prototype.parse=function(o){for(var c,f;o.getPosition()<this.start+this.size;)if(c=l.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),c.code===l.OK)if(f=c.box,this.boxes.push(f),this.subBoxNames&&this.subBoxNames.indexOf(f.type)!=-1)this[this.subBoxNames[this.subBoxNames.indexOf(f.type)]+"s"].push(f);else{var m=f.type!=="uuid"?f.type:f.uuid;this[m]?e.warn("Box of type "+m+" already stored in field of this type"):this[m]=f}else return},l.Box.prototype.parseLanguage=function(o){this.language=o.readUint16();var c=[];c[0]=this.language>>10&31,c[1]=this.language>>5&31,c[2]=this.language&31,this.languageString=String.fromCharCode(c[0]+96,c[1]+96,c[2]+96)},l.SAMPLE_ENTRY_TYPE_VISUAL="Visual",l.SAMPLE_ENTRY_TYPE_AUDIO="Audio",l.SAMPLE_ENTRY_TYPE_HINT="Hint",l.SAMPLE_ENTRY_TYPE_METADATA="Metadata",l.SAMPLE_ENTRY_TYPE_SUBTITLE="Subtitle",l.SAMPLE_ENTRY_TYPE_SYSTEM="System",l.SAMPLE_ENTRY_TYPE_TEXT="Text",l.SampleEntry.prototype.parseHeader=function(o){o.readUint8Array(6),this.data_reference_index=o.readUint16(),this.hdr_size+=8},l.SampleEntry.prototype.parse=function(o){this.parseHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size)},l.SampleEntry.prototype.parseDataAndRewind=function(o){this.parseHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,o.position-=this.size-this.hdr_size},l.SampleEntry.prototype.parseFooter=function(o){l.ContainerBox.prototype.parse.call(this,o)},l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_HINT),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_METADATA),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SYSTEM),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_TEXT),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,function(o){var c;this.parseHeader(o),o.readUint16(),o.readUint16(),o.readUint32Array(3),this.width=o.readUint16(),this.height=o.readUint16(),this.horizresolution=o.readUint32(),this.vertresolution=o.readUint32(),o.readUint32(),this.frame_count=o.readUint16(),c=Math.min(31,o.readUint8()),this.compressorname=o.readString(c),c<31&&o.readString(31-c),this.depth=o.readUint16(),o.readUint16(),this.parseFooter(o)}),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,function(o){this.parseHeader(o),o.readUint32Array(2),this.channel_count=o.readUint16(),this.samplesize=o.readUint16(),o.readUint16(),o.readUint16(),this.samplerate=o.readUint32()/65536,this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"avc1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"avc2"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"avc3"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"avc4"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"av01"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"dav1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"hvc1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"hev1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"hvt1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"lhe1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"dvh1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"dvhe"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vvc1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vvi1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vvs1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vvcN"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vp08"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vp09"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"avs3"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"j2ki"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"mjp2"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"mjpg"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"uncv"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"mp4a"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"ac-3"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"ac-4"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"ec-3"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"Opus"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"mha1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"mha2"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"mhm1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"mhm2"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"fLaC"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"encv"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"enca"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE,"encu"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SYSTEM,"encs"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_TEXT,"enct"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_METADATA,"encm"),l.createBoxCtor("a1lx","AV1LayeredImageIndexingProperty",function(o){var c=o.readUint8()&1,f=((c&1)+1)*16;this.layer_size=[];for(var m=0;m<3;m++)f==16?this.layer_size[m]=o.readUint16():this.layer_size[m]=o.readUint32()}),l.createBoxCtor("a1op","OperatingPointSelectorProperty",function(o){this.op_index=o.readUint8()}),l.createFullBoxCtor("auxC","AuxiliaryTypeProperty",function(o){this.aux_type=o.readCString();var c=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=o.readUint8Array(c)}),l.createBoxCtor("av1C","AV1CodecConfigurationBox",function(o){var c=o.readUint8();if((c>>7&1)!==1){e.error("av1C marker problem");return}if(this.version=c&127,this.version!==1){e.error("av1C version "+this.version+" not supported");return}if(c=o.readUint8(),this.seq_profile=c>>5&7,this.seq_level_idx_0=c&31,c=o.readUint8(),this.seq_tier_0=c>>7&1,this.high_bitdepth=c>>6&1,this.twelve_bit=c>>5&1,this.monochrome=c>>4&1,this.chroma_subsampling_x=c>>3&1,this.chroma_subsampling_y=c>>2&1,this.chroma_sample_position=c&3,c=o.readUint8(),this.reserved_1=c>>5&7,this.reserved_1!==0){e.error("av1C reserved_1 parsing problem");return}if(this.initial_presentation_delay_present=c>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=c&15;else if(this.reserved_2=c&15,this.reserved_2!==0){e.error("av1C reserved_2 parsing problem");return}var f=this.size-this.hdr_size-4;this.configOBUs=o.readUint8Array(f)});function u(o){var c="<table class='inner-table'>";c+="<thead><tr><th>length</th><th>nalu_data</th></tr></thead>",c+="<tbody>";for(var f=0;f<o.length;f++){var m=o[f];c+="<tr>",c+="<td>"+m.length+"</td>",c+="<td>",c+=m.nalu.reduce(function(S,T){return S+T.toString(16).padStart(2,"0")},"0x"),c+="</td></tr>"}return c+="</tbody></table>",c}l.createBoxCtor("avcC","AVCConfigurationBox",function(o){var c,f;for(this.configurationVersion=o.readUint8(),this.AVCProfileIndication=o.readUint8(),this.profile_compatibility=o.readUint8(),this.AVCLevelIndication=o.readUint8(),this.lengthSizeMinusOne=o.readUint8()&3,this.nb_SPS_nalus=o.readUint8()&31,f=this.size-this.hdr_size-6,this.SPS=[],this.SPS.toString=function(){return u(this)},c=0;c<this.nb_SPS_nalus;c++)this.SPS[c]={},this.SPS[c].length=o.readUint16(),this.SPS[c].nalu=o.readUint8Array(this.SPS[c].length),f-=2+this.SPS[c].length;for(this.nb_PPS_nalus=o.readUint8(),f--,this.PPS=[],this.PPS.toString=function(){return u(this)},c=0;c<this.nb_PPS_nalus;c++)this.PPS[c]={},this.PPS[c].length=o.readUint16(),this.PPS[c].nalu=o.readUint8Array(this.PPS[c].length),f-=2+this.PPS[c].length;f>0&&(this.ext=o.readUint8Array(f))}),l.createBoxCtor("btrt","BitRateBox",function(o){this.bufferSizeDB=o.readUint32(),this.maxBitrate=o.readUint32(),this.avgBitrate=o.readUint32()}),l.createFullBoxCtor("ccst","CodingConstraintsBox",function(o){var c=o.readUint8();this.all_ref_pics_intra=(c&128)==128,this.intra_pred_used=(c&64)==64,this.max_ref_per_pic=(c&63)>>2,o.readUint24()}),l.createBoxCtor("cdef","ComponentDefinitionBox",function(o){var c;for(this.channel_count=o.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[],c=0;c<this.channel_count;c++)this.channel_indexes.push(o.readUint16()),this.channel_types.push(o.readUint16()),this.channel_associations.push(o.readUint16())}),l.createBoxCtor("clap","CleanApertureBox",function(o){this.cleanApertureWidthN=o.readUint32(),this.cleanApertureWidthD=o.readUint32(),this.cleanApertureHeightN=o.readUint32(),this.cleanApertureHeightD=o.readUint32(),this.horizOffN=o.readUint32(),this.horizOffD=o.readUint32(),this.vertOffN=o.readUint32(),this.vertOffD=o.readUint32()}),l.createBoxCtor("clli","ContentLightLevelBox",function(o){this.max_content_light_level=o.readUint16(),this.max_pic_average_light_level=o.readUint16()}),l.createFullBoxCtor("cmex","CameraExtrinsicMatrixProperty",function(o){this.flags&1&&(this.pos_x=o.readInt32()),this.flags&2&&(this.pos_y=o.readInt32()),this.flags&4&&(this.pos_z=o.readInt32()),this.flags&8&&(this.version==0?this.flags&16?(this.quat_x=o.readInt32(),this.quat_y=o.readInt32(),this.quat_z=o.readInt32()):(this.quat_x=o.readInt16(),this.quat_y=o.readInt16(),this.quat_z=o.readInt16()):this.version==1),this.flags&32&&(this.id=o.readUint32())}),l.createFullBoxCtor("cmin","CameraIntrinsicMatrixProperty",function(o){this.focal_length_x=o.readInt32(),this.principal_point_x=o.readInt32(),this.principal_point_y=o.readInt32(),this.flags&1&&(this.focal_length_y=o.readInt32(),this.skew_factor=o.readInt32())}),l.createBoxCtor("cmpd","ComponentDefinitionBox",function(o){for(this.component_count=o.readUint32(),this.component_types=[],this.component_type_urls=[],i=0;i<this.component_count;i++){var c=o.readUint16();this.component_types.push(c),c>=32768&&this.component_type_urls.push(o.readCString())}}),l.createFullBoxCtor("co64","ChunkLargeOffsetBox",function(o){var c,f;if(c=o.readUint32(),this.chunk_offsets=[],this.version===0)for(f=0;f<c;f++)this.chunk_offsets.push(o.readUint64())}),l.createFullBoxCtor("CoLL","ContentLightLevelBox",function(o){this.maxCLL=o.readUint16(),this.maxFALL=o.readUint16()}),l.createBoxCtor("colr","ColourInformationBox",function(o){if(this.colour_type=o.readString(4),this.colour_type==="nclx"){this.colour_primaries=o.readUint16(),this.transfer_characteristics=o.readUint16(),this.matrix_coefficients=o.readUint16();var c=o.readUint8();this.full_range_flag=c>>7}else this.colour_type==="rICC"?this.ICC_profile=o.readUint8Array(this.size-4):this.colour_type==="prof"&&(this.ICC_profile=o.readUint8Array(this.size-4))}),l.createFullBoxCtor("cprt","CopyrightBox",function(o){this.parseLanguage(o),this.notice=o.readCString()}),l.createFullBoxCtor("cslg","CompositionToDecodeBox",function(o){this.version===0&&(this.compositionToDTSShift=o.readInt32(),this.leastDecodeToDisplayDelta=o.readInt32(),this.greatestDecodeToDisplayDelta=o.readInt32(),this.compositionStartTime=o.readInt32(),this.compositionEndTime=o.readInt32())}),l.createFullBoxCtor("ctts","CompositionOffsetBox",function(o){var c,f;if(c=o.readUint32(),this.sample_counts=[],this.sample_offsets=[],this.version===0)for(f=0;f<c;f++){this.sample_counts.push(o.readUint32());var m=o.readInt32();m<0&&e.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(m)}else if(this.version==1)for(f=0;f<c;f++)this.sample_counts.push(o.readUint32()),this.sample_offsets.push(o.readInt32())}),l.createBoxCtor("dac3","AC3SpecificBox",function(o){var c=o.readUint8(),f=o.readUint8(),m=o.readUint8();this.fscod=c>>6,this.bsid=c>>1&31,this.bsmod=(c&1)<<2|f>>6&3,this.acmod=f>>3&7,this.lfeon=f>>2&1,this.bit_rate_code=f&3|m>>5&7}),l.createBoxCtor("dec3","EC3SpecificBox",function(o){var c=o.readUint16();this.data_rate=c>>3,this.num_ind_sub=c&7,this.ind_subs=[];for(var f=0;f<this.num_ind_sub+1;f++){var m={};this.ind_subs.push(m);var S=o.readUint8(),T=o.readUint8(),b=o.readUint8();m.fscod=S>>6,m.bsid=S>>1&31,m.bsmod=(S&1)<<4|T>>4&15,m.acmod=T>>1&7,m.lfeon=T&1,m.num_dep_sub=b>>1&15,m.num_dep_sub>0&&(m.chan_loc=(b&1)<<8|o.readUint8())}}),l.createFullBoxCtor("dfLa","FLACSpecificBox",function(o){var c=127,f=128,m=[],S=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];do{var T=o.readUint8(),b=Math.min(T&c,S.length-1);if(b?o.readUint8Array(o.readUint24()):(o.readUint8Array(13),this.samplerate=o.readUint32()>>12,o.readUint8Array(20)),m.push(S[b]),T&f)break}while(!0);this.numMetadataBlocks=m.length+" ("+m.join(", ")+")"}),l.createBoxCtor("dimm","hintimmediateBytesSent",function(o){this.bytessent=o.readUint64()}),l.createBoxCtor("dmax","hintlongestpacket",function(o){this.time=o.readUint32()}),l.createBoxCtor("dmed","hintmediaBytesSent",function(o){this.bytessent=o.readUint64()}),l.createBoxCtor("dOps","OpusSpecificBox",function(o){if(this.Version=o.readUint8(),this.OutputChannelCount=o.readUint8(),this.PreSkip=o.readUint16(),this.InputSampleRate=o.readUint32(),this.OutputGain=o.readInt16(),this.ChannelMappingFamily=o.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=o.readUint8(),this.CoupledCount=o.readUint8(),this.ChannelMapping=[];for(var c=0;c<this.OutputChannelCount;c++)this.ChannelMapping[c]=o.readUint8()}}),l.createFullBoxCtor("dref","DataReferenceBox",function(o){var c,f;this.entries=[];for(var m=o.readUint32(),S=0;S<m;S++)if(c=l.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),c.code===l.OK)f=c.box,this.entries.push(f);else return}),l.createBoxCtor("drep","hintrepeatedBytesSent",function(o){this.bytessent=o.readUint64()}),l.createFullBoxCtor("elng","ExtendedLanguageBox",function(o){this.extended_language=o.readString(this.size-this.hdr_size)}),l.createFullBoxCtor("elst","EditListBox",function(o){this.entries=[];for(var c=o.readUint32(),f=0;f<c;f++){var m={};this.entries.push(m),this.version===1?(m.segment_duration=o.readUint64(),m.media_time=o.readInt64()):(m.segment_duration=o.readUint32(),m.media_time=o.readInt32()),m.media_rate_integer=o.readInt16(),m.media_rate_fraction=o.readInt16()}}),l.createFullBoxCtor("emsg","EventMessageBox",function(o){this.version==1?(this.timescale=o.readUint32(),this.presentation_time=o.readUint64(),this.event_duration=o.readUint32(),this.id=o.readUint32(),this.scheme_id_uri=o.readCString(),this.value=o.readCString()):(this.scheme_id_uri=o.readCString(),this.value=o.readCString(),this.timescale=o.readUint32(),this.presentation_time_delta=o.readUint32(),this.event_duration=o.readUint32(),this.id=o.readUint32());var c=this.size-this.hdr_size-(4*4+(this.scheme_id_uri.length+1)+(this.value.length+1));this.version==1&&(c-=4),this.message_data=o.readUint8Array(c)}),l.createEntityToGroupCtor=function(o,c){l[o+"Box"]=function(f){l.FullBox.call(this,o,f)},l[o+"Box"].prototype=new l.FullBox,l[o+"Box"].prototype.parse=function(f){if(this.parseFullHeader(f),c)c.call(this,f);else for(this.group_id=f.readUint32(),this.num_entities_in_group=f.readUint32(),this.entity_ids=[],i=0;i<this.num_entities_in_group;i++){var m=f.readUint32();this.entity_ids.push(m)}}},l.createEntityToGroupCtor("aebr"),l.createEntityToGroupCtor("afbr"),l.createEntityToGroupCtor("albc"),l.createEntityToGroupCtor("altr"),l.createEntityToGroupCtor("brst"),l.createEntityToGroupCtor("dobr"),l.createEntityToGroupCtor("eqiv"),l.createEntityToGroupCtor("favc"),l.createEntityToGroupCtor("fobr"),l.createEntityToGroupCtor("iaug"),l.createEntityToGroupCtor("pano"),l.createEntityToGroupCtor("slid"),l.createEntityToGroupCtor("ster"),l.createEntityToGroupCtor("tsyn"),l.createEntityToGroupCtor("wbbr"),l.createEntityToGroupCtor("prgr"),l.createEntityToGroupCtor("pymd",function(o){this.group_id=o.readUint32(),this.num_entities_in_group=o.readUint32(),this.entity_ids=[];for(var c=0;c<this.num_entities_in_group;c++){var f=o.readUint32();this.entity_ids.push(f)}for(this.tile_size_x=o.readUint16(),this.tile_size_y=o.readUint16(),this.layer_binning=[],this.tiles_in_layer_column_minus1=[],this.tiles_in_layer_row_minus1=[],c=0;c<this.num_entities_in_group;c++)this.layer_binning[c]=o.readUint16(),this.tiles_in_layer_row_minus1[c]=o.readUint16(),this.tiles_in_layer_column_minus1[c]=o.readUint16()}),l.createFullBoxCtor("esds","ElementaryStreamDescriptorBox",function(o){var c=o.readUint8Array(this.size-this.hdr_size);if(typeof h<"u"){var f=new h;this.esd=f.parseOneDescriptor(new s(c.buffer,0,s.BIG_ENDIAN))}}),l.createBoxCtor("fiel","FieldHandlingBox",function(o){this.fieldCount=o.readUint8(),this.fieldOrdering=o.readUint8()}),l.createBoxCtor("frma","OriginalFormatBox",function(o){this.data_format=o.readString(4)}),l.createBoxCtor("ftyp","FileTypeBox",function(o){var c=this.size-this.hdr_size;this.major_brand=o.readString(4),this.minor_version=o.readUint32(),c-=8,this.compatible_brands=[];for(var f=0;c>=4;)this.compatible_brands[f]=o.readString(4),c-=4,f++}),l.createFullBoxCtor("hdlr","HandlerBox",function(o){this.version===0&&(o.readUint32(),this.handler=o.readString(4),o.readUint32Array(3),this.name=o.readString(this.size-this.hdr_size-20),this.name[this.name.length-1]==="\0"&&(this.name=this.name.slice(0,-1)))}),l.createBoxCtor("hvcC","HEVCConfigurationBox",function(o){var c,f,m,S;this.configurationVersion=o.readUint8(),S=o.readUint8(),this.general_profile_space=S>>6,this.general_tier_flag=(S&32)>>5,this.general_profile_idc=S&31,this.general_profile_compatibility=o.readUint32(),this.general_constraint_indicator=o.readUint8Array(6),this.general_level_idc=o.readUint8(),this.min_spatial_segmentation_idc=o.readUint16()&4095,this.parallelismType=o.readUint8()&3,this.chroma_format_idc=o.readUint8()&3,this.bit_depth_luma_minus8=o.readUint8()&7,this.bit_depth_chroma_minus8=o.readUint8()&7,this.avgFrameRate=o.readUint16(),S=o.readUint8(),this.constantFrameRate=S>>6,this.numTemporalLayers=(S&13)>>3,this.temporalIdNested=(S&4)>>2,this.lengthSizeMinusOne=S&3,this.nalu_arrays=[],this.nalu_arrays.toString=function(){var L="<table class='inner-table'>";L+="<thead><tr><th>completeness</th><th>nalu_type</th><th>nalu_data</th></tr></thead>",L+="<tbody>";for(var w=0;w<this.length;w++){var C=this[w];L+="<tr>",L+="<td rowspan='"+C.length+"'>"+C.completeness+"</td>",L+="<td rowspan='"+C.length+"'>"+C.nalu_type+"</td>";for(var k=0;k<C.length;k++){var U=C[k];k!==0&&(L+="<tr>"),L+="<td>",L+=U.data.reduce(function(G,$){return G+$.toString(16).padStart(2,"0")},"0x"),L+="</td></tr>"}}return L+="</tbody></table>",L};var T=o.readUint8();for(c=0;c<T;c++){var b=[];this.nalu_arrays.push(b),S=o.readUint8(),b.completeness=(S&128)>>7,b.nalu_type=S&63;var A=o.readUint16();for(f=0;f<A;f++){var I={};b.push(I),m=o.readUint16(),I.data=o.readUint8Array(m)}}}),l.createFullBoxCtor("iinf","ItemInfoBox",function(o){var c;this.version===0?this.entry_count=o.readUint16():this.entry_count=o.readUint32(),this.item_infos=[];for(var f=0;f<this.entry_count;f++)if(c=l.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),c.code===l.OK)c.box.type!=="infe"&&e.error("BoxParser","Expected 'infe' box, got "+c.box.type),this.item_infos[f]=c.box;else return}),l.createFullBoxCtor("iloc","ItemLocationBox",function(o){var c;c=o.readUint8(),this.offset_size=c>>4&15,this.length_size=c&15,c=o.readUint8(),this.base_offset_size=c>>4&15,this.version===1||this.version===2?this.index_size=c&15:this.index_size=0,this.items=[];var f=0;if(this.version<2)f=o.readUint16();else if(this.version===2)f=o.readUint32();else throw"version of iloc box not supported";for(var m=0;m<f;m++){var S={};if(this.items.push(S),this.version<2)S.item_ID=o.readUint16();else if(this.version===2)S.item_ID=o.readUint32();else throw"version of iloc box not supported";switch(this.version===1||this.version===2?S.construction_method=o.readUint16()&15:S.construction_method=0,S.data_reference_index=o.readUint16(),this.base_offset_size){case 0:S.base_offset=0;break;case 4:S.base_offset=o.readUint32();break;case 8:S.base_offset=o.readUint64();break;default:throw"Error reading base offset size"}var T=o.readUint16();S.extents=[];for(var b=0;b<T;b++){var A={};if(S.extents.push(A),this.version===1||this.version===2)switch(this.index_size){case 0:A.extent_index=0;break;case 4:A.extent_index=o.readUint32();break;case 8:A.extent_index=o.readUint64();break;default:throw"Error reading extent index"}switch(this.offset_size){case 0:A.extent_offset=0;break;case 4:A.extent_offset=o.readUint32();break;case 8:A.extent_offset=o.readUint64();break;default:throw"Error reading extent index"}switch(this.length_size){case 0:A.extent_length=0;break;case 4:A.extent_length=o.readUint32();break;case 8:A.extent_length=o.readUint64();break;default:throw"Error reading extent index"}}}}),l.createBoxCtor("imir","ImageMirror",function(o){var c=o.readUint8();this.reserved=c>>7,this.axis=c&1}),l.createFullBoxCtor("infe","ItemInfoEntry",function(o){if((this.version===0||this.version===1)&&(this.item_ID=o.readUint16(),this.item_protection_index=o.readUint16(),this.item_name=o.readCString(),this.content_type=o.readCString(),this.content_encoding=o.readCString()),this.version===1){this.extension_type=o.readString(4),e.warn("BoxParser","Cannot parse extension type"),o.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=o.readUint16():this.version===3&&(this.item_ID=o.readUint32()),this.item_protection_index=o.readUint16(),this.item_type=o.readString(4),this.item_name=o.readCString(),this.item_type==="mime"?(this.content_type=o.readCString(),this.content_encoding=o.readCString()):this.item_type==="uri "&&(this.item_uri_type=o.readCString()))}),l.createFullBoxCtor("ipma","ItemPropertyAssociationBox",function(o){var c,f;for(entry_count=o.readUint32(),this.associations=[],c=0;c<entry_count;c++){var m={};this.associations.push(m),this.version<1?m.id=o.readUint16():m.id=o.readUint32();var S=o.readUint8();for(m.props=[],f=0;f<S;f++){var T=o.readUint8(),b={};m.props.push(b),b.essential=(T&128)>>7===1,this.flags&1?b.property_index=(T&127)<<8|o.readUint8():b.property_index=T&127}}}),l.createFullBoxCtor("iref","ItemReferenceBox",function(o){var c,f;for(this.references=[];o.getPosition()<this.start+this.size;)if(c=l.parseOneBox(o,!0,this.size-(o.getPosition()-this.start)),c.code===l.OK)this.version===0?f=new l.SingleItemTypeReferenceBox(c.type,c.size,c.hdr_size,c.start):f=new l.SingleItemTypeReferenceBoxLarge(c.type,c.size,c.hdr_size,c.start),f.write===l.Box.prototype.write&&f.type!=="mdat"&&(e.warn("BoxParser",f.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),f.parseDataAndRewind(o)),f.parse(o),this.references.push(f);else return}),l.createBoxCtor("irot","ImageRotation",function(o){this.angle=o.readUint8()&3}),l.createFullBoxCtor("ispe","ImageSpatialExtentsProperty",function(o){this.image_width=o.readUint32(),this.image_height=o.readUint32()}),l.createFullBoxCtor("kind","KindBox",function(o){this.schemeURI=o.readCString(),this.value=o.readCString()}),l.createFullBoxCtor("leva","LevelAssignmentBox",function(o){var c=o.readUint8();this.levels=[];for(var f=0;f<c;f++){var m={};this.levels[f]=m,m.track_ID=o.readUint32();var S=o.readUint8();switch(m.padding_flag=S>>7,m.assignment_type=S&127,m.assignment_type){case 0:m.grouping_type=o.readString(4);break;case 1:m.grouping_type=o.readString(4),m.grouping_type_parameter=o.readUint32();break;case 2:break;case 3:break;case 4:m.sub_track_id=o.readUint32();break;default:e.warn("BoxParser","Unknown leva assignement type")}}}),l.createBoxCtor("lhvC","LHEVCConfigurationBox",function(o){var c,f,m;this.configurationVersion=o.readUint8(),this.min_spatial_segmentation_idc=o.readUint16()&4095,this.parallelismType=o.readUint8()&3,m=o.readUint8(),this.numTemporalLayers=(m&13)>>3,this.temporalIdNested=(m&4)>>2,this.lengthSizeMinusOne=m&3,this.nalu_arrays=[],this.nalu_arrays.toString=function(){var L="<table class='inner-table'>";L+="<thead><tr><th>completeness</th><th>nalu_type</th><th>nalu_data</th></tr></thead>",L+="<tbody>";for(var w=0;w<this.length;w++){var C=this[w];L+="<tr>",L+="<td rowspan='"+C.length+"'>"+C.completeness+"</td>",L+="<td rowspan='"+C.length+"'>"+C.nalu_type+"</td>";for(var k=0;k<C.length;k++){var U=C[k];k!==0&&(L+="<tr>"),L+="<td>",L+=U.data.reduce(function(G,$){return G+$.toString(16).padStart(2,"0")},"0x"),L+="</td></tr>"}}return L+="</tbody></table>",L};var S=o.readUint8();for(c=0;c<S;c++){var T=[];this.nalu_arrays.push(T),m=o.readUint8(),T.completeness=(m&128)>>7,T.nalu_type=m&63;var b=o.readUint16();for(f=0;f<b;f++){var A={};T.push(A);var I=o.readUint16();A.data=o.readUint8Array(I)}}}),l.createBoxCtor("lsel","LayerSelectorProperty",function(o){this.layer_id=o.readUint16()}),l.createBoxCtor("maxr","hintmaxrate",function(o){this.period=o.readUint32(),this.bytes=o.readUint32()});function d(o,c){this.x=o,this.y=c}d.prototype.toString=function(){return"("+this.x+","+this.y+")"},l.createBoxCtor("mdcv","MasteringDisplayColourVolumeBox",function(o){this.display_primaries=[],this.display_primaries[0]=new d(o.readUint16(),o.readUint16()),this.display_primaries[1]=new d(o.readUint16(),o.readUint16()),this.display_primaries[2]=new d(o.readUint16(),o.readUint16()),this.white_point=new d(o.readUint16(),o.readUint16()),this.max_display_mastering_luminance=o.readUint32(),this.min_display_mastering_luminance=o.readUint32()}),l.createFullBoxCtor("mdhd","MediaHeaderBox",function(o){this.version==1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.timescale=o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.timescale=o.readUint32(),this.duration=o.readUint32()),this.parseLanguage(o),o.readUint16()}),l.createFullBoxCtor("mehd","MovieExtendsHeaderBox",function(o){this.flags&1&&(e.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),this.version==1?this.fragment_duration=o.readUint64():this.fragment_duration=o.readUint32()}),l.createFullBoxCtor("meta","MetaBox",function(o){this.boxes=[],l.ContainerBox.prototype.parse.call(this,o)}),l.createFullBoxCtor("mfhd","MovieFragmentHeaderBox",function(o){this.sequence_number=o.readUint32()}),l.createFullBoxCtor("mfro","MovieFragmentRandomAccessOffsetBox",function(o){this._size=o.readUint32()}),l.createFullBoxCtor("mskC","MaskConfigurationProperty",function(o){this.bits_per_pixel=o.readUint8()}),l.createFullBoxCtor("mvhd","MovieHeaderBox",function(o){this.version==1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.timescale=o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.timescale=o.readUint32(),this.duration=o.readUint32()),this.rate=o.readUint32(),this.volume=o.readUint16()>>8,o.readUint16(),o.readUint32Array(2),this.matrix=o.readUint32Array(9),o.readUint32Array(6),this.next_track_id=o.readUint32()}),l.createBoxCtor("npck","hintPacketsSent",function(o){this.packetssent=o.readUint32()}),l.createBoxCtor("nump","hintPacketsSent",function(o){this.packetssent=o.readUint64()}),l.createFullBoxCtor("padb","PaddingBitsBox",function(o){var c=o.readUint32();this.padbits=[];for(var f=0;f<Math.floor((c+1)/2);f++)this.padbits=o.readUint8()}),l.createBoxCtor("pasp","PixelAspectRatioBox",function(o){this.hSpacing=o.readUint32(),this.vSpacing=o.readUint32()}),l.createBoxCtor("payl","CuePayloadBox",function(o){this.text=o.readString(this.size-this.hdr_size)}),l.createBoxCtor("payt","hintpayloadID",function(o){this.payloadID=o.readUint32();var c=o.readUint8();this.rtpmap_string=o.readString(c)}),l.createFullBoxCtor("pdin","ProgressiveDownloadInfoBox",function(o){var c=(this.size-this.hdr_size)/8;this.rate=[],this.initial_delay=[];for(var f=0;f<c;f++)this.rate[f]=o.readUint32(),this.initial_delay[f]=o.readUint32()}),l.createFullBoxCtor("pitm","PrimaryItemBox",function(o){this.version===0?this.item_id=o.readUint16():this.item_id=o.readUint32()}),l.createFullBoxCtor("pixi","PixelInformationProperty",function(o){var c;for(this.num_channels=o.readUint8(),this.bits_per_channels=[],c=0;c<this.num_channels;c++)this.bits_per_channels[c]=o.readUint8()}),l.createBoxCtor("pmax","hintlargestpacket",function(o){this.bytes=o.readUint32()}),l.createFullBoxCtor("prdi","ProgressiveDerivedImageItemInformationProperty",function(o){if(this.step_count=o.readUint16(),this.item_count=[],this.flags&2)for(var c=0;c<this.step_count;c++)this.item_count[c]=o.readUint16()}),l.createFullBoxCtor("prft","ProducerReferenceTimeBox",function(o){this.ref_track_id=o.readUint32(),this.ntp_timestamp=o.readUint64(),this.version===0?this.media_time=o.readUint32():this.media_time=o.readUint64()}),l.createFullBoxCtor("pssh","ProtectionSystemSpecificHeaderBox",function(o){if(this.system_id=l.parseHex16(o),this.version>0){var c=o.readUint32();this.kid=[];for(var f=0;f<c;f++)this.kid[f]=l.parseHex16(o)}var m=o.readUint32();m>0&&(this.data=o.readUint8Array(m))}),l.createFullBoxCtor("clef","TrackCleanApertureDimensionsBox",function(o){this.width=o.readUint32(),this.height=o.readUint32()}),l.createFullBoxCtor("enof","TrackEncodedPixelsDimensionsBox",function(o){this.width=o.readUint32(),this.height=o.readUint32()}),l.createFullBoxCtor("prof","TrackProductionApertureDimensionsBox",function(o){this.width=o.readUint32(),this.height=o.readUint32()}),l.createContainerBoxCtor("tapt","TrackApertureModeDimensionsBox",null,["clef","prof","enof"]),l.createBoxCtor("rtp ","rtpmoviehintinformation",function(o){this.descriptionformat=o.readString(4),this.sdptext=o.readString(this.size-this.hdr_size-4)}),l.createFullBoxCtor("saio","SampleAuxiliaryInformationOffsetsBox",function(o){this.flags&1&&(this.aux_info_type=o.readString(4),this.aux_info_type_parameter=o.readUint32());var c=o.readUint32();this.offset=[];for(var f=0;f<c;f++)this.version===0?this.offset[f]=o.readUint32():this.offset[f]=o.readUint64()}),l.createFullBoxCtor("saiz","SampleAuxiliaryInformationSizesBox",function(o){if(this.flags&1&&(this.aux_info_type=o.readString(4),this.aux_info_type_parameter=o.readUint32()),this.default_sample_info_size=o.readUint8(),this.sample_count=o.readUint32(),this.sample_info_size=[],this.default_sample_info_size===0)for(var c=0;c<this.sample_count;c++)this.sample_info_size[c]=o.readUint8()}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_METADATA,"mett",function(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_METADATA,"metx",function(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.namespace=o.readCString(),this.schema_location=o.readCString(),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE,"sbtt",function(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE,"stpp",function(o){this.parseHeader(o),this.namespace=o.readCString(),this.schema_location=o.readCString(),this.auxiliary_mime_types=o.readCString(),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE,"stxt",function(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE,"tx3g",function(o){this.parseHeader(o),this.displayFlags=o.readUint32(),this.horizontal_justification=o.readInt8(),this.vertical_justification=o.readInt8(),this.bg_color_rgba=o.readUint8Array(4),this.box_record=o.readInt16Array(4),this.style_record=o.readUint8Array(12),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_METADATA,"wvtt",function(o){this.parseHeader(o),this.parseFooter(o)}),l.createSampleGroupCtor("alst",function(o){var c,f=o.readUint16();for(this.first_output_sample=o.readUint16(),this.sample_offset=[],c=0;c<f;c++)this.sample_offset[c]=o.readUint32();var m=this.description_length-4-4*f;for(this.num_output_samples=[],this.num_total_samples=[],c=0;c<m/4;c++)this.num_output_samples[c]=o.readUint16(),this.num_total_samples[c]=o.readUint16()}),l.createSampleGroupCtor("avll",function(o){this.layerNumber=o.readUint8(),this.accurateStatisticsFlag=o.readUint8(),this.avgBitRate=o.readUint16(),this.avgFrameRate=o.readUint16()}),l.createSampleGroupCtor("avss",function(o){this.subSequenceIdentifier=o.readUint16(),this.layerNumber=o.readUint8();var c=o.readUint8();this.durationFlag=c>>7,this.avgRateFlag=c>>6&1,this.durationFlag&&(this.duration=o.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=o.readUint8(),this.avgBitRate=o.readUint16(),this.avgFrameRate=o.readUint16()),this.dependency=[];for(var f=o.readUint8(),m=0;m<f;m++){var S={};this.dependency.push(S),S.subSeqDirectionFlag=o.readUint8(),S.layerNumber=o.readUint8(),S.subSequenceIdentifier=o.readUint16()}}),l.createSampleGroupCtor("dtrt",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("mvif",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("prol",function(o){this.roll_distance=o.readInt16()}),l.createSampleGroupCtor("rap ",function(o){var c=o.readUint8();this.num_leading_samples_known=c>>7,this.num_leading_samples=c&127}),l.createSampleGroupCtor("rash",function(o){if(this.operation_point_count=o.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)e.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=o.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=o.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(var c=0;c<this.operation_point_count;c++)this.available_bitrate[c]=o.readUint32(),this.target_rate_share[c]=o.readUint16()}this.maximum_bitrate=o.readUint32(),this.minimum_bitrate=o.readUint32(),this.discard_priority=o.readUint8()}}),l.createSampleGroupCtor("roll",function(o){this.roll_distance=o.readInt16()}),l.SampleGroupEntry.prototype.parse=function(o){e.warn("BoxParser","Unknown Sample Group type: "+this.grouping_type),this.data=o.readUint8Array(this.description_length)},l.createSampleGroupCtor("scif",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("scnm",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("seig",function(o){this.reserved=o.readUint8();var c=o.readUint8();this.crypt_byte_block=c>>4,this.skip_byte_block=c&15,this.isProtected=o.readUint8(),this.Per_Sample_IV_Size=o.readUint8(),this.KID=l.parseHex16(o),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=o.readUint8(),this.constant_IV=o.readUint8Array(this.constant_IV_size))}),l.createSampleGroupCtor("stsa",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("sync",function(o){var c=o.readUint8();this.NAL_unit_type=c&63}),l.createSampleGroupCtor("tele",function(o){var c=o.readUint8();this.level_independently_decodable=c>>7}),l.createSampleGroupCtor("tsas",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("tscl",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("vipr",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createFullBoxCtor("sbgp","SampleToGroupBox",function(o){this.grouping_type=o.readString(4),this.version===1?this.grouping_type_parameter=o.readUint32():this.grouping_type_parameter=0,this.entries=[];for(var c=o.readUint32(),f=0;f<c;f++){var m={};this.entries.push(m),m.sample_count=o.readInt32(),m.group_description_index=o.readInt32()}});function p(o,c){this.bad_pixel_row=o,this.bad_pixel_column=c}p.prototype.toString=function(){return"[row: "+this.bad_pixel_row+", column: "+this.bad_pixel_column+"]"},l.createFullBoxCtor("sbpm","SensorBadPixelsMapBox",function(o){var c;for(this.component_count=o.readUint16(),this.component_index=[],c=0;c<this.component_count;c++)this.component_index.push(o.readUint16());var f=o.readUint8();for(this.correction_applied=(f&128)==128,this.num_bad_rows=o.readUint32(),this.num_bad_cols=o.readUint32(),this.num_bad_pixels=o.readUint32(),this.bad_rows=[],this.bad_columns=[],this.bad_pixels=[],c=0;c<this.num_bad_rows;c++)this.bad_rows.push(o.readUint32());for(c=0;c<this.num_bad_cols;c++)this.bad_columns.push(o.readUint32());for(c=0;c<this.num_bad_pixels;c++){var m=o.readUint32(),S=o.readUint32();this.bad_pixels.push(new p(m,S))}}),l.createFullBoxCtor("schm","SchemeTypeBox",function(o){this.scheme_type=o.readString(4),this.scheme_version=o.readUint32(),this.flags&1&&(this.scheme_uri=o.readString(this.size-this.hdr_size-8))}),l.createBoxCtor("sdp ","rtptracksdphintinformation",function(o){this.sdptext=o.readString(this.size-this.hdr_size)}),l.createFullBoxCtor("sdtp","SampleDependencyTypeBox",function(o){var c,f=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(var m=0;m<f;m++)c=o.readUint8(),this.is_leading[m]=c>>6,this.sample_depends_on[m]=c>>4&3,this.sample_is_depended_on[m]=c>>2&3,this.sample_has_redundancy[m]=c&3}),l.createFullBoxCtor("senc","SampleEncryptionBox"),l.createFullBoxCtor("sgpd","SampleGroupDescriptionBox",function(o){this.grouping_type=o.readString(4),e.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),this.version===1?this.default_length=o.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=o.readUint32()),this.entries=[];for(var c=o.readUint32(),f=0;f<c;f++){var m;l[this.grouping_type+"SampleGroupEntry"]?m=new l[this.grouping_type+"SampleGroupEntry"](this.grouping_type):m=new l.SampleGroupEntry(this.grouping_type),this.entries.push(m),this.version===1?this.default_length===0?m.description_length=o.readUint32():m.description_length=this.default_length:m.description_length=this.default_length,m.write===l.SampleGroupEntry.prototype.write&&(e.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),m.data=o.readUint8Array(m.description_length),o.position-=m.description_length),m.parse(o)}}),l.createFullBoxCtor("sidx","CompressedSegmentIndexBox",function(o){this.reference_ID=o.readUint32(),this.timescale=o.readUint32(),this.version===0?(this.earliest_presentation_time=o.readUint32(),this.first_offset=o.readUint32()):(this.earliest_presentation_time=o.readUint64(),this.first_offset=o.readUint64()),o.readUint16(),this.references=[];for(var c=o.readUint16(),f=0;f<c;f++){var m={};this.references.push(m);var S=o.readUint32();m.reference_type=S>>31&1,m.referenced_size=S&2147483647,m.subsegment_duration=o.readUint32(),S=o.readUint32(),m.starts_with_SAP=S>>31&1,m.SAP_type=S>>28&7,m.SAP_delta_time=S&268435455}}),l.SingleItemTypeReferenceBox=function(o,c,f,m){l.Box.call(this,o,c),this.hdr_size=f,this.start=m},l.SingleItemTypeReferenceBox.prototype=new l.Box,l.SingleItemTypeReferenceBox.prototype.parse=function(o){this.from_item_ID=o.readUint16();var c=o.readUint16();this.references=[];for(var f=0;f<c;f++)this.references[f]={},this.references[f].to_item_ID=o.readUint16()},l.SingleItemTypeReferenceBoxLarge=function(o,c,f,m){l.Box.call(this,o,c),this.hdr_size=f,this.start=m},l.SingleItemTypeReferenceBoxLarge.prototype=new l.Box,l.SingleItemTypeReferenceBoxLarge.prototype.parse=function(o){this.from_item_ID=o.readUint32();var c=o.readUint16();this.references=[];for(var f=0;f<c;f++)this.references[f]={},this.references[f].to_item_ID=o.readUint32()},l.createFullBoxCtor("SmDm","SMPTE2086MasteringDisplayMetadataBox",function(o){this.primaryRChromaticity_x=o.readUint16(),this.primaryRChromaticity_y=o.readUint16(),this.primaryGChromaticity_x=o.readUint16(),this.primaryGChromaticity_y=o.readUint16(),this.primaryBChromaticity_x=o.readUint16(),this.primaryBChromaticity_y=o.readUint16(),this.whitePointChromaticity_x=o.readUint16(),this.whitePointChromaticity_y=o.readUint16(),this.luminanceMax=o.readUint32(),this.luminanceMin=o.readUint32()}),l.createFullBoxCtor("smhd","SoundMediaHeaderBox",function(o){this.balance=o.readUint16(),o.readUint16()}),l.createFullBoxCtor("ssix","CompressedSubsegmentIndexBox",function(o){this.subsegments=[];for(var c=o.readUint32(),f=0;f<c;f++){var m={};this.subsegments.push(m),m.ranges=[];for(var S=o.readUint32(),T=0;T<S;T++){var b={};m.ranges.push(b),b.level=o.readUint8(),b.range_size=o.readUint24()}}}),l.createFullBoxCtor("stco","ChunkOffsetBox",function(o){var c;if(c=o.readUint32(),this.chunk_offsets=[],this.version===0)for(var f=0;f<c;f++)this.chunk_offsets.push(o.readUint32())}),l.createFullBoxCtor("stdp","DegradationPriorityBox",function(o){var c=(this.size-this.hdr_size)/2;this.priority=[];for(var f=0;f<c;f++)this.priority[f]=o.readUint16()}),l.createFullBoxCtor("sthd","SubtitleMediaHeaderBox"),l.createFullBoxCtor("stri","SubTrackInformationBox",function(o){this.switch_group=o.readUint16(),this.alternate_group=o.readUint16(),this.sub_track_id=o.readUint32();var c=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(var f=0;f<c;f++)this.attribute_list[f]=o.readUint32()}),l.createFullBoxCtor("stsc","SampleToChunkBox",function(o){var c,f;if(c=o.readUint32(),this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],this.version===0)for(f=0;f<c;f++)this.first_chunk.push(o.readUint32()),this.samples_per_chunk.push(o.readUint32()),this.sample_description_index.push(o.readUint32())}),l.createFullBoxCtor("stsd","SampleDescriptionBox",function(o){var c,f,m,S;for(this.entries=[],m=o.readUint32(),c=1;c<=m;c++)if(f=l.parseOneBox(o,!0,this.size-(o.getPosition()-this.start)),f.code===l.OK)l[f.type+"SampleEntry"]?(S=new l[f.type+"SampleEntry"](f.size),S.hdr_size=f.hdr_size,S.start=f.start):(e.warn("BoxParser","Unknown sample entry type: "+f.type),S=new l.SampleEntry(f.type,f.size,f.hdr_size,f.start)),S.write===l.SampleEntry.prototype.write&&(e.info("BoxParser","SampleEntry "+S.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),S.parseDataAndRewind(o)),S.parse(o),this.entries.push(S);else return}),l.createFullBoxCtor("stsg","SubTrackSampleGroupBox",function(o){this.grouping_type=o.readUint32();var c=o.readUint16();this.group_description_index=[];for(var f=0;f<c;f++)this.group_description_index[f]=o.readUint32()}),l.createFullBoxCtor("stsh","ShadowSyncSampleBox",function(o){var c,f;if(c=o.readUint32(),this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],this.version===0)for(f=0;f<c;f++)this.shadowed_sample_numbers.push(o.readUint32()),this.sync_sample_numbers.push(o.readUint32())}),l.createFullBoxCtor("stss","SyncSampleBox",function(o){var c,f;if(f=o.readUint32(),this.version===0)for(this.sample_numbers=[],c=0;c<f;c++)this.sample_numbers.push(o.readUint32())}),l.createFullBoxCtor("stsz","SampleSizeBox",function(o){var c;if(this.sample_sizes=[],this.version===0)for(this.sample_size=o.readUint32(),this.sample_count=o.readUint32(),c=0;c<this.sample_count;c++)this.sample_size===0?this.sample_sizes.push(o.readUint32()):this.sample_sizes[c]=this.sample_size}),l.createFullBoxCtor("stts","TimeToSampleBox",function(o){var c,f,m;if(c=o.readUint32(),this.sample_counts=[],this.sample_deltas=[],this.version===0)for(f=0;f<c;f++)this.sample_counts.push(o.readUint32()),m=o.readInt32(),m<0&&(e.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),m=1),this.sample_deltas.push(m)}),l.createFullBoxCtor("stvi","StereoVideoBox",function(o){var c=o.readUint32();this.single_view_allowed=c&3,this.stereo_scheme=o.readUint32();var f=o.readUint32();this.stereo_indication_type=o.readString(f);var m,S;for(this.boxes=[];o.getPosition()<this.start+this.size;)if(m=l.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),m.code===l.OK)S=m.box,this.boxes.push(S),this[S.type]=S;else return}),l.createBoxCtor("styp","SegmentTypeBox",function(o){l.ftypBox.prototype.parse.call(this,o)}),l.createFullBoxCtor("stz2","CompactSampleSizeBox",function(o){var c,f;if(this.sample_sizes=[],this.version===0)if(this.reserved=o.readUint24(),this.field_size=o.readUint8(),f=o.readUint32(),this.field_size===4)for(c=0;c<f;c+=2){var m=o.readUint8();this.sample_sizes[c]=m>>4&15,this.sample_sizes[c+1]=m&15}else if(this.field_size===8)for(c=0;c<f;c++)this.sample_sizes[c]=o.readUint8();else if(this.field_size===16)for(c=0;c<f;c++)this.sample_sizes[c]=o.readUint16();else e.error("BoxParser","Error in length field in stz2 box")}),l.createFullBoxCtor("subs","SubSampleInformationBox",function(o){var c,f,m,S;for(m=o.readUint32(),this.entries=[],c=0;c<m;c++){var T={};if(this.entries[c]=T,T.sample_delta=o.readUint32(),T.subsamples=[],S=o.readUint16(),S>0)for(f=0;f<S;f++){var b={};T.subsamples.push(b),this.version==1?b.size=o.readUint32():b.size=o.readUint16(),b.priority=o.readUint8(),b.discardable=o.readUint8(),b.codec_specific_parameters=o.readUint32()}}}),l.createFullBoxCtor("tenc","TrackEncryptionBox",function(o){if(o.readUint8(),this.version===0)o.readUint8();else{var c=o.readUint8();this.default_crypt_byte_block=c>>4&15,this.default_skip_byte_block=c&15}this.default_isProtected=o.readUint8(),this.default_Per_Sample_IV_Size=o.readUint8(),this.default_KID=l.parseHex16(o),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=o.readUint8(),this.default_constant_IV=o.readUint8Array(this.default_constant_IV_size))}),l.createFullBoxCtor("tfdt","TrackFragmentBaseMediaDecodeTimeBox",function(o){this.version==1?this.baseMediaDecodeTime=o.readUint64():this.baseMediaDecodeTime=o.readUint32()}),l.createFullBoxCtor("tfhd","TrackFragmentHeaderBox",function(o){var c=0;this.track_id=o.readUint32(),this.size-this.hdr_size>c&&this.flags&l.TFHD_FLAG_BASE_DATA_OFFSET?(this.base_data_offset=o.readUint64(),c+=8):this.base_data_offset=0,this.size-this.hdr_size>c&&this.flags&l.TFHD_FLAG_SAMPLE_DESC?(this.default_sample_description_index=o.readUint32(),c+=4):this.default_sample_description_index=0,this.size-this.hdr_size>c&&this.flags&l.TFHD_FLAG_SAMPLE_DUR?(this.default_sample_duration=o.readUint32(),c+=4):this.default_sample_duration=0,this.size-this.hdr_size>c&&this.flags&l.TFHD_FLAG_SAMPLE_SIZE?(this.default_sample_size=o.readUint32(),c+=4):this.default_sample_size=0,this.size-this.hdr_size>c&&this.flags&l.TFHD_FLAG_SAMPLE_FLAGS?(this.default_sample_flags=o.readUint32(),c+=4):this.default_sample_flags=0}),l.createFullBoxCtor("tfra","TrackFragmentRandomAccessBox",function(o){this.track_ID=o.readUint32(),o.readUint24();var c=o.readUint8();this.length_size_of_traf_num=c>>4&3,this.length_size_of_trun_num=c>>2&3,this.length_size_of_sample_num=c&3,this.entries=[];for(var f=o.readUint32(),m=0;m<f;m++)this.version===1?(this.time=o.readUint64(),this.moof_offset=o.readUint64()):(this.time=o.readUint32(),this.moof_offset=o.readUint32()),this.traf_number=o["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=o["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=o["readUint"+8*(this.length_size_of_sample_num+1)]()}),l.createFullBoxCtor("tkhd","TrackHeaderBox",function(o){this.version==1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.track_id=o.readUint32(),o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.track_id=o.readUint32(),o.readUint32(),this.duration=o.readUint32()),o.readUint32Array(2),this.layer=o.readInt16(),this.alternate_group=o.readInt16(),this.volume=o.readInt16()>>8,o.readUint16(),this.matrix=o.readInt32Array(9),this.width=o.readUint32(),this.height=o.readUint32()}),l.createBoxCtor("tmax","hintmaxrelativetime",function(o){this.time=o.readUint32()}),l.createBoxCtor("tmin","hintminrelativetime",function(o){this.time=o.readUint32()}),l.createBoxCtor("totl","hintBytesSent",function(o){this.bytessent=o.readUint32()}),l.createBoxCtor("tpay","hintBytesSent",function(o){this.bytessent=o.readUint32()}),l.createBoxCtor("tpyl","hintBytesSent",function(o){this.bytessent=o.readUint64()}),l.TrackGroupTypeBox.prototype.parse=function(o){this.parseFullHeader(o),this.track_group_id=o.readUint32()},l.createTrackGroupCtor("msrc"),l.TrackReferenceTypeBox=function(o,c,f,m){l.Box.call(this,o,c),this.hdr_size=f,this.start=m},l.TrackReferenceTypeBox.prototype=new l.Box,l.TrackReferenceTypeBox.prototype.parse=function(o){this.track_ids=o.readUint32Array((this.size-this.hdr_size)/4)},l.trefBox.prototype.parse=function(o){for(var c,f;o.getPosition()<this.start+this.size;)if(c=l.parseOneBox(o,!0,this.size-(o.getPosition()-this.start)),c.code===l.OK)f=new l.TrackReferenceTypeBox(c.type,c.size,c.hdr_size,c.start),f.write===l.Box.prototype.write&&f.type!=="mdat"&&(e.info("BoxParser","TrackReference "+f.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),f.parseDataAndRewind(o)),f.parse(o),this.boxes.push(f);else return},l.createFullBoxCtor("trep","TrackExtensionPropertiesBox",function(o){for(this.track_ID=o.readUint32(),this.boxes=[];o.getPosition()<this.start+this.size;)if(ret=l.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),ret.code===l.OK)box=ret.box,this.boxes.push(box);else return}),l.createFullBoxCtor("trex","TrackExtendsBox",function(o){this.track_id=o.readUint32(),this.default_sample_description_index=o.readUint32(),this.default_sample_duration=o.readUint32(),this.default_sample_size=o.readUint32(),this.default_sample_flags=o.readUint32()}),l.createBoxCtor("trpy","hintBytesSent",function(o){this.bytessent=o.readUint64()}),l.createFullBoxCtor("trun","TrackRunBox",function(o){var c=0;if(this.sample_count=o.readUint32(),c+=4,this.size-this.hdr_size>c&&this.flags&l.TRUN_FLAGS_DATA_OFFSET?(this.data_offset=o.readInt32(),c+=4):this.data_offset=0,this.size-this.hdr_size>c&&this.flags&l.TRUN_FLAGS_FIRST_FLAG?(this.first_sample_flags=o.readUint32(),c+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>c)for(var f=0;f<this.sample_count;f++)this.flags&l.TRUN_FLAGS_DURATION&&(this.sample_duration[f]=o.readUint32()),this.flags&l.TRUN_FLAGS_SIZE&&(this.sample_size[f]=o.readUint32()),this.flags&l.TRUN_FLAGS_FLAGS&&(this.sample_flags[f]=o.readUint32()),this.flags&l.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?this.sample_composition_time_offset[f]=o.readUint32():this.sample_composition_time_offset[f]=o.readInt32())}),l.createFullBoxCtor("tsel","TrackSelectionBox",function(o){this.switch_group=o.readUint32();var c=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(var f=0;f<c;f++)this.attribute_list[f]=o.readUint32()}),l.createFullBoxCtor("txtC","TextConfigBox",function(o){this.config=o.readCString()}),l.createBoxCtor("tyco","TypeCombinationBox",function(o){var c=(this.size-this.hdr_size)/4;this.compatible_brands=[];for(var f=0;f<c;f++)this.compatible_brands[f]=o.readString(4)}),l.createFullBoxCtor("udes","UserDescriptionProperty",function(o){this.lang=o.readCString(),this.name=o.readCString(),this.description=o.readCString(),this.tags=o.readCString()}),l.createFullBoxCtor("uncC","UncompressedFrameConfigBox",function(o){var c;if(this.profile=o.readString(4),this.version!=1){if(this.version==0){for(this.component_count=o.readUint32(),this.component_index=[],this.component_bit_depth_minus_one=[],this.component_format=[],this.component_align_size=[],c=0;c<this.component_count;c++)this.component_index.push(o.readUint16()),this.component_bit_depth_minus_one.push(o.readUint8()),this.component_format.push(o.readUint8()),this.component_align_size.push(o.readUint8());this.sampling_type=o.readUint8(),this.interleave_type=o.readUint8(),this.block_size=o.readUint8();var f=o.readUint8();this.component_little_endian=f>>7&1,this.block_pad_lsb=f>>6&1,this.block_little_endian=f>>5&1,this.block_reversed=f>>4&1,this.pad_unknown=f>>3&1,this.pixel_size=o.readUint32(),this.row_align_size=o.readUint32(),this.tile_align_size=o.readUint32(),this.num_tile_cols_minus_one=o.readUint32(),this.num_tile_rows_minus_one=o.readUint32()}}}),l.createFullBoxCtor("url ","DataEntryUrlBox",function(o){this.flags!==1&&(this.location=o.readCString())}),l.createFullBoxCtor("urn ","DataEntryUrnBox",function(o){this.name=o.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=o.readCString())}),l.createUUIDBox("a5d40b30e81411ddba2f0800200c9a66","LiveServerManifestBox",!0,!1,function(o){this.LiveServerManifest=o.readString(this.size-this.hdr_size).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}),l.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3","PiffProtectionSystemSpecificHeaderBox",!0,!1,function(o){this.system_id=l.parseHex16(o);var c=o.readUint32();c>0&&(this.data=o.readUint8Array(c))}),l.createUUIDBox("a2394f525a9b4f14a2446c427c648df4","PiffSampleEncryptionBox",!0,!1),l.createUUIDBox("8974dbce7be74c5184f97148f9882554","PiffTrackEncryptionBox",!0,!1,function(o){this.default_AlgorithmID=o.readUint24(),this.default_IV_size=o.readUint8(),this.default_KID=l.parseHex16(o)}),l.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f","TfrfBox",!0,!1,function(o){this.fragment_count=o.readUint8(),this.entries=[];for(var c=0;c<this.fragment_count;c++){var f={},m=0,S=0;this.version===1?(m=o.readUint64(),S=o.readUint64()):(m=o.readUint32(),S=o.readUint32()),f.absolute_time=m,f.absolute_duration=S,this.entries.push(f)}}),l.createUUIDBox("6d1d9b0542d544e680e2141daff757b2","TfxdBox",!0,!1,function(o){this.version===1?(this.absolute_time=o.readUint64(),this.duration=o.readUint64()):(this.absolute_time=o.readUint32(),this.duration=o.readUint32())}),l.createFullBoxCtor("vmhd","VideoMediaHeaderBox",function(o){this.graphicsmode=o.readUint16(),this.opcolor=o.readUint16Array(3)}),l.createFullBoxCtor("vpcC","VPCodecConfigurationRecord",function(o){var c;this.version===1?(this.profile=o.readUint8(),this.level=o.readUint8(),c=o.readUint8(),this.bitDepth=c>>4,this.chromaSubsampling=c>>1&7,this.videoFullRangeFlag=c&1,this.colourPrimaries=o.readUint8(),this.transferCharacteristics=o.readUint8(),this.matrixCoefficients=o.readUint8(),this.codecIntializationDataSize=o.readUint16(),this.codecIntializationData=o.readUint8Array(this.codecIntializationDataSize)):(this.profile=o.readUint8(),this.level=o.readUint8(),c=o.readUint8(),this.bitDepth=c>>4&15,this.colorSpace=c&15,c=o.readUint8(),this.chromaSubsampling=c>>4&15,this.transferFunction=c>>1&7,this.videoFullRangeFlag=c&1,this.codecIntializationDataSize=o.readUint16(),this.codecIntializationData=o.readUint8Array(this.codecIntializationDataSize))}),l.createBoxCtor("vttC","WebVTTConfigurationBox",function(o){this.text=o.readString(this.size-this.hdr_size)}),l.createFullBoxCtor("vvcC","VvcConfigurationBox",function(o){var c,f,m={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(U){this.held_bits=U.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(U){this.held_bits=U.readUint16(),this.num_held_bits=16},extract_bits:function(U){var G=this.held_bits>>this.num_held_bits-U&(1<<U)-1;return this.num_held_bits-=U,G}};if(m.stream_read_1_bytes(o),m.extract_bits(5),this.lengthSizeMinusOne=m.extract_bits(2),this.ptl_present_flag=m.extract_bits(1),this.ptl_present_flag){m.stream_read_2_bytes(o),this.ols_idx=m.extract_bits(9),this.num_sublayers=m.extract_bits(3),this.constant_frame_rate=m.extract_bits(2),this.chroma_format_idc=m.extract_bits(2),m.stream_read_1_bytes(o),this.bit_depth_minus8=m.extract_bits(3),m.extract_bits(5);{if(m.stream_read_2_bytes(o),m.extract_bits(2),this.num_bytes_constraint_info=m.extract_bits(6),this.general_profile_idc=m.extract_bits(7),this.general_tier_flag=m.extract_bits(1),this.general_level_idc=o.readUint8(),m.stream_read_1_bytes(o),this.ptl_frame_only_constraint_flag=m.extract_bits(1),this.ptl_multilayer_enabled_flag=m.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(c=0;c<this.num_bytes_constraint_info-1;c++){var S=m.extract_bits(6);m.stream_read_1_bytes(o);var T=m.extract_bits(2);this.general_constraint_info[c]=S<<2|T}this.general_constraint_info[this.num_bytes_constraint_info-1]=m.extract_bits(6)}else m.extract_bits(6);if(this.num_sublayers>1){for(m.stream_read_1_bytes(o),this.ptl_sublayer_present_mask=0,f=this.num_sublayers-2;f>=0;--f){var b=m.extract_bits(1);this.ptl_sublayer_present_mask|=b<<f}for(f=this.num_sublayers;f<=8&&this.num_sublayers>1;++f)m.extract_bits(1);for(this.sublayer_level_idc=[],f=this.num_sublayers-2;f>=0;--f)this.ptl_sublayer_present_mask&1<<f&&(this.sublayer_level_idc[f]=o.readUint8())}if(this.ptl_num_sub_profiles=o.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(c=0;c<this.ptl_num_sub_profiles;c++)this.general_sub_profile_idc.push(o.readUint32())}this.max_picture_width=o.readUint16(),this.max_picture_height=o.readUint16(),this.avg_frame_rate=o.readUint16()}var A=12,I=13;this.nalu_arrays=[];var L=o.readUint8();for(c=0;c<L;c++){var w=[];this.nalu_arrays.push(w),m.stream_read_1_bytes(o),w.completeness=m.extract_bits(1),m.extract_bits(2),w.nalu_type=m.extract_bits(5);var C=1;for(w.nalu_type!=I&&w.nalu_type!=A&&(C=o.readUint16()),f=0;f<C;f++){var k=o.readUint16();w.push({data:o.readUint8Array(k),length:k})}}}),l.createFullBoxCtor("vvnC","VvcNALUConfigBox",function(o){var c=strm.readUint8();this.lengthSizeMinusOne=c&3}),l.SampleEntry.prototype.isVideo=function(){return!1},l.SampleEntry.prototype.isAudio=function(){return!1},l.SampleEntry.prototype.isSubtitle=function(){return!1},l.SampleEntry.prototype.isMetadata=function(){return!1},l.SampleEntry.prototype.isHint=function(){return!1},l.SampleEntry.prototype.getCodec=function(){return this.type.replace(".","")},l.SampleEntry.prototype.getWidth=function(){return""},l.SampleEntry.prototype.getHeight=function(){return""},l.SampleEntry.prototype.getChannelCount=function(){return""},l.SampleEntry.prototype.getSampleRate=function(){return""},l.SampleEntry.prototype.getSampleSize=function(){return""},l.VisualSampleEntry.prototype.isVideo=function(){return!0},l.VisualSampleEntry.prototype.getWidth=function(){return this.width},l.VisualSampleEntry.prototype.getHeight=function(){return this.height},l.AudioSampleEntry.prototype.isAudio=function(){return!0},l.AudioSampleEntry.prototype.getChannelCount=function(){return this.channel_count},l.AudioSampleEntry.prototype.getSampleRate=function(){return this.samplerate},l.AudioSampleEntry.prototype.getSampleSize=function(){return this.samplesize},l.SubtitleSampleEntry.prototype.isSubtitle=function(){return!0},l.MetadataSampleEntry.prototype.isMetadata=function(){return!0},l.decimalToHex=function(o,c){var f=Number(o).toString(16);for(c=typeof c>"u"||c===null?c=2:c;f.length<c;)f="0"+f;return f},l.avc1SampleEntry.prototype.getCodec=l.avc2SampleEntry.prototype.getCodec=l.avc3SampleEntry.prototype.getCodec=l.avc4SampleEntry.prototype.getCodec=function(){var o=l.SampleEntry.prototype.getCodec.call(this);return this.avcC?o+"."+l.decimalToHex(this.avcC.AVCProfileIndication)+l.decimalToHex(this.avcC.profile_compatibility)+l.decimalToHex(this.avcC.AVCLevelIndication):o},l.hev1SampleEntry.prototype.getCodec=l.hvc1SampleEntry.prototype.getCodec=function(){var o,c=l.SampleEntry.prototype.getCodec.call(this);if(this.hvcC){switch(c+=".",this.hvcC.general_profile_space){case 0:c+="";break;case 1:c+="A";break;case 2:c+="B";break;case 3:c+="C";break}c+=this.hvcC.general_profile_idc,c+=".";var f=this.hvcC.general_profile_compatibility,m=0;for(o=0;o<32&&(m|=f&1,o!=31);o++)m<<=1,f>>=1;c+=l.decimalToHex(m,0),c+=".",this.hvcC.general_tier_flag===0?c+="L":c+="H",c+=this.hvcC.general_level_idc;var S=!1,T="";for(o=5;o>=0;o--)(this.hvcC.general_constraint_indicator[o]||S)&&(T="."+l.decimalToHex(this.hvcC.general_constraint_indicator[o],0)+T,S=!0);c+=T}return c},l.vvc1SampleEntry.prototype.getCodec=l.vvi1SampleEntry.prototype.getCodec=function(){var o,c=l.SampleEntry.prototype.getCodec.call(this);if(this.vvcC){c+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?c+=".H":c+=".L",c+=this.vvcC.general_level_idc;var f="";if(this.vvcC.general_constraint_info){var m=[],S=0;S|=this.vvcC.ptl_frame_only_constraint<<7,S|=this.vvcC.ptl_multilayer_enabled<<6;var T;for(o=0;o<this.vvcC.general_constraint_info.length;++o)S|=this.vvcC.general_constraint_info[o]>>2&63,m.push(S),S&&(T=o),S=this.vvcC.general_constraint_info[o]>>2&3;if(T===void 0)f=".CA";else{f=".C";var b="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",A=0,I=0;for(o=0;o<=T;++o)for(A=A<<8|m[o],I+=8;I>=5;){var L=A>>I-5&31;f+=b[L],I-=5,A&=(1<<I)-1}I&&(A<<=5-I,f+=b[A&31])}}c+=f}return c},l.mp4aSampleEntry.prototype.getCodec=function(){var o=l.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var c=this.esds.esd.getOTI(),f=this.esds.esd.getAudioConfig();return o+"."+l.decimalToHex(c)+(f?"."+f:"")}else return o},l.stxtSampleEntry.prototype.getCodec=function(){var o=l.SampleEntry.prototype.getCodec.call(this);return this.mime_format?o+"."+this.mime_format:o},l.vp08SampleEntry.prototype.getCodec=l.vp09SampleEntry.prototype.getCodec=function(){var o=l.SampleEntry.prototype.getCodec.call(this),c=this.vpcC.level;c==0&&(c="00");var f=this.vpcC.bitDepth;return f==8&&(f="08"),o+".0"+this.vpcC.profile+"."+c+"."+f},l.av01SampleEntry.prototype.getCodec=function(){var o=l.SampleEntry.prototype.getCodec.call(this),c=this.av1C.seq_level_idx_0;c<10&&(c="0"+c);var f;return this.av1C.seq_profile===2&&this.av1C.high_bitdepth===1?f=this.av1C.twelve_bit===1?"12":"10":this.av1C.seq_profile<=2&&(f=this.av1C.high_bitdepth===1?"10":"08"),o+"."+this.av1C.seq_profile+"."+c+(this.av1C.seq_tier_0?"H":"M")+"."+f},l.Box.prototype.writeHeader=function(o,c){this.size+=8,this.size>n&&(this.size+=8),this.type==="uuid"&&(this.size+=16),e.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+o.getPosition()+(c||"")),this.size>n?o.writeUint32(1):(this.sizePosition=o.getPosition(),o.writeUint32(this.size)),o.writeString(this.type,null,4),this.type==="uuid"&&o.writeUint8Array(this.uuid),this.size>n&&o.writeUint64(this.size)},l.FullBox.prototype.writeHeader=function(o){this.size+=4,l.Box.prototype.writeHeader.call(this,o," v="+this.version+" f="+this.flags),o.writeUint8(this.version),o.writeUint24(this.flags)},l.Box.prototype.write=function(o){this.type==="mdat"?this.data&&(this.size=this.data.length,this.writeHeader(o),o.writeUint8Array(this.data)):(this.size=this.data?this.data.length:0,this.writeHeader(o),this.data&&o.writeUint8Array(this.data))},l.ContainerBox.prototype.write=function(o){this.size=0,this.writeHeader(o);for(var c=0;c<this.boxes.length;c++)this.boxes[c]&&(this.boxes[c].write(o),this.size+=this.boxes[c].size);e.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},l.TrackReferenceTypeBox.prototype.write=function(o){this.size=this.track_ids.length*4,this.writeHeader(o),o.writeUint32Array(this.track_ids)},l.avcCBox.prototype.write=function(o){var c;for(this.size=7,c=0;c<this.SPS.length;c++)this.size+=2+this.SPS[c].length;for(c=0;c<this.PPS.length;c++)this.size+=2+this.PPS[c].length;for(this.ext&&(this.size+=this.ext.length),this.writeHeader(o),o.writeUint8(this.configurationVersion),o.writeUint8(this.AVCProfileIndication),o.writeUint8(this.profile_compatibility),o.writeUint8(this.AVCLevelIndication),o.writeUint8(this.lengthSizeMinusOne+252),o.writeUint8(this.SPS.length+224),c=0;c<this.SPS.length;c++)o.writeUint16(this.SPS[c].length),o.writeUint8Array(this.SPS[c].nalu);for(o.writeUint8(this.PPS.length),c=0;c<this.PPS.length;c++)o.writeUint16(this.PPS[c].length),o.writeUint8Array(this.PPS[c].nalu);this.ext&&o.writeUint8Array(this.ext)},l.co64Box.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(o),o.writeUint32(this.chunk_offsets.length),c=0;c<this.chunk_offsets.length;c++)o.writeUint64(this.chunk_offsets[c])},l.cslgBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(o),o.writeInt32(this.compositionToDTSShift),o.writeInt32(this.leastDecodeToDisplayDelta),o.writeInt32(this.greatestDecodeToDisplayDelta),o.writeInt32(this.compositionStartTime),o.writeInt32(this.compositionEndTime)},l.cttsBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(o),o.writeUint32(this.sample_counts.length),c=0;c<this.sample_counts.length;c++)o.writeUint32(this.sample_counts[c]),this.version===1?o.writeInt32(this.sample_offsets[c]):o.writeUint32(this.sample_offsets[c])},l.drefBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4,this.writeHeader(o),o.writeUint32(this.entries.length);for(var c=0;c<this.entries.length;c++)this.entries[c].write(o),this.size+=this.entries[c].size;e.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},l.elngBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(o),o.writeString(this.extended_language)},l.elstBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4+12*this.entries.length,this.writeHeader(o),o.writeUint32(this.entries.length);for(var c=0;c<this.entries.length;c++){var f=this.entries[c];o.writeUint32(f.segment_duration),o.writeInt32(f.media_time),o.writeInt16(f.media_rate_integer),o.writeInt16(f.media_rate_fraction)}},l.emsgBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4*4+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(o),o.writeCString(this.scheme_id_uri),o.writeCString(this.value),o.writeUint32(this.timescale),o.writeUint32(this.presentation_time_delta),o.writeUint32(this.event_duration),o.writeUint32(this.id),o.writeUint8Array(this.message_data)},l.ftypBox.prototype.write=function(o){this.size=8+4*this.compatible_brands.length,this.writeHeader(o),o.writeString(this.major_brand,null,4),o.writeUint32(this.minor_version);for(var c=0;c<this.compatible_brands.length;c++)o.writeString(this.compatible_brands[c],null,4)},l.hdlrBox.prototype.write=function(o){this.size=5*4+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(o),o.writeUint32(0),o.writeString(this.handler,null,4),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeCString(this.name)},l.hvcCBox.prototype.write=function(o){var c,f;for(this.size=23,c=0;c<this.nalu_arrays.length;c++)for(this.size+=3,f=0;f<this.nalu_arrays[c].length;f++)this.size+=2+this.nalu_arrays[c][f].data.length;for(this.writeHeader(o),o.writeUint8(this.configurationVersion),o.writeUint8((this.general_profile_space<<6)+(this.general_tier_flag<<5)+this.general_profile_idc),o.writeUint32(this.general_profile_compatibility),o.writeUint8Array(this.general_constraint_indicator),o.writeUint8(this.general_level_idc),o.writeUint16(this.min_spatial_segmentation_idc+(15<<24)),o.writeUint8(this.parallelismType+252),o.writeUint8(this.chroma_format_idc+252),o.writeUint8(this.bit_depth_luma_minus8+248),o.writeUint8(this.bit_depth_chroma_minus8+248),o.writeUint16(this.avgFrameRate),o.writeUint8((this.constantFrameRate<<6)+(this.numTemporalLayers<<3)+(this.temporalIdNested<<2)+this.lengthSizeMinusOne),o.writeUint8(this.nalu_arrays.length),c=0;c<this.nalu_arrays.length;c++)for(o.writeUint8((this.nalu_arrays[c].completeness<<7)+this.nalu_arrays[c].nalu_type),o.writeUint16(this.nalu_arrays[c].length),f=0;f<this.nalu_arrays[c].length;f++)o.writeUint16(this.nalu_arrays[c][f].data.length),o.writeUint8Array(this.nalu_arrays[c][f].data)},l.kindBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value.length+1),this.writeHeader(o),o.writeCString(this.schemeURI),o.writeCString(this.value)},l.mdhdBox.prototype.write=function(o){this.size=4*4+2*2,this.flags=0,this.version=0,this.writeHeader(o),o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.timescale),o.writeUint32(this.duration),o.writeUint16(this.language),o.writeUint16(0)},l.mehdBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4,this.writeHeader(o),o.writeUint32(this.fragment_duration)},l.mfhdBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4,this.writeHeader(o),o.writeUint32(this.sequence_number)},l.mvhdBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=23*4+2*2,this.writeHeader(o),o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.timescale),o.writeUint32(this.duration),o.writeUint32(this.rate),o.writeUint16(this.volume<<8),o.writeUint16(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32Array(this.matrix),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(this.next_track_id)},l.SampleEntry.prototype.writeHeader=function(o){this.size=8,l.Box.prototype.writeHeader.call(this,o),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint16(this.data_reference_index)},l.SampleEntry.prototype.writeFooter=function(o){for(var c=0;c<this.boxes.length;c++)this.boxes[c].write(o),this.size+=this.boxes[c].size;e.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},l.SampleEntry.prototype.write=function(o){this.writeHeader(o),o.writeUint8Array(this.data),this.size+=this.data.length,e.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},l.VisualSampleEntry.prototype.write=function(o){this.writeHeader(o),this.size+=2*7+6*4+32,o.writeUint16(0),o.writeUint16(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint16(this.width),o.writeUint16(this.height),o.writeUint32(this.horizresolution),o.writeUint32(this.vertresolution),o.writeUint32(0),o.writeUint16(this.frame_count),o.writeUint8(Math.min(31,this.compressorname.length)),o.writeString(this.compressorname,null,31),o.writeUint16(this.depth),o.writeInt16(-1),this.writeFooter(o)},l.AudioSampleEntry.prototype.write=function(o){this.writeHeader(o),this.size+=2*4+3*4,o.writeUint32(0),o.writeUint32(0),o.writeUint16(this.channel_count),o.writeUint16(this.samplesize),o.writeUint16(0),o.writeUint16(0),o.writeUint32(this.samplerate<<16),this.writeFooter(o)},l.stppSampleEntry.prototype.write=function(o){this.writeHeader(o),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,o.writeCString(this.namespace),o.writeCString(this.schema_location),o.writeCString(this.auxiliary_mime_types),this.writeFooter(o)},l.SampleGroupEntry.prototype.write=function(o){o.writeUint8Array(this.data)},l.sbgpBox.prototype.write=function(o){this.version=1,this.flags=0,this.size=12+8*this.entries.length,this.writeHeader(o),o.writeString(this.grouping_type,null,4),o.writeUint32(this.grouping_type_parameter),o.writeUint32(this.entries.length);for(var c=0;c<this.entries.length;c++){var f=this.entries[c];o.writeInt32(f.sample_count),o.writeInt32(f.group_description_index)}},l.sgpdBox.prototype.write=function(o){var c,f;for(this.flags=0,this.size=12,c=0;c<this.entries.length;c++)f=this.entries[c],this.version===1&&(this.default_length===0&&(this.size+=4),this.size+=f.data.length);for(this.writeHeader(o),o.writeString(this.grouping_type,null,4),this.version===1&&o.writeUint32(this.default_length),this.version>=2&&o.writeUint32(this.default_sample_description_index),o.writeUint32(this.entries.length),c=0;c<this.entries.length;c++)f=this.entries[c],this.version===1&&this.default_length===0&&o.writeUint32(f.description_length),f.write(o)},l.sidxBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4*4+2+2+12*this.references.length,this.writeHeader(o),o.writeUint32(this.reference_ID),o.writeUint32(this.timescale),o.writeUint32(this.earliest_presentation_time),o.writeUint32(this.first_offset),o.writeUint16(0),o.writeUint16(this.references.length);for(var c=0;c<this.references.length;c++){var f=this.references[c];o.writeUint32(f.reference_type<<31|f.referenced_size),o.writeUint32(f.subsegment_duration),o.writeUint32(f.starts_with_SAP<<31|f.SAP_type<<28|f.SAP_delta_time)}},l.smhdBox.prototype.write=function(o){this.version=0,this.flags=1,this.size=4,this.writeHeader(o),o.writeUint16(this.balance),o.writeUint16(0)},l.stcoBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(o),o.writeUint32(this.chunk_offsets.length),o.writeUint32Array(this.chunk_offsets)},l.stscBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(o),o.writeUint32(this.first_chunk.length),c=0;c<this.first_chunk.length;c++)o.writeUint32(this.first_chunk[c]),o.writeUint32(this.samples_per_chunk[c]),o.writeUint32(this.sample_description_index[c])},l.stsdBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=0,this.writeHeader(o),o.writeUint32(this.entries.length),this.size+=4,c=0;c<this.entries.length;c++)this.entries[c].write(o),this.size+=this.entries[c].size;e.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},l.stshBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(o),o.writeUint32(this.shadowed_sample_numbers.length),c=0;c<this.shadowed_sample_numbers.length;c++)o.writeUint32(this.shadowed_sample_numbers[c]),o.writeUint32(this.sync_sample_numbers[c])},l.stssBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(o),o.writeUint32(this.sample_numbers.length),o.writeUint32Array(this.sample_numbers)},l.stszBox.prototype.write=function(o){var c,f=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0)for(c=0;c+1<this.sample_sizes.length;)if(this.sample_sizes[c+1]!==this.sample_sizes[0]){f=!1;break}else c++;else f=!1;this.size=8,f||(this.size+=4*this.sample_sizes.length),this.writeHeader(o),f?o.writeUint32(this.sample_sizes[0]):o.writeUint32(0),o.writeUint32(this.sample_sizes.length),f||o.writeUint32Array(this.sample_sizes)},l.sttsBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(o),o.writeUint32(this.sample_counts.length),c=0;c<this.sample_counts.length;c++)o.writeUint32(this.sample_counts[c]),o.writeUint32(this.sample_deltas[c])},l.tfdtBox.prototype.write=function(o){var c=Math.pow(2,32)-1;this.version=this.baseMediaDecodeTime>c?1:0,this.flags=0,this.size=4,this.version===1&&(this.size+=4),this.writeHeader(o),this.version===1?o.writeUint64(this.baseMediaDecodeTime):o.writeUint32(this.baseMediaDecodeTime)},l.tfhdBox.prototype.write=function(o){this.version=0,this.size=4,this.flags&l.TFHD_FLAG_BASE_DATA_OFFSET&&(this.size+=8),this.flags&l.TFHD_FLAG_SAMPLE_DESC&&(this.size+=4),this.flags&l.TFHD_FLAG_SAMPLE_DUR&&(this.size+=4),this.flags&l.TFHD_FLAG_SAMPLE_SIZE&&(this.size+=4),this.flags&l.TFHD_FLAG_SAMPLE_FLAGS&&(this.size+=4),this.writeHeader(o),o.writeUint32(this.track_id),this.flags&l.TFHD_FLAG_BASE_DATA_OFFSET&&o.writeUint64(this.base_data_offset),this.flags&l.TFHD_FLAG_SAMPLE_DESC&&o.writeUint32(this.default_sample_description_index),this.flags&l.TFHD_FLAG_SAMPLE_DUR&&o.writeUint32(this.default_sample_duration),this.flags&l.TFHD_FLAG_SAMPLE_SIZE&&o.writeUint32(this.default_sample_size),this.flags&l.TFHD_FLAG_SAMPLE_FLAGS&&o.writeUint32(this.default_sample_flags)},l.tkhdBox.prototype.write=function(o){this.version=0,this.size=4*18+2*4,this.writeHeader(o),o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.track_id),o.writeUint32(0),o.writeUint32(this.duration),o.writeUint32(0),o.writeUint32(0),o.writeInt16(this.layer),o.writeInt16(this.alternate_group),o.writeInt16(this.volume<<8),o.writeUint16(0),o.writeInt32Array(this.matrix),o.writeUint32(this.width),o.writeUint32(this.height)},l.trexBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(o),o.writeUint32(this.track_id),o.writeUint32(this.default_sample_description_index),o.writeUint32(this.default_sample_duration),o.writeUint32(this.default_sample_size),o.writeUint32(this.default_sample_flags)},l.trunBox.prototype.write=function(o){this.version=0,this.size=4,this.flags&l.TRUN_FLAGS_DATA_OFFSET&&(this.size+=4),this.flags&l.TRUN_FLAGS_FIRST_FLAG&&(this.size+=4),this.flags&l.TRUN_FLAGS_DURATION&&(this.size+=4*this.sample_duration.length),this.flags&l.TRUN_FLAGS_SIZE&&(this.size+=4*this.sample_size.length),this.flags&l.TRUN_FLAGS_FLAGS&&(this.size+=4*this.sample_flags.length),this.flags&l.TRUN_FLAGS_CTS_OFFSET&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(o),o.writeUint32(this.sample_count),this.flags&l.TRUN_FLAGS_DATA_OFFSET&&(this.data_offset_position=o.getPosition(),o.writeInt32(this.data_offset)),this.flags&l.TRUN_FLAGS_FIRST_FLAG&&o.writeUint32(this.first_sample_flags);for(var c=0;c<this.sample_count;c++)this.flags&l.TRUN_FLAGS_DURATION&&o.writeUint32(this.sample_duration[c]),this.flags&l.TRUN_FLAGS_SIZE&&o.writeUint32(this.sample_size[c]),this.flags&l.TRUN_FLAGS_FLAGS&&o.writeUint32(this.sample_flags[c]),this.flags&l.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?o.writeUint32(this.sample_composition_time_offset[c]):o.writeInt32(this.sample_composition_time_offset[c]))},l["url Box"].prototype.write=function(o){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(o),this.location&&o.writeCString(this.location)},l["urn Box"].prototype.write=function(o){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(o),o.writeCString(this.name),this.location&&o.writeCString(this.location)},l.vmhdBox.prototype.write=function(o){this.version=0,this.flags=1,this.size=8,this.writeHeader(o),o.writeUint16(this.graphicsmode),o.writeUint16Array(this.opcolor)},l.cttsBox.prototype.unpack=function(o){var c,f,m;for(m=0,c=0;c<this.sample_counts.length;c++)for(f=0;f<this.sample_counts[c];f++)o[m].pts=o[m].dts+this.sample_offsets[c],m++},l.sttsBox.prototype.unpack=function(o){var c,f,m;for(m=0,c=0;c<this.sample_counts.length;c++)for(f=0;f<this.sample_counts[c];f++)m===0?o[m].dts=0:o[m].dts=o[m-1].dts+this.sample_deltas[c],m++},l.stcoBox.prototype.unpack=function(o){var c;for(c=0;c<this.chunk_offsets.length;c++)o[c].offset=this.chunk_offsets[c]},l.stscBox.prototype.unpack=function(o){var c,f,m,S,T;for(S=0,T=0,c=0;c<this.first_chunk.length;c++)for(f=0;f<(c+1<this.first_chunk.length?this.first_chunk[c+1]:1/0);f++)for(T++,m=0;m<this.samples_per_chunk[c];m++){if(o[S])o[S].description_index=this.sample_description_index[c],o[S].chunk_index=T;else return;S++}},l.stszBox.prototype.unpack=function(o){var c;for(c=0;c<this.sample_sizes.length;c++)o[c].size=this.sample_sizes[c]},l.DIFF_BOXES_PROP_NAMES=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],l.DIFF_PRIMITIVE_ARRAY_PROP_NAMES=["compatible_brands","matrix","opcolor","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"],l.boxEqualFields=function(o,c){if(o&&!c)return!1;var f;for(f in o)if(!(l.DIFF_BOXES_PROP_NAMES.indexOf(f)>-1)){if(o[f]instanceof l.Box||c[f]instanceof l.Box)continue;if(typeof o[f]>"u"||typeof c[f]>"u")continue;if(typeof o[f]=="function"||typeof c[f]=="function")continue;if(o.subBoxNames&&o.subBoxNames.indexOf(f.slice(0,4))>-1||c.subBoxNames&&c.subBoxNames.indexOf(f.slice(0,4))>-1)continue;if(f==="data"||f==="start"||f==="size"||f==="creation_time"||f==="modification_time")continue;if(l.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(f)>-1)continue;if(o[f]!==c[f])return!1}return!0},l.boxEqual=function(o,c){if(!l.boxEqualFields(o,c))return!1;for(var f=0;f<l.DIFF_BOXES_PROP_NAMES.length;f++){var m=l.DIFF_BOXES_PROP_NAMES[f];if(o[m]&&c[m]&&!l.boxEqual(o[m],c[m]))return!1}return!0};var g=function(){};g.prototype.parseSample=function(o){var c,f,m=new t(o.buffer);for(c=[];!m.isEos();)f=l.parseOneBox(m,!1),f.code===l.OK&&f.box.type==="vttc"&&c.push(f.box);return c},g.prototype.getText=function(o,c,f){function m(L,w,C){return C=C||"0",L=L+"",L.length>=w?L:new Array(w-L.length+1).join(C)+L}function S(L){var w=Math.floor(L/3600),C=Math.floor((L-w*3600)/60),k=Math.floor(L-w*3600-C*60),U=Math.floor((L-w*3600-C*60-k)*1e3);return""+m(w,2)+":"+m(C,2)+":"+m(k,2)+"."+m(U,3)}for(var T=this.parseSample(f),b="",A=0;A<T.length;A++){var I=T[A];b+=S(o)+" --> "+S(c)+`\r
|
|
145
|
-
`,b+=I.payl.text}return b};var y=function(){};y.prototype.parseSample=function(o){var c={},f;c.resources=[];var m=new t(o.data.buffer);if(!o.subsamples||o.subsamples.length===0)c.documentString=m.readString(o.data.length);else if(c.documentString=m.readString(o.subsamples[0].size),o.subsamples.length>1)for(f=1;f<o.subsamples.length;f++)c.resources[f]=m.readUint8Array(o.subsamples[f].size);return typeof DOMParser<"u"&&(c.document=new DOMParser().parseFromString(c.documentString,"application/xml")),c};var v=function(){};v.prototype.parseSample=function(o){var c,f=new t(o.data.buffer);return c=f.readString(o.data.length),c},v.prototype.parseConfig=function(o){var c,f=new t(o.buffer);return f.readUint32(),c=f.readCString(),c},r.VTTin4Parser=g,r.XMLSubtitlein4Parser=y,r.Textin4Parser=v;var x=function(o){this.stream=o||new a,this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.onMoovStart=null,this.moovStartSent=!1,this.onReady=null,this.readySent=!1,this.onSegment=null,this.onSamples=null,this.onError=null,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.items=[],this.entity_groups=[],this.onSidx=null,this.sidxSent=!1};x.prototype.setSegmentOptions=function(o,c,f){var m=this.getTrackById(o);if(m){var S={};this.fragmentedTracks.push(S),S.id=o,S.user=c,S.trak=m,m.nextSample=0,S.segmentStream=null,S.nb_samples=1e3,S.rapAlignement=!0,f&&(f.nbSamples&&(S.nb_samples=f.nbSamples),f.rapAlignement&&(S.rapAlignement=f.rapAlignement))}},x.prototype.unsetSegmentOptions=function(o){for(var c=-1,f=0;f<this.fragmentedTracks.length;f++){var m=this.fragmentedTracks[f];m.id==o&&(c=f)}c>-1&&this.fragmentedTracks.splice(c,1)},x.prototype.setExtractionOptions=function(o,c,f){var m=this.getTrackById(o);if(m){var S={};this.extractedTracks.push(S),S.id=o,S.user=c,S.trak=m,m.nextSample=0,S.nb_samples=1e3,S.samples=[],f&&f.nbSamples&&(S.nb_samples=f.nbSamples)}},x.prototype.unsetExtractionOptions=function(o){for(var c=-1,f=0;f<this.extractedTracks.length;f++){var m=this.extractedTracks[f];m.id==o&&(c=f)}c>-1&&this.extractedTracks.splice(c,1)},x.prototype.parse=function(){var o,c,f=!1;if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else if(this.saveParsePosition&&this.saveParsePosition(),o=l.parseOneBox(this.stream,f),o.code===l.ERR_NOT_ENOUGH_DATA)if(this.processIncompleteBox){if(this.processIncompleteBox(o))continue;return}else return;else{var m;switch(c=o.box,m=c.type!=="uuid"?c.type:c.uuid,this.boxes.push(c),m){case"mdat":this.mdats.push(c);break;case"moof":this.moofs.push(c);break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[m]!==void 0&&e.warn("ISOFile","Duplicate Box of type: "+m+", overriding previous occurrence"),this[m]=c;break}this.updateUsedBytes&&this.updateUsedBytes(c,o)}},x.prototype.checkBuffer=function(o){if(o==null)throw"Buffer must be defined and non empty";if(o.fileStart===void 0)throw"Buffer must have a fileStart property";return o.byteLength===0?(e.warn("ISOFile","Ignoring empty buffer (fileStart: "+o.fileStart+")"),this.stream.logBufferLevel(),!1):(e.info("ISOFile","Processing buffer (fileStart: "+o.fileStart+")"),o.usedBytes=0,this.stream.insertBuffer(o),this.stream.logBufferLevel(),this.stream.initialized()?!0:(e.warn("ISOFile","Not ready to start parsing"),!1))},x.prototype.appendBuffer=function(o,c){var f;if(this.checkBuffer(o))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(c),this.nextSeekPosition?(f=this.nextSeekPosition,this.nextSeekPosition=void 0):f=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(f=this.stream.getEndFilePositionAfter(f))):this.nextParsePosition?f=this.nextParsePosition:f=0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(e.info("ISOFile","Done processing buffer (fileStart: "+o.fileStart+") - next buffer to fetch should have a fileStart position of "+f),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),e.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),f},x.prototype.getInfo=function(){var o,c,f={},m,S,T,b,A=new Date("1904-01-01T00:00:00Z").getTime();if(this.moov)for(f.hasMoov=!0,f.duration=this.moov.mvhd.duration,f.timescale=this.moov.mvhd.timescale,f.isFragmented=this.moov.mvex!=null,f.isFragmented&&this.moov.mvex.mehd&&(f.fragment_duration=this.moov.mvex.mehd.fragment_duration),f.isProgressive=this.isProgressive,f.hasIOD=this.moov.iods!=null,f.brands=[],f.brands.push(this.ftyp.major_brand),f.brands=f.brands.concat(this.ftyp.compatible_brands),f.created=new Date(A+this.moov.mvhd.creation_time*1e3),f.modified=new Date(A+this.moov.mvhd.modification_time*1e3),f.tracks=[],f.audioTracks=[],f.videoTracks=[],f.subtitleTracks=[],f.metadataTracks=[],f.hintTracks=[],f.otherTracks=[],o=0;o<this.moov.traks.length;o++){if(m=this.moov.traks[o],b=m.mdia.minf.stbl.stsd.entries[0],S={},f.tracks.push(S),S.id=m.tkhd.track_id,S.name=m.mdia.hdlr.name,S.references=[],m.tref)for(c=0;c<m.tref.boxes.length;c++)T={},S.references.push(T),T.type=m.tref.boxes[c].type,T.track_ids=m.tref.boxes[c].track_ids;m.edts&&(S.edits=m.edts.elst.entries),S.created=new Date(A+m.tkhd.creation_time*1e3),S.modified=new Date(A+m.tkhd.modification_time*1e3),S.movie_duration=m.tkhd.duration,S.movie_timescale=f.timescale,S.layer=m.tkhd.layer,S.alternate_group=m.tkhd.alternate_group,S.volume=m.tkhd.volume,S.matrix=m.tkhd.matrix,S.track_width=m.tkhd.width/65536,S.track_height=m.tkhd.height/65536,S.timescale=m.mdia.mdhd.timescale,S.cts_shift=m.mdia.minf.stbl.cslg,S.duration=m.mdia.mdhd.duration,S.samples_duration=m.samples_duration,S.codec=b.getCodec(),S.kind=m.udta&&m.udta.kinds.length?m.udta.kinds[0]:{schemeURI:"",value:""},S.language=m.mdia.elng?m.mdia.elng.extended_language:m.mdia.mdhd.languageString,S.nb_samples=m.samples.length,S.size=m.samples_size,S.bitrate=S.size*8*S.timescale/S.samples_duration,b.isAudio()?(S.type="audio",f.audioTracks.push(S),S.audio={},S.audio.sample_rate=b.getSampleRate(),S.audio.channel_count=b.getChannelCount(),S.audio.sample_size=b.getSampleSize()):b.isVideo()?(S.type="video",f.videoTracks.push(S),S.video={},S.video.width=b.getWidth(),S.video.height=b.getHeight()):b.isSubtitle()?(S.type="subtitles",f.subtitleTracks.push(S)):b.isHint()?(S.type="metadata",f.hintTracks.push(S)):b.isMetadata()?(S.type="metadata",f.metadataTracks.push(S)):(S.type="metadata",f.otherTracks.push(S))}else f.hasMoov=!1;if(f.mime="",f.hasMoov&&f.tracks){for(f.videoTracks&&f.videoTracks.length>0?f.mime+='video/mp4; codecs="':f.audioTracks&&f.audioTracks.length>0?f.mime+='audio/mp4; codecs="':f.mime+='application/mp4; codecs="',o=0;o<f.tracks.length;o++)o!==0&&(f.mime+=","),f.mime+=f.tracks[o].codec;f.mime+='"; profiles="',f.mime+=this.ftyp.compatible_brands.join(),f.mime+='"'}return f},x.prototype.setNextSeekPositionFromSample=function(o){o&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(o.offset+o.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=o.offset+o.alreadyRead)},x.prototype.processSamples=function(o){var c,f;if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==null)for(c=0;c<this.fragmentedTracks.length;c++){var m=this.fragmentedTracks[c];for(f=m.trak;f.nextSample<f.samples.length&&this.sampleProcessingStarted;){e.debug("ISOFile","Creating media fragment on track #"+m.id+" for sample "+f.nextSample);var S=this.createFragment(m.id,f.nextSample,m.segmentStream);if(S)m.segmentStream=S,f.nextSample++;else break;if((f.nextSample%m.nb_samples===0||o||f.nextSample>=f.samples.length)&&(e.info("ISOFile","Sending fragmented data on track #"+m.id+" for samples ["+Math.max(0,f.nextSample-m.nb_samples)+","+(f.nextSample-1)+"]"),e.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(m.id,m.user,m.segmentStream.buffer,f.nextSample,o||f.nextSample>=f.samples.length),m.segmentStream=null,m!==this.fragmentedTracks[c]))break}}if(this.onSamples!==null)for(c=0;c<this.extractedTracks.length;c++){var T=this.extractedTracks[c];for(f=T.trak;f.nextSample<f.samples.length&&this.sampleProcessingStarted;){e.debug("ISOFile","Exporting on track #"+T.id+" sample #"+f.nextSample);var b=this.getSample(f,f.nextSample);if(b)f.nextSample++,T.samples.push(b);else{this.setNextSeekPositionFromSample(f.samples[f.nextSample]);break}if((f.nextSample%T.nb_samples===0||f.nextSample>=f.samples.length)&&(e.debug("ISOFile","Sending samples on track #"+T.id+" for sample "+f.nextSample),this.onSamples&&this.onSamples(T.id,T.user,T.samples),T.samples=[],T!==this.extractedTracks[c]))break}}}},x.prototype.getBox=function(o){var c=this.getBoxes(o,!0);return c.length?c[0]:null},x.prototype.getBoxes=function(o,c){var f=[];return x._sweep.call(this,o,f,c),f},x._sweep=function(o,c,f){this.type&&this.type==o&&c.push(this);for(var m in this.boxes){if(c.length&&f)return;x._sweep.call(this.boxes[m],o,c,f)}},x.prototype.getTrackSamplesInfo=function(o){var c=this.getTrackById(o);if(c)return c.samples},x.prototype.getTrackSample=function(o,c){var f=this.getTrackById(o),m=this.getSample(f,c);return m},x.prototype.releaseUsedSamples=function(o,c){var f=0,m=this.getTrackById(o);m.lastValidSample||(m.lastValidSample=0);for(var S=m.lastValidSample;S<c;S++)f+=this.releaseSample(m,S);e.info("ISOFile","Track #"+o+" released samples up to "+c+" (released size: "+f+", remaining: "+this.samplesDataSize+")"),m.lastValidSample=c},x.prototype.start=function(){this.sampleProcessingStarted=!0,this.processSamples(!1)},x.prototype.stop=function(){this.sampleProcessingStarted=!1},x.prototype.flush=function(){e.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)},x.prototype.seekTrack=function(o,c,f){var m,S,T=1/0,b=0,A=0,I;if(f.samples.length===0)return e.info("ISOFile","No sample in track, cannot seek! Using time "+e.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(m=0;m<f.samples.length;m++){if(S=f.samples[m],m===0)A=0,I=S.timescale;else if(S.cts>o*S.timescale){A=m-1;break}c&&S.is_sync&&(b=m)}for(c&&(A=b),o=f.samples[A].cts,f.nextSample=A;f.samples[A].alreadyRead===f.samples[A].size&&f.samples[A+1];)A++;return T=f.samples[A].offset+f.samples[A].alreadyRead,e.info("ISOFile","Seeking to "+(c?"RAP":"")+" sample #"+f.nextSample+" on track "+f.tkhd.track_id+", time "+e.getDurationString(o,I)+" and offset: "+T),{offset:T,time:o/I}},x.prototype.getTrackDuration=function(o){var c;return o.samples?(c=o.samples[o.samples.length-1],(c.cts+c.duration)/c.timescale):1/0},x.prototype.seek=function(o,c){var f=this.moov,m,S,T,b={offset:1/0,time:1/0};if(this.moov){for(T=0;T<f.traks.length;T++)m=f.traks[T],!(o>this.getTrackDuration(m))&&(S=this.seekTrack(o,c,m),S.offset<b.offset&&(b.offset=S.offset),S.time<b.time&&(b.time=S.time));return e.info("ISOFile","Seeking at time "+e.getDurationString(b.time,1)+" needs a buffer with a fileStart position of "+b.offset),b.offset===1/0?b={offset:this.nextParsePosition,time:0}:b.offset=this.stream.getEndFilePositionAfter(b.offset),e.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+b.offset),b}else throw"Cannot seek: moov not received!"},x.prototype.equal=function(o){for(var c=0;c<this.boxes.length&&c<o.boxes.length;){var f=this.boxes[c],m=o.boxes[c];if(!l.boxEqual(f,m))return!1;c++}return!0},r.ISOFile=x,x.prototype.lastBoxStartPosition=0,x.prototype.parsingMdat=null,x.prototype.nextParsePosition=0,x.prototype.discardMdatData=!1,x.prototype.processIncompleteBox=function(o){var c,f,m;return o.type==="mdat"?(c=new l[o.type+"Box"](o.size),this.parsingMdat=c,this.boxes.push(c),this.mdats.push(c),c.start=o.start,c.hdr_size=o.hdr_size,this.stream.addUsedBytes(c.hdr_size),this.lastBoxStartPosition=c.start+c.size,m=this.stream.seek(c.start+c.size,!1,this.discardMdatData),m?(this.parsingMdat=null,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=c.start+c.size,!1)):(o.type==="moov"&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),f=this.stream.mergeNextBuffer?this.stream.mergeNextBuffer():!1,f?(this.nextParsePosition=this.stream.getEndPosition(),!0):(o.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+o.size:this.nextParsePosition=this.stream.getEndPosition(),!1))},x.prototype.hasIncompleteMdat=function(){return this.parsingMdat!==null},x.prototype.processIncompleteMdat=function(){var o,c;return o=this.parsingMdat,c=this.stream.seek(o.start+o.size,!1,this.discardMdatData),c?(e.debug("ISOFile","Found 'mdat' end in buffered data"),this.parsingMdat=null,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)},x.prototype.restoreParsePosition=function(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)},x.prototype.saveParsePosition=function(){this.lastBoxStartPosition=this.stream.getPosition()},x.prototype.updateUsedBytes=function(o,c){this.stream.addUsedBytes&&(o.type==="mdat"?(this.stream.addUsedBytes(o.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(o.size-o.hdr_size)):this.stream.addUsedBytes(o.size))},x.prototype.add=l.Box.prototype.add,x.prototype.addBox=l.Box.prototype.addBox,x.prototype.init=function(o){var c=o||{};this.add("ftyp").set("major_brand",c.brands&&c.brands[0]||"iso4").set("minor_version",0).set("compatible_brands",c.brands||["iso4"]);var f=this.add("moov");return f.add("mvhd").set("timescale",c.timescale||600).set("rate",c.rate||65536).set("creation_time",0).set("modification_time",0).set("duration",c.duration||0).set("volume",c.width?0:256).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("next_track_id",1),f.add("mvex"),this},x.prototype.addTrack=function(o){this.moov||this.init(o);var c=o||{};c.width=c.width||320,c.height=c.height||320,c.id=c.id||this.moov.mvhd.next_track_id,c.type=c.type||"avc1";var f=this.moov.add("trak");this.moov.mvhd.next_track_id=c.id+1,f.add("tkhd").set("flags",l.TKHD_FLAG_ENABLED|l.TKHD_FLAG_IN_MOVIE|l.TKHD_FLAG_IN_PREVIEW).set("creation_time",0).set("modification_time",0).set("track_id",c.id).set("duration",c.duration||0).set("layer",c.layer||0).set("alternate_group",0).set("volume",1).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("width",c.width<<16).set("height",c.height<<16);var m=f.add("mdia");m.add("mdhd").set("creation_time",0).set("modification_time",0).set("timescale",c.timescale||1).set("duration",c.media_duration||0).set("language",c.language||"und"),m.add("hdlr").set("handler",c.hdlr||"vide").set("name",c.name||"Track created with MP4Box.js"),m.add("elng").set("extended_language",c.language||"fr-FR");var S=m.add("minf");if(l[c.type+"SampleEntry"]!==void 0){var T=new l[c.type+"SampleEntry"];T.data_reference_index=1;var b="";for(var A in l.sampleEntryCodes)for(var I=l.sampleEntryCodes[A],L=0;L<I.length;L++)if(I.indexOf(c.type)>-1){b=A;break}switch(b){case"Visual":if(S.add("vmhd").set("graphicsmode",0).set("opcolor",[0,0,0]),T.set("width",c.width).set("height",c.height).set("horizresolution",72<<16).set("vertresolution",72<<16).set("frame_count",1).set("compressorname",c.type+" Compressor").set("depth",24),c.avcDecoderConfigRecord){var w=new l.avcCBox;w.parse(new t(c.avcDecoderConfigRecord)),T.addBox(w)}else if(c.hevcDecoderConfigRecord){var C=new l.hvcCBox;C.parse(new t(c.hevcDecoderConfigRecord)),T.addBox(C)}break;case"Audio":S.add("smhd").set("balance",c.balance||0),T.set("channel_count",c.channel_count||2).set("samplesize",c.samplesize||16).set("samplerate",c.samplerate||65536);break;case"Hint":S.add("hmhd");break;case"Subtitle":switch(S.add("sthd"),c.type){case"stpp":T.set("namespace",c.namespace||"nonamespace").set("schema_location",c.schema_location||"").set("auxiliary_mime_types",c.auxiliary_mime_types||"");break}break;case"Metadata":S.add("nmhd");break;case"System":S.add("nmhd");break;default:S.add("nmhd");break}c.description&&T.addBox(c.description),c.description_boxes&&c.description_boxes.forEach(function(U){T.addBox(U)}),S.add("dinf").add("dref").addEntry(new l["url Box"]().set("flags",1));var k=S.add("stbl");return k.add("stsd").addEntry(T),k.add("stts").set("sample_counts",[]).set("sample_deltas",[]),k.add("stsc").set("first_chunk",[]).set("samples_per_chunk",[]).set("sample_description_index",[]),k.add("stco").set("chunk_offsets",[]),k.add("stsz").set("sample_sizes",[]),this.moov.mvex.add("trex").set("track_id",c.id).set("default_sample_description_index",c.default_sample_description_index||1).set("default_sample_duration",c.default_sample_duration||0).set("default_sample_size",c.default_sample_size||0).set("default_sample_flags",c.default_sample_flags||0),this.buildTrakSampleLists(f),c.id}},l.Box.prototype.computeSize=function(o){var c=o||new s;c.endianness=s.BIG_ENDIAN,this.write(c)},x.prototype.addSample=function(o,c,f){var m=f||{},S={},T=this.getTrackById(o);if(T!==null){S.number=T.samples.length,S.track_id=T.tkhd.track_id,S.timescale=T.mdia.mdhd.timescale,S.description_index=m.sample_description_index?m.sample_description_index-1:0,S.description=T.mdia.minf.stbl.stsd.entries[S.description_index],S.data=c,S.size=c.byteLength,S.alreadyRead=S.size,S.duration=m.duration||1,S.cts=m.cts||0,S.dts=m.dts||0,S.is_sync=m.is_sync||!1,S.is_leading=m.is_leading||0,S.depends_on=m.depends_on||0,S.is_depended_on=m.is_depended_on||0,S.has_redundancy=m.has_redundancy||0,S.degradation_priority=m.degradation_priority||0,S.offset=0,S.subsamples=m.subsamples,T.samples.push(S),T.samples_size+=S.size,T.samples_duration+=S.duration,T.first_dts===void 0&&(T.first_dts=m.dts),this.processSamples();var b=this.createSingleSampleMoof(S);return this.addBox(b),b.computeSize(),b.trafs[0].truns[0].data_offset=b.size+8,this.add("mdat").data=new Uint8Array(c),S}},x.prototype.createSingleSampleMoof=function(o){var c=0;o.is_sync?c=1<<25:c=65536;var f=new l.moofBox;f.add("mfhd").set("sequence_number",this.nextMoofNumber),this.nextMoofNumber++;var m=f.add("traf"),S=this.getTrackById(o.track_id);return m.add("tfhd").set("track_id",o.track_id).set("flags",l.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),m.add("tfdt").set("baseMediaDecodeTime",o.dts-(S.first_dts||0)),m.add("trun").set("flags",l.TRUN_FLAGS_DATA_OFFSET|l.TRUN_FLAGS_DURATION|l.TRUN_FLAGS_SIZE|l.TRUN_FLAGS_FLAGS|l.TRUN_FLAGS_CTS_OFFSET).set("data_offset",0).set("first_sample_flags",0).set("sample_count",1).set("sample_duration",[o.duration]).set("sample_size",[o.size]).set("sample_flags",[c]).set("sample_composition_time_offset",[o.cts-o.dts]),f},x.prototype.lastMoofIndex=0,x.prototype.samplesDataSize=0,x.prototype.resetTables=function(){var o,c,f,m,S,T,b,A;for(this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0,o=0;o<this.moov.traks.length;o++){c=this.moov.traks[o],c.tkhd.duration=0,c.mdia.mdhd.duration=0,f=c.mdia.minf.stbl.stco||c.mdia.minf.stbl.co64,f.chunk_offsets=[],m=c.mdia.minf.stbl.stsc,m.first_chunk=[],m.samples_per_chunk=[],m.sample_description_index=[],S=c.mdia.minf.stbl.stsz||c.mdia.minf.stbl.stz2,S.sample_sizes=[],T=c.mdia.minf.stbl.stts,T.sample_counts=[],T.sample_deltas=[],b=c.mdia.minf.stbl.ctts,b&&(b.sample_counts=[],b.sample_offsets=[]),A=c.mdia.minf.stbl.stss;var I=c.mdia.minf.stbl.boxes.indexOf(A);I!=-1&&(c.mdia.minf.stbl.boxes[I]=null)}},x.initSampleGroups=function(o,c,f,m,S){var T,b,A,I;function L(w,C,k){this.grouping_type=w,this.grouping_type_parameter=C,this.sbgp=k,this.last_sample_in_run=-1,this.entry_index=-1}for(c&&(c.sample_groups_info=[]),o.sample_groups_info||(o.sample_groups_info=[]),b=0;b<f.length;b++){for(I=f[b].grouping_type+"/"+f[b].grouping_type_parameter,A=new L(f[b].grouping_type,f[b].grouping_type_parameter,f[b]),c&&(c.sample_groups_info[I]=A),o.sample_groups_info[I]||(o.sample_groups_info[I]=A),T=0;T<m.length;T++)m[T].grouping_type===f[b].grouping_type&&(A.description=m[T],A.description.used=!0);if(S)for(T=0;T<S.length;T++)S[T].grouping_type===f[b].grouping_type&&(A.fragment_description=S[T],A.fragment_description.used=!0,A.is_fragment=!0)}if(c){if(S)for(b=0;b<S.length;b++)!S[b].used&&S[b].version>=2&&(I=S[b].grouping_type+"/0",A=new L(S[b].grouping_type,0),A.is_fragment=!0,c.sample_groups_info[I]||(c.sample_groups_info[I]=A))}else for(b=0;b<m.length;b++)!m[b].used&&m[b].version>=2&&(I=m[b].grouping_type+"/0",A=new L(m[b].grouping_type,0),o.sample_groups_info[I]||(o.sample_groups_info[I]=A))},x.setSampleGroupProperties=function(o,c,f,m){var S,T;c.sample_groups=[];for(S in m)if(c.sample_groups[S]={},c.sample_groups[S].grouping_type=m[S].grouping_type,c.sample_groups[S].grouping_type_parameter=m[S].grouping_type_parameter,f>=m[S].last_sample_in_run&&(m[S].last_sample_in_run<0&&(m[S].last_sample_in_run=0),m[S].entry_index++,m[S].entry_index<=m[S].sbgp.entries.length-1&&(m[S].last_sample_in_run+=m[S].sbgp.entries[m[S].entry_index].sample_count)),m[S].entry_index<=m[S].sbgp.entries.length-1?c.sample_groups[S].group_description_index=m[S].sbgp.entries[m[S].entry_index].group_description_index:c.sample_groups[S].group_description_index=-1,c.sample_groups[S].group_description_index!==0){var b;m[S].fragment_description?b=m[S].fragment_description:b=m[S].description,c.sample_groups[S].group_description_index>0?(c.sample_groups[S].group_description_index>65535?T=(c.sample_groups[S].group_description_index>>16)-1:T=c.sample_groups[S].group_description_index-1,b&&T>=0&&(c.sample_groups[S].description=b.entries[T])):b&&b.version>=2&&b.default_group_description_index>0&&(c.sample_groups[S].description=b.entries[b.default_group_description_index-1])}},x.process_sdtp=function(o,c,f){c&&(o?(c.is_leading=o.is_leading[f],c.depends_on=o.sample_depends_on[f],c.is_depended_on=o.sample_is_depended_on[f],c.has_redundancy=o.sample_has_redundancy[f]):(c.is_leading=0,c.depends_on=0,c.is_depended_on=0,c.has_redundancy=0))},x.prototype.buildSampleLists=function(){var o,c;for(o=0;o<this.moov.traks.length;o++)c=this.moov.traks[o],this.buildTrakSampleLists(c)},x.prototype.buildTrakSampleLists=function(o){var c,f,m,S,T,b,A,I,L,w,C,k,U,G,$,z,j,Y,F,O,te,ee,se,he;if(o.samples=[],o.samples_duration=0,o.samples_size=0,f=o.mdia.minf.stbl.stco||o.mdia.minf.stbl.co64,m=o.mdia.minf.stbl.stsc,S=o.mdia.minf.stbl.stsz||o.mdia.minf.stbl.stz2,T=o.mdia.minf.stbl.stts,b=o.mdia.minf.stbl.ctts,A=o.mdia.minf.stbl.stss,I=o.mdia.minf.stbl.stsd,L=o.mdia.minf.stbl.subs,k=o.mdia.minf.stbl.stdp,w=o.mdia.minf.stbl.sbgps,C=o.mdia.minf.stbl.sgpds,Y=-1,F=-1,O=-1,te=-1,ee=0,se=0,he=0,x.initSampleGroups(o,null,w,C),!(typeof S>"u")){for(c=0;c<S.sample_sizes.length;c++){var W={};W.number=c,W.track_id=o.tkhd.track_id,W.timescale=o.mdia.mdhd.timescale,W.alreadyRead=0,o.samples[c]=W,W.size=S.sample_sizes[c],o.samples_size+=W.size,c===0?(G=1,U=0,W.chunk_index=G,W.chunk_run_index=U,j=m.samples_per_chunk[U],z=0,U+1<m.first_chunk.length?$=m.first_chunk[U+1]-1:$=1/0):c<j?(W.chunk_index=G,W.chunk_run_index=U):(G++,W.chunk_index=G,z=0,G<=$||(U++,U+1<m.first_chunk.length?$=m.first_chunk[U+1]-1:$=1/0),W.chunk_run_index=U,j+=m.samples_per_chunk[U]),W.description_index=m.sample_description_index[W.chunk_run_index]-1,W.description=I.entries[W.description_index],W.offset=f.chunk_offsets[W.chunk_index-1]+z,z+=W.size,c>Y&&(F++,Y<0&&(Y=0),Y+=T.sample_counts[F]),c>0?(o.samples[c-1].duration=T.sample_deltas[F],o.samples_duration+=o.samples[c-1].duration,W.dts=o.samples[c-1].dts+o.samples[c-1].duration):W.dts=0,b?(c>=O&&(te++,O<0&&(O=0),O+=b.sample_counts[te]),W.cts=o.samples[c].dts+b.sample_offsets[te]):W.cts=W.dts,A?(c==A.sample_numbers[ee]-1?(W.is_sync=!0,ee++):(W.is_sync=!1,W.degradation_priority=0),L&&L.entries[se].sample_delta+he==c+1&&(W.subsamples=L.entries[se].subsamples,he+=L.entries[se].sample_delta,se++)):W.is_sync=!0,x.process_sdtp(o.mdia.minf.stbl.sdtp,W,W.number),k?W.degradation_priority=k.priority[c]:W.degradation_priority=0,L&&L.entries[se].sample_delta+he==c&&(W.subsamples=L.entries[se].subsamples,he+=L.entries[se].sample_delta),(w.length>0||C.length>0)&&x.setSampleGroupProperties(o,W,c,o.sample_groups_info)}c>0&&(o.samples[c-1].duration=Math.max(o.mdia.mdhd.duration-o.samples[c-1].dts,0),o.samples_duration+=o.samples[c-1].duration)}},x.prototype.updateSampleLists=function(){var o,c,f,m,S,T,b,A,I,L,w,C,k,U,G;if(this.moov!==void 0){for(;this.lastMoofIndex<this.moofs.length;)if(I=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,I.type=="moof")for(L=I,o=0;o<L.trafs.length;o++){for(w=L.trafs[o],C=this.getTrackById(w.tfhd.track_id),k=this.getTrexById(w.tfhd.track_id),w.tfhd.flags&l.TFHD_FLAG_SAMPLE_DESC?m=w.tfhd.default_sample_description_index:m=k?k.default_sample_description_index:1,w.tfhd.flags&l.TFHD_FLAG_SAMPLE_DUR?S=w.tfhd.default_sample_duration:S=k?k.default_sample_duration:0,w.tfhd.flags&l.TFHD_FLAG_SAMPLE_SIZE?T=w.tfhd.default_sample_size:T=k?k.default_sample_size:0,w.tfhd.flags&l.TFHD_FLAG_SAMPLE_FLAGS?b=w.tfhd.default_sample_flags:b=k?k.default_sample_flags:0,w.sample_number=0,w.sbgps.length>0&&x.initSampleGroups(C,w,w.sbgps,C.mdia.minf.stbl.sgpds,w.sgpds),c=0;c<w.truns.length;c++){var $=w.truns[c];for(f=0;f<$.sample_count;f++){U={},U.moof_number=this.lastMoofIndex,U.number_in_traf=w.sample_number,w.sample_number++,U.number=C.samples.length,w.first_sample_index=C.samples.length,C.samples.push(U),U.track_id=C.tkhd.track_id,U.timescale=C.mdia.mdhd.timescale,U.description_index=m-1,U.description=C.mdia.minf.stbl.stsd.entries[U.description_index],U.size=T,$.flags&l.TRUN_FLAGS_SIZE&&(U.size=$.sample_size[f]),C.samples_size+=U.size,U.duration=S,$.flags&l.TRUN_FLAGS_DURATION&&(U.duration=$.sample_duration[f]),C.samples_duration+=U.duration,C.first_traf_merged||f>0?U.dts=C.samples[C.samples.length-2].dts+C.samples[C.samples.length-2].duration:(w.tfdt?U.dts=w.tfdt.baseMediaDecodeTime:U.dts=0,C.first_traf_merged=!0),U.cts=U.dts,$.flags&l.TRUN_FLAGS_CTS_OFFSET&&(U.cts=U.dts+$.sample_composition_time_offset[f]),G=b,$.flags&l.TRUN_FLAGS_FLAGS?G=$.sample_flags[f]:f===0&&$.flags&l.TRUN_FLAGS_FIRST_FLAG&&(G=$.first_sample_flags),U.is_sync=!(G>>16&1),U.is_leading=G>>26&3,U.depends_on=G>>24&3,U.is_depended_on=G>>22&3,U.has_redundancy=G>>20&3,U.degradation_priority=G&65535;var z=!!(w.tfhd.flags&l.TFHD_FLAG_BASE_DATA_OFFSET),j=!!(w.tfhd.flags&l.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),Y=!!($.flags&l.TRUN_FLAGS_DATA_OFFSET),F=0;z?F=w.tfhd.base_data_offset:j||c===0?F=L.start:F=A,c===0&&f===0?Y?U.offset=F+$.data_offset:U.offset=F:U.offset=A,A=U.offset+U.size,(w.sbgps.length>0||w.sgpds.length>0||C.mdia.minf.stbl.sbgps.length>0||C.mdia.minf.stbl.sgpds.length>0)&&x.setSampleGroupProperties(C,U,U.number_in_traf,w.sample_groups_info)}}if(w.subs){C.has_fragment_subsamples=!0;var O=w.first_sample_index;for(c=0;c<w.subs.entries.length;c++)O+=w.subs.entries[c].sample_delta,U=C.samples[O-1],U.subsamples=w.subs.entries[c].subsamples}}}},x.prototype.getSample=function(o,c){var f,m=o.samples[c];if(!this.moov)return null;if(!m.data)m.data=new Uint8Array(m.size),m.alreadyRead=0,this.samplesDataSize+=m.size,e.debug("ISOFile","Allocating sample #"+c+" on track #"+o.tkhd.track_id+" of size "+m.size+" (total: "+this.samplesDataSize+")");else if(m.alreadyRead==m.size)return m;for(;;){var S=this.stream.findPosition(!0,m.offset+m.alreadyRead,!1);if(S>-1){f=this.stream.buffers[S];var T=f.byteLength-(m.offset+m.alreadyRead-f.fileStart);if(m.size-m.alreadyRead<=T)return e.debug("ISOFile","Getting sample #"+c+" data (alreadyRead: "+m.alreadyRead+" offset: "+(m.offset+m.alreadyRead-f.fileStart)+" read size: "+(m.size-m.alreadyRead)+" full size: "+m.size+")"),s.memcpy(m.data.buffer,m.alreadyRead,f,m.offset+m.alreadyRead-f.fileStart,m.size-m.alreadyRead),f.usedBytes+=m.size-m.alreadyRead,this.stream.logBufferLevel(),m.alreadyRead=m.size,m;if(T===0)return null;e.debug("ISOFile","Getting sample #"+c+" partial data (alreadyRead: "+m.alreadyRead+" offset: "+(m.offset+m.alreadyRead-f.fileStart)+" read size: "+T+" full size: "+m.size+")"),s.memcpy(m.data.buffer,m.alreadyRead,f,m.offset+m.alreadyRead-f.fileStart,T),m.alreadyRead+=T,f.usedBytes+=T,this.stream.logBufferLevel()}else return null}},x.prototype.releaseSample=function(o,c){var f=o.samples[c];return f.data?(this.samplesDataSize-=f.size,f.data=null,f.alreadyRead=0,f.size):0},x.prototype.getAllocatedSampleDataSize=function(){return this.samplesDataSize},x.prototype.getCodecs=function(){var o,c="";for(o=0;o<this.moov.traks.length;o++){var f=this.moov.traks[o];o>0&&(c+=","),c+=f.mdia.minf.stbl.stsd.entries[0].getCodec()}return c},x.prototype.getTrexById=function(o){var c;if(!this.moov||!this.moov.mvex)return null;for(c=0;c<this.moov.mvex.trexs.length;c++){var f=this.moov.mvex.trexs[c];if(f.track_id==o)return f}return null},x.prototype.getTrackById=function(o){if(this.moov===void 0)return null;for(var c=0;c<this.moov.traks.length;c++){var f=this.moov.traks[c];if(f.tkhd.track_id==o)return f}return null},x.prototype.itemsDataSize=0,x.prototype.flattenItemInfo=function(){var o=this.items,c=this.entity_groups,f,m,S,T=this.meta;if(T!=null&&T.hdlr!==void 0&&T.iinf!==void 0){for(f=0;f<T.iinf.item_infos.length;f++)S={},S.id=T.iinf.item_infos[f].item_ID,o[S.id]=S,S.ref_to=[],S.name=T.iinf.item_infos[f].item_name,T.iinf.item_infos[f].protection_index>0&&(S.protection=T.ipro.protections[T.iinf.item_infos[f].protection_index-1]),T.iinf.item_infos[f].item_type?S.type=T.iinf.item_infos[f].item_type:S.type="mime",S.content_type=T.iinf.item_infos[f].content_type,S.content_encoding=T.iinf.item_infos[f].content_encoding,S.item_uri_type=T.iinf.item_infos[f].item_uri_type;if(T.grpl)for(f=0;f<T.grpl.boxes.length;f++)entity_group={},entity_group.id=T.grpl.boxes[f].group_id,entity_group.entity_ids=T.grpl.boxes[f].entity_ids,entity_group.type=T.grpl.boxes[f].type,c[entity_group.id]=entity_group;if(T.iloc)for(f=0;f<T.iloc.items.length;f++){var b=T.iloc.items[f];switch(S=o[b.item_ID],b.data_reference_index!==0&&(e.warn("Item storage with reference to other files: not supported"),S.source=T.dinf.boxes[b.data_reference_index-1]),b.construction_method){case 0:break;case 1:break;case 2:e.warn("Item storage with construction_method : not supported");break}for(S.extents=[],S.size=0,m=0;m<b.extents.length;m++)S.extents[m]={},S.extents[m].offset=b.extents[m].extent_offset+b.base_offset,b.construction_method==1&&(S.extents[m].offset+=T.idat.start+T.idat.hdr_size),S.extents[m].length=b.extents[m].extent_length,S.extents[m].alreadyRead=0,S.size+=S.extents[m].length}if(T.pitm&&(o[T.pitm.item_id].primary=!0),T.iref)for(f=0;f<T.iref.references.length;f++){var A=T.iref.references[f];for(m=0;m<A.references.length;m++)o[A.from_item_ID].ref_to.push({type:A.type,id:A.references[m]})}if(T.iprp)for(var I=0;I<T.iprp.ipmas.length;I++){var L=T.iprp.ipmas[I];for(f=0;f<L.associations.length;f++){var w=L.associations[f];if(S=o[w.id],S||(S=c[w.id]),S)for(S.properties===void 0&&(S.properties={},S.properties.boxes=[]),m=0;m<w.props.length;m++){var C=w.props[m];if(C.property_index>0&&C.property_index-1<T.iprp.ipco.boxes.length){var k=T.iprp.ipco.boxes[C.property_index-1];S.properties[k.type]=k,S.properties.boxes.push(k)}}}}}},x.prototype.getItem=function(o){var c,f;if(!this.meta)return null;if(f=this.items[o],!f.data&&f.size)f.data=new Uint8Array(f.size),f.alreadyRead=0,this.itemsDataSize+=f.size,e.debug("ISOFile","Allocating item #"+o+" of size "+f.size+" (total: "+this.itemsDataSize+")");else if(f.alreadyRead===f.size)return f;for(var m=0;m<f.extents.length;m++){var S=f.extents[m];if(S.alreadyRead!==S.length){var T=this.stream.findPosition(!0,S.offset+S.alreadyRead,!1);if(T>-1){c=this.stream.buffers[T];var b=c.byteLength-(S.offset+S.alreadyRead-c.fileStart);if(S.length-S.alreadyRead<=b)e.debug("ISOFile","Getting item #"+o+" extent #"+m+" data (alreadyRead: "+S.alreadyRead+" offset: "+(S.offset+S.alreadyRead-c.fileStart)+" read size: "+(S.length-S.alreadyRead)+" full extent size: "+S.length+" full item size: "+f.size+")"),s.memcpy(f.data.buffer,f.alreadyRead,c,S.offset+S.alreadyRead-c.fileStart,S.length-S.alreadyRead),c.usedBytes+=S.length-S.alreadyRead,this.stream.logBufferLevel(),f.alreadyRead+=S.length-S.alreadyRead,S.alreadyRead=S.length;else return e.debug("ISOFile","Getting item #"+o+" extent #"+m+" partial data (alreadyRead: "+S.alreadyRead+" offset: "+(S.offset+S.alreadyRead-c.fileStart)+" read size: "+b+" full extent size: "+S.length+" full item size: "+f.size+")"),s.memcpy(f.data.buffer,f.alreadyRead,c,S.offset+S.alreadyRead-c.fileStart,b),S.alreadyRead+=b,f.alreadyRead+=b,c.usedBytes+=b,this.stream.logBufferLevel(),null}else return null}}return f.alreadyRead===f.size?f:null},x.prototype.releaseItem=function(o){var c=this.items[o];if(c.data){this.itemsDataSize-=c.size,c.data=null,c.alreadyRead=0;for(var f=0;f<c.extents.length;f++){var m=c.extents[f];m.alreadyRead=0}return c.size}else return 0},x.prototype.processItems=function(o){for(var c in this.items){var f=this.items[c];this.getItem(f.id),o&&!f.sent&&(o(f),f.sent=!0,f.data=null)}},x.prototype.hasItem=function(o){for(var c in this.items){var f=this.items[c];if(f.name===o)return f.id}return-1},x.prototype.getMetaHandler=function(){return this.meta?this.meta.hdlr.handler:null},x.prototype.getPrimaryItem=function(){return!this.meta||!this.meta.pitm?null:this.getItem(this.meta.pitm.item_id)},x.prototype.itemToFragmentedTrackFile=function(o){var c=o||{},f=null;if(c.itemId?f=this.getItem(c.itemId):f=this.getPrimaryItem(),f==null)return null;var m=new x;m.discardMdatData=!1;var S={type:f.type,description_boxes:f.properties.boxes};f.properties.ispe&&(S.width=f.properties.ispe.image_width,S.height=f.properties.ispe.image_height);var T=m.addTrack(S);return T?(m.addSample(T,f.data),m):null},x.prototype.write=function(o){for(var c=0;c<this.boxes.length;c++)this.boxes[c].write(o)},x.prototype.createFragment=function(o,c,f){var m=this.getTrackById(o),S=this.getSample(m,c);if(S==null)return this.setNextSeekPositionFromSample(m.samples[c]),null;var T=f||new s;T.endianness=s.BIG_ENDIAN;var b=this.createSingleSampleMoof(S);b.write(T),b.trafs[0].truns[0].data_offset=b.size+8,e.debug("MP4Box","Adjusting data_offset with new value "+b.trafs[0].truns[0].data_offset),T.adjustUint32(b.trafs[0].truns[0].data_offset_position,b.trafs[0].truns[0].data_offset);var A=new l.mdatBox;return A.data=S.data,A.write(T),T},x.writeInitializationSegment=function(o,c,f,m){var S;e.debug("ISOFile","Generating initialization segment");var T=new s;T.endianness=s.BIG_ENDIAN,o.write(T);var b=c.add("mvex");for(f&&b.add("mehd").set("fragment_duration",f),S=0;S<c.traks.length;S++)b.add("trex").set("track_id",c.traks[S].tkhd.track_id).set("default_sample_description_index",1).set("default_sample_duration",m).set("default_sample_size",0).set("default_sample_flags",65536);return c.write(T),T.buffer},x.prototype.save=function(o){var c=new s;c.endianness=s.BIG_ENDIAN,this.write(c),c.save(o)},x.prototype.getBuffer=function(){var o=new s;return o.endianness=s.BIG_ENDIAN,this.write(o),o.buffer},x.prototype.initializeSegmentation=function(){var o,c,f,m;for(this.onSegment===null&&e.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.nextMoofNumber=0,this.resetTables()),c=[],o=0;o<this.fragmentedTracks.length;o++){var S=new l.moovBox;S.mvhd=this.moov.mvhd,S.boxes.push(S.mvhd),f=this.getTrackById(this.fragmentedTracks[o].id),S.boxes.push(f),S.traks.push(f),m={},m.id=f.tkhd.track_id,m.user=this.fragmentedTracks[o].user,m.buffer=x.writeInitializationSegment(this.ftyp,S,this.moov.mvex&&this.moov.mvex.mehd?this.moov.mvex.mehd.fragment_duration:void 0,this.moov.traks[o].samples.length>0?this.moov.traks[o].samples[0].duration:0),c.push(m)}return c},l.Box.prototype.printHeader=function(o){this.size+=8,this.size>n&&(this.size+=8),this.type==="uuid"&&(this.size+=16),o.log(o.indent+"size:"+this.size),o.log(o.indent+"type:"+this.type)},l.FullBox.prototype.printHeader=function(o){this.size+=4,l.Box.prototype.printHeader.call(this,o),o.log(o.indent+"version:"+this.version),o.log(o.indent+"flags:"+this.flags)},l.Box.prototype.print=function(o){this.printHeader(o)},l.ContainerBox.prototype.print=function(o){this.printHeader(o);for(var c=0;c<this.boxes.length;c++)if(this.boxes[c]){var f=o.indent;o.indent+=" ",this.boxes[c].print(o),o.indent=f}},x.prototype.print=function(o){o.indent="";for(var c=0;c<this.boxes.length;c++)this.boxes[c]&&this.boxes[c].print(o)},l.mvhdBox.prototype.print=function(o){l.FullBox.prototype.printHeader.call(this,o),o.log(o.indent+"creation_time: "+this.creation_time),o.log(o.indent+"modification_time: "+this.modification_time),o.log(o.indent+"timescale: "+this.timescale),o.log(o.indent+"duration: "+this.duration),o.log(o.indent+"rate: "+this.rate),o.log(o.indent+"volume: "+(this.volume>>8)),o.log(o.indent+"matrix: "+this.matrix.join(", ")),o.log(o.indent+"next_track_id: "+this.next_track_id)},l.tkhdBox.prototype.print=function(o){l.FullBox.prototype.printHeader.call(this,o),o.log(o.indent+"creation_time: "+this.creation_time),o.log(o.indent+"modification_time: "+this.modification_time),o.log(o.indent+"track_id: "+this.track_id),o.log(o.indent+"duration: "+this.duration),o.log(o.indent+"volume: "+(this.volume>>8)),o.log(o.indent+"matrix: "+this.matrix.join(", ")),o.log(o.indent+"layer: "+this.layer),o.log(o.indent+"alternate_group: "+this.alternate_group),o.log(o.indent+"width: "+this.width),o.log(o.indent+"height: "+this.height)};var E={};E.createFile=function(o,c){var f=o!==void 0?o:!0,m=new x(c);return m.discardMdatData=!f,m},r.createFile=E.createFile})(Xn);class Fh{constructor(e,t,s,n=0){this.segment=e,this.sourceFps=t,this.targetFps=s,this.sum=n,this.framesRequested=0}async getNextFrame(){var t;const e=this.sourceFps/this.targetFps;if(this.sum+=e,this.framesRequested+=1,this.sum<1&&this.lastFrame)return this.lastFrame;for(;this.sum>=2;){const s=await this.segment.getNextFrame();if(!s)return;s.close(),this.sum-=1}if(this.sum>=1||!this.lastFrame){this.sum-=1;const s=await this.segment.getNextFrame();return s?((t=this.lastFrame)==null||t.close(),this.lastFrame=s,s):void 0}throw new Error("Unreachable code")}getLastFrame(){return this.lastFrame}getSum(){return this.sum}getSegment(){return this.segment}getTime(e){return(this.framesRequested-e)/this.targetFps}}class lu{constructor(e,t,s=0){this.file=e,this.setStatus=t,this.offset=s}write(e){const t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e),t.fileStart=this.offset,this.offset+=t.byteLength,this.setStatus("fetch",(this.offset/1024**2).toFixed(1)+" MiB"),this.file.appendBuffer(t)}close(){this.setStatus("fetch","Done"),this.file.flush()}}const zv=30;class Uh{constructor(e,t,s,n,a=0){this.done=!1,this.currentFramePastSegmentEndTime=!1,this.abortController=new AbortController,this.responseFinished=!1,this.framesProcessed=0,this.framesDue=0,this.frameBuffer=[],this.encodedChunkQueue=[],this.readMore=async()=>{},this.uri=e,this.file=t,this.file.onSamples=this.onSamples.bind(this),this.edit=s[n],this.startTime=a;const h=Math.floor(this.startTime*this.edit.fps);this.framesProcessed+=h,this.decoder=new VideoDecoder({output:this.onFrame.bind(this),error(l){console.error(l)}})}async start(e){if(this.edit.mediaTime===-1){this.done=!0,this.responseFinished=!0,this.decoder.close();const d=this.edit.segmentDuration/this.file.getInfo().videoTracks[0].movie_timescale,p=Math.ceil(d*this.edit.fps),g=this.file.getInfo().videoTracks[0].track_height,y=this.file.getInfo().videoTracks[0].track_width,v=g*y*4,x=new ArrayBuffer(v),E=new Uint8Array(x);E.fill(0),this.frameBuffer=Array.from({length:p},()=>new VideoFrame(E,{timestamp:0,duration:1/this.edit.fps,codedHeight:g,codedWidth:y,format:"BGRA"}));return}this.decoder.configure(e);const t=this.file.getInfo().videoTracks[0],s=this.file.getTrackById(t.id),n=this.edit.mediaTime,a=this.startTime*t.timescale,l=(n+a)/t.timescale,u=this.file.seekTrack(l,!0,s);this.readMore=await this.startStreamingAtOffset(this.file,this.uri,u.offset)}async startStreamingAtOffset(e,t,s){return fetch(t,{headers:{Range:`bytes=${s}-`},signal:this.abortController.signal}).then(async n=>{if(!n.body)throw new Error("Response body is null");const a=n.body.getReader(),h=new lu(e,()=>{},s);return async()=>a.read().then(({done:l,value:u})=>{if(l){this.responseFinished=!0,this.abortController.abort(),h.close();return}h.write(u)})})}onSamples(e,t,s){for(const n of s){const a=new EncodedVideoChunk({type:n.is_sync?"key":"delta",timestamp:1e6*n.cts/n.timescale,duration:1e6*n.duration/n.timescale,data:n.data});this.framesDue++,this.encodedChunkQueue.push(a);const h=this.file.getInfo().videoTracks[0],l=this.file.getTrackById(h.id);this.file.releaseSample(l,n.number)}}async decodeChunks(){for(;this.encodedChunkQueue.length>0&&this.decoder.decodeQueueSize<zv;){const e=this.encodedChunkQueue.shift();e&&this.decoder.decode(e)}if(this.done){this.currentFramePastSegmentEndTime=!0;return}if(this.responseFinished&&this.encodedChunkQueue.length===0){await this.flushDecoderWithRetry(),this.currentFramePastSegmentEndTime=!0;return}}async flushDecoderWithRetry(e=3,t=2e3){for(let s=0;s<e;s++){if(this.decoder.decodeQueueSize===0)return;try{await Promise.race([this.decoder.flush(),new Promise((n,a)=>setTimeout(()=>a(new Error("Flush timeout")),t))])}catch(n){if(s===e)throw n}}}async onFrame(e){this.framesDue--;const t=this.edit.mediaTime/this.file.getInfo().videoTracks[0].timescale,s=this.startTime+t,n=e.timestamp/1e6;if(n<s){e.close();return}const a=this.edit.segmentDuration/this.file.getInfo().videoTracks[0].movie_timescale,h=t+a;if(n>h){e.close(),this.done=!0,await this.decoder.flush();return}this.frameBuffer.push(e)}async populateBuffer(){for(;this.frameBuffer.length===0&&!this.currentFramePastSegmentEndTime;)this.responseFinished||await this.readMore(),await this.decodeChunks(),await new Promise(e=>setTimeout(e,0));if(this.frameBuffer.length===0&&this.framesDue>0){let e=200;for(;this.frameBuffer.length===0;)if(await new Promise(t=>setTimeout(t,10)),e--,this.done||e===0)return}}async getNextFrame(){await this.populateBuffer();const e=this.frameBuffer.shift();return e&&this.framesProcessed++,e}async close(){this.abortController.abort(),this.frameBuffer.forEach(e=>e.close());try{this.decoder.state==="configured"&&(await this.decoder.flush(),this.decoder.close())}catch{}}getFramesProcessed(){return this.framesProcessed}getStartTime(){return this.startTime}}function Hv(r,e){const t=r.getTrackById(e.id);for(const s of t.mdia.minf.stbl.stsd.entries){const n=s.avcC||s.hvcC||s.vpcC||s.av1C;if(n){const a=new Xn.DataStream(void 0,0,Xn.DataStream.BIG_ENDIAN);return n.write(a),new Uint8Array(a.buffer,8)}}throw new Error("avcC, hvcC, vpcC, or av1C box not found")}function Vv(r){return{mediaTime:r.media_time,segmentDuration:r.segment_duration,mediaRateInteger:r.media_rate_integer,mediaRateFraction:r.media_rate_fraction}}async function Kv(r){return new Promise((e,t)=>{const s=Xn.createFile();let n=!1;const a=new AbortController;return s.onReady=h=>{var v;n=!0,a.abort();const l=h.videoTracks[0],u={codec:l.codec.startsWith("vp08")?"vp8":l.codec,codedHeight:l.video.height,codedWidth:l.video.width,description:Hv(s,l)},d={mediaTime:0,segmentDuration:l.duration,mediaRateInteger:1,mediaRateFraction:0},p=(v=l.edits)==null?void 0:v.map(x=>Vv(x)),y=(p!=null&&p.length?p:[d]).map(x=>{const E=l.duration/l.timescale,o=x.segmentDuration/l.movie_timescale,c=l.nb_samples*(o/E),f=x.mediaRateInteger+x.mediaRateFraction/65535,m=c/o*f;return{...x,fps:m}});s.setExtractionOptions(l.id),s.start(),e({file:s,edits:y,config:u})},fetch(r,{signal:a.signal}).then(async h=>{if(!h.body)throw new Error("Response body is null");const l=h.body.getReader(),u=new lu(s,()=>{});for(;!n;)await l.read().then(({done:d,value:p})=>{if(d){s.flush(),a.abort(),t("Could not find moov");return}u.write(p)})})})}class Yv{constructor(e,t,s){this.edits=[],this.nextSegment=0,this.uri=e,this.targetFps=t,this.startTime=s}async start(){const{file:e,edits:t,config:s}=await Kv(this.uri);this.file=e,this.edits=t,this.decoderConfig=s}async getNextFrame(){var t;if(!this.sampler){let s=this.startTime;for(;this.nextSegment<this.edits.length;){const a=this.getSecondDurationOfSegment(this.edits[this.nextSegment]);if(s<a)break;s-=a,this.nextSegment++}if(this.nextSegment>=this.edits.length)throw new Error(`Timestamp ${this.startTime} is outside of the video, max timestamp is ${this.getDuration()}`);const n=new Uh(this.uri,this.file,this.edits,this.nextSegment,s);await n.start(this.decoderConfig),this.sampler=new Fh(n,this.edits[this.nextSegment].fps,this.targetFps,0),this.nextSegment++}let e=await this.sampler.getNextFrame();for(;!e&&this.nextSegment<this.edits.length;){this.sampler.getSegment().close(),(t=this.sampler.getLastFrame())==null||t.close();const s=new Uh(this.uri,this.file,this.edits,this.nextSegment,0);await s.start(this.decoderConfig),this.sampler=new Fh(s,this.edits[this.nextSegment].fps,this.targetFps,this.sampler.getSum()),this.nextSegment++,e=await this.sampler.getNextFrame()}if(!e&&(e=this.sampler.getLastFrame(),await this.sampler.getSegment().close(),!e))throw new Error("There are no frames in the video.");return e}getSecondDurationOfSegment(e){const t=e.mediaRateInteger+e.mediaRateFraction/65535;return e.segmentDuration/this.file.getInfo().videoTracks[0].movie_timescale/t}getDuration(){return this.edits.reduce((e,t)=>e+this.getSecondDurationOfSegment(t),0)}getTimeSubtractingFrames(e){const t=this.edits.slice(0,this.nextSegment-1).reduce((a,h)=>a+this.getSecondDurationOfSegment(h),0);if(!this.sampler)throw new Error("No current segment");const s=this.sampler.getSegment().getStartTime(),n=this.sampler.getTime(e);return t+s+n}getTime(){return this.getTimeSubtractingFrames(0)}getLastTime(){return this.getTimeSubtractingFrames(1)}getLastFrame(){var e;return(e=this.sampler)==null?void 0:e.getLastFrame()}close(){var e,t,s;(e=this.sampler)==null||e.getSegment().close(),(s=(t=this.sampler)==null?void 0:t.getLastFrame())==null||s.close(),this.file.flush()}}const ji=new Map;async function Wv(r,e){const t=e+"-"+r,s=ji.get(t);s&&(s.close(),ji.delete(t))}async function jv(r,e,t,s){const n=e+"-"+r;let a=ji.get(n);const h=1/s,l=a==null?void 0:a.getDuration();l&&t>l&&(t=l);const u=a&&Math.abs(t-a.getLastTime())<h/2;if(a&&u){const d=a.getLastFrame();if(!d)throw new Error("No last frame");return d}return a&&t+h<a.getTime()&&(a.close(),ji.delete(n),a=void 0),a&&t>a.getTime()+h*1.5&&(a.close(),ji.delete(n),a=void 0),a||(a=new Yv(e,s,t),await a.start(),ji.set(n,a)),a.getNextFrame()}function*qv(r,e=1e4){const t=Date.now();for(;!r();){if(Date.now()-t>e)throw new Error("Timeout waiting for condition");yield}}var Oi=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},Vi;let dt=Vi=class extends Ye{constructor(e){super(e),this.detectedFileType="unknown",this.fileTypeWasDetected=!1,this.lastFrame=null}desiredSize(){const e=super.desiredSize();if(e.x===null&&e.y===null){const t=this.video();return{x:t.videoWidth,y:t.videoHeight}}return e}mediaElement(){return this.video()}seekedMedia(){return this.seekedVideo()}fastSeekedMedia(){return this.fastSeekedVideo()}video(){const e=this.src(),t=`${this.key}/${e}`;let s=Vi.pool[t];if(!s){if(s=document.createElement("video"),s.crossOrigin="anonymous",s.preload="metadata",s.playsInline=!0,s.setAttribute("webkit-playsinline","true"),s.setAttribute("playsinline","true"),s.volume=this.getVolume(),new URL(e,window.location.origin).pathname.endsWith(".m3u8")){const h=new oi;h.loadSource(e),h.attachMedia(s)}else s.src=e;s.addEventListener("loadedmetadata",()=>{(s.duration===1/0||s.duration===0)&&(s.currentTime=24*60*60)}),s.addEventListener("seeked",()=>{(s.duration===1/0||s.duration===0)&&(s.currentTime=0)}),s.addEventListener("durationchange",()=>{(s.duration===1/0||s.duration===0)&&(s.currentTime=.1)}),s.addEventListener("loadeddata",()=>{(s.duration===1/0||s.duration===0)&&(s.currentTime=.1)}),s.addEventListener("canplay",()=>{(s.duration===1/0||s.duration===0)&&(s.currentTime=.1)}),Vi.pool[t]=s}return s.volume=this.getVolume(),this.waitForCanPlayNecessary(s)&&be.collectPromise(new Promise(a=>{this.waitForCanPlay(s,a)})),s}seekedVideo(){const e=this.video(),t=this.clampTime(this.time());return e.playbackRate=this.playbackRate(),e.paused||e.pause(),this.lastTime===t||this.setCurrentTime(t),e}fastSeekedVideo(){const e=this.video(),t=this.clampTime(this.time());if(e.playbackRate=this.playbackRate(),this.lastTime===t)return e;const s=this.playing()&&t<e.duration&&e.playbackRate>0;return s?e.paused&&be.collectPromise(e.play()):e.paused||e.pause(),Math.abs(e.currentTime-t)>1?this.setCurrentTime(t):s||(e.currentTime=t),e}async webcodecSeekedVideo(){const e=this.video(),t=this.clampTime(this.time());if(e.playbackRate=this.playbackRate(),this.lastFrame&&this.lastTime===t)return this.lastFrame;const s=this.view().fps()/this.playbackRate();return jv(this.key,e.src,t,s)}async ffmpegSeekedVideo(){const e=this.video(),t=this.clampTime(this.time()),s=this.getDuration();if(e.playbackRate=this.playbackRate(),this.lastFrame&&this.lastTime===t)return this.lastFrame;const n=this.view().fps()/this.playbackRate();if(!Vi.imageCommunication)throw new Error("ServerSeekedVideo can only be used with HMR.");const a=await Vi.imageCommunication.getFrame(this.key,e.src,t,s,n);return this.lastFrame=a,this.lastTime=t,a}async seekFunction(){const e=this.view().playbackState();return e===xt.Playing||e===xt.Presenting?this.fastSeekedVideo():e===xt.Paused?this.seekedVideo():this.decoder()==="slow"?this.seekedVideo():this.decoder()==="ffmpeg"?this.ffmpegSeekedVideo():this.decoder()==="web"?this.webcodecSeekedVideo():(this.fileTypeWasDetected||this.detectFileType(),this.detectedFileType==="webm"?this.ffmpegSeekedVideo():this.detectedFileType==="hls"?this.seekedVideo():this.webcodecSeekedVideo())}async draw(e){this.drawShape(e);const t=this.alpha();if(t>0){const s=await this.seekFunction(),n=fe.fromSizeCentered(this.computedSize());e.save(),e.clip(this.getPath()),t<1&&(e.globalAlpha*=t),e.imageSmoothingEnabled=this.smoothing(),Fc(e,s,n),e.restore()}this.clip()&&e.clip(this.getPath()),await this.drawChildren(e)}applyFlex(){super.applyFlex();const e=this.video();this.element.style.aspectRatio=(this.ratio()??e.videoWidth/e.videoHeight).toString()}remove(){return super.remove(),Wv(this.key,this.video().src),this}handleUnknownFileType(e){console.warn(`WARNING: Could not detect file type of video (${e}), will default to using mp4 decoder. If your video file is not an mp4 file, this will lead to an error - to fix this, reencode your video as an mp4 file (better performance) or specify a different decoder: https://docs.re.video/common-issues/slow-rendering#use-mp4-decoder`),this.detectedFileType="unknown",this.fileTypeWasDetected=!0}detectFileType(){return be.collectPromise((async()=>{var a;const e=this.src(),t=(a=e.split("?")[0].split(".").pop())==null?void 0:a.toLowerCase();if(t==="mp4"||t==="webm"||t==="mov"){this.detectedFileType=t,this.fileTypeWasDetected=!0;return}if(t==="m3u8"){this.detectedFileType="hls",this.fileTypeWasDetected=!0;return}if(!e.startsWith("http://")&&!e.startsWith("https://")){this.handleUnknownFileType(e);return}const n=(await fetch(e,{method:"HEAD"})).headers.get("Content-Type");if(!n){this.handleUnknownFileType(e);return}if(n.includes("video/mp4")){this.detectedFileType="mp4",this.fileTypeWasDetected=!0;return}if(n.includes("video/webm")){this.detectedFileType="webm",this.fileTypeWasDetected=!0;return}if(n.includes("video/quicktime")){this.detectedFileType="mov",this.fileTypeWasDetected=!0;return}if(n.includes("application/vnd.apple.mpegurl")||n.includes("application/x-mpegURL")){this.detectedFileType="hls",this.fileTypeWasDetected=!0;return}this.handleUnknownFileType(e)})())}*waitForMetadata(){const e=this.video();e.duration>0&&e.duration!==1/0||(e.currentTime=.1,yield*qv(()=>e.duration>0&&e.duration!==1/0))}};dt.pool={};dt.imageCommunication=null;Oi([V(1),N()],dt.prototype,"alpha",void 0);Oi([V(!0),N()],dt.prototype,"smoothing",void 0);Oi([V(null),N()],dt.prototype,"decoder",void 0);Oi([J()],dt.prototype,"video",null);Oi([J()],dt.prototype,"seekedVideo",null);Oi([J()],dt.prototype,"fastSeekedVideo",null);dt=Vi=Oi([nt("Video")],dt);class Xv extends Lg{constructor(e){super(e),this.view=null,this.registeredNodes=new Map,this.nodeCounters=new Map,this.assetHash=Date.now().toString(),this.recreateView()}getView(){return this.view}next(){var e;return(e=this.getView())==null||e.playbackState(this.playback.state).globalTime(this.playback.time),super.next()}async draw(e){e.save(),this.renderLifecycle.dispatch([It.BeforeRender,e]),e.save(),this.renderLifecycle.dispatch([It.BeginRender,e]),this.getView().playbackState(this.playback.state).globalTime(this.playback.time).fps(this.playback.fps),await this.getView().render(e),this.renderLifecycle.dispatch([It.FinishRender,e]),e.restore(),this.renderLifecycle.dispatch([It.AfterRender,e]),e.restore()}reset(e){for(const t of this.registeredNodes.keys())try{this.registeredNodes.get(t).dispose()}catch(s){this.logger.error(s)}return this.registeredNodes.clear(),this.registeredNodes=new Map,this.nodeCounters.clear(),this.recreateView(),super.reset(e)}inspectPosition(e,t){const s=this.getNodeByPosition(e,t);return s==null?void 0:s.key}getNodeByPosition(e,t){return this.execute(()=>this.getView().hit(new R(e,t))??null)}validateInspection(e){var t;return((t=this.getNode(e))==null?void 0:t.key)??null}inspectAttributes(e){const t=this.getNode(e);if(!t)return null;const s={stack:t.creationStack,key:t.key};for(const{key:n,meta:a,signal:h}of t)a.inspectable&&(s[n]=h());return s}drawOverlay(e,t,s){const n=this.getNode(e);n&&this.execute(()=>{n.drawOverlay(s,t.multiply(n.localToWorld()))})}transformMousePosition(e,t){return Pt(new R(e,t),this.getView().localToParent().inverse())}registerNode(e,t){var h;const s=((h=e.constructor)==null?void 0:h.name)??"unknown",n=(this.nodeCounters.get(s)??0)+1;this.nodeCounters.set(s,n),t&&this.registeredNodes.has(t)&&(Me().error({message:`Duplicated node key: "${t}".`,inspect:t,stack:new Error().stack}),t=void 0),t??(t=`${this.name}/${s}[${n}]`),this.registeredNodes.set(t,e);const a=this.registeredNodes;return[t,()=>a.delete(t)]}getNode(e){return typeof e!="string"?null:this.registeredNodes.get(e)??null}*getDetachedNodes(){for(const e of this.registeredNodes.values())!e.parent()&&e!==this.view&&(yield e)}getMediaAssets(){const e=Array.from(this.registeredNodes.values()).filter(n=>n instanceof dt).filter(n=>n.isPlaying()),t=Array.from(this.registeredNodes.values()).filter(n=>n instanceof Wt).filter(n=>n.isPlaying()),s=[];return s.push(...e.map(n=>({key:n.key,type:"video",src:n.src(),decoder:n.decoder(),playbackRate:typeof n.playbackRate=="function"?n.playbackRate():n.playbackRate,volume:n.getVolume(),currentTime:n.getCurrentTime(),duration:n.getDuration()}))),s.push(...t.map(n=>({key:n.key,type:"audio",src:n.src(),playbackRate:typeof n.playbackRate=="function"?n.playbackRate():n.playbackRate,volume:n.getVolume(),currentTime:n.getCurrentTime(),duration:n.getDuration()}))),s}stopAllMedia(){const e=Array.from(this.registeredNodes.values()).filter(t=>t instanceof Ye).filter(t=>t.isPlaying());for(const t of e)t.dispose()}adjustVolume(e){const t=Array.from(this.registeredNodes.values()).filter(s=>s instanceof Ye);for(const s of t)s.setVolume(s.getVolume()*e)}recreateView(){this.execute(()=>{const e=this.getSize();this.view=new jt({position:e.scale(this.resolutionScale/2),scale:this.resolutionScale,assetHash:this.assetHash,size:e})})}}function Qv(r,e){return{klass:Xv,name:r,config:e,stack:new Error().stack,plugins:["@twick/2d/editor"]}}const hu="#000000",cu={x:0,y:0},ci="easeInOut",xs={VIDEO:"video",AUDIO:"audio",CAPTION:"caption",SCENE:"scene",ELEMENT:"element"},Oh={highlight_bg:{rect:{alignItems:"center",gap:2},word:{lineWidth:.35,stroke:"#000000",fontWeight:700,shadowOffset:[-3,3],shadowColor:"#000000",fill:"#ffffff",fontFamily:"Bangers",bgColor:"#444444",bgOffsetWidth:30,bgOffsetHeight:8,fontSize:50}},word_by_word:{rect:{alignItems:"center",justifyContent:"center",gap:8},word:{lineWidth:.35,stroke:"#000000",fontWeight:700,strokeFirst:!0,shadowOffset:[-2,2],shadowColor:"#000000",shadowBlur:5,fontFamily:"Bangers",fill:"#FFFFFF",bgOffsetWidth:20,bgOffsetHeight:10,fontSize:50}},word_by_word_with_bg:{rect:{alignItems:"center",gap:8,padding:[10,20],radius:10},word:{lineWidth:.35,stroke:"#000000",fontWeight:700,strokeFirst:!0,shadowOffset:[-2,2],shadowColor:"#000000",shadowBlur:5,fontFamily:"Bangers",fill:"#FFFFFF",bgOffsetWidth:20,bgOffsetHeight:10,fontSize:50}}},Zv={text:"#000000",bgColor:"#444444"},Jv={family:"Poppins",size:48,weight:400},eS="#FFFFFF00",Bh={VIDEO:"video",IMAGE:"image"},pa={CONTAIN:"contain",COVER:"cover",FILL:"fill"},We={SATURATED:"saturated",BRIGHT:"bright",VIBRANT:"vibrant",RETRO:"retro",BLACK_WHITE:"blackWhite",COOL:"cool",WARM:"warm",CINEMATIC:"cinematic",SOFT_GLOW:"softGlow",MOODY:"moody",DREAMY:"dreamy",INVERTED:"inverted",VINTAGE:"vintage",DRAMATIC:"dramatic",FADED:"faded"},Nh={PLAYER_UPDATE:"twick:playerUpdate"};function js(r,e){console.log(`[Visualizer] ${r}`,e||"")}const tS={name:"audio",*create({containerRef:r,element:e,view:t}){const s=Fe();yield*ae(e==null?void 0:e.s),yield r().add(Ce(Wt,{ref:s,play:!0,...e.props},e.id)),yield*ae(Math.max(0,e.e-e.s)),yield s().play(!1),yield s().remove()}};function iS({t:r,s:e,e:t}){const s=r.split(" "),n=t-e,a=s.join("").length;let h=e;return s.map(l=>{const u=l.length/a*n,d=h,p=d+u;return h=p,{t:l,s:parseFloat(d.toFixed(2)),e:parseFloat(p.toFixed(2))}})}const du=r=>{let e=r.replace(/^#/,"");if(e.length===3&&(e=e.split("").map(h=>h+h).join("")),e.length!==6)throw new Error("Invalid hex color");const t=parseInt(e,16),s=t>>16&255,n=t>>8&255,a=t&255;return{r:s,g:n,b:a}},sS={name:"caption",*create({containerRef:r,caption:e}){var a,h,l,u,d,p;const t=iS(e);let s=0;t!=null&&t.length&&(s=t[0].s);let n={refs:[],props:[],idx:0,prevTime:s};for(const g of t){n.props.push(e.props);const y=Fe(),v=e.props;if(r().add(Ce(kt,{ref:y,...v,text:g.t,opacity:0})),e.capStyle=="highlight_bg"){const x=Fe(),E=Fe(),o=new Le({...du(v.colors.bgColor),a:(v==null?void 0:v.bgOpacity)??1});r().add(Ce(Ke,{ref:x,fill:o,width:y().width()+(v.bgOffsetWidth??30),height:y().height()+(v.bgOffsetHeight??10),margin:v.bgMargin??[0,-5],radius:v.bgRadius??10,padding:v.bgPadding??[0,15],opacity:0,alignItems:"center",justifyContent:"center",layout:!0,children:Ce(kt,{ref:E,...v,text:g.t})})),y().remove(),n.refs.push({bgRef:x,textRef:E})}else n.refs.push({textRef:y});n.prevTime=g.e,n.idx=n.idx+1}n.prevTime=s,n.idx=0;for(const g of t)e.capStyle=="highlight_bg"?(yield*(h=(a=n.refs[n.idx])==null?void 0:a.bgRef)==null?void 0:h.call(a).opacity(1,0),yield*ae(Math.max(0,g.e-g.s)),yield*(u=(l=n.refs[n.idx])==null?void 0:l.bgRef)==null?void 0:u.call(l).fill(eS,0)):(yield*(p=(d=n.refs[n.idx])==null?void 0:d.textRef)==null?void 0:p.call(d).opacity(1,0),yield*ae(Math.max(0,g.e-g.s))),n.prevTime=g.e,n.idx=n.idx+1}},nS={name:"elastic",*run({elementRef:r,duration:e,delay:t}){t&&(yield*ae(t)),r().scale(0),yield*r().scale(1,e,jh)}},rS={name:"erase",*run({elementRef:r,duration:e,delay:t,bufferTime:s=.1}){const n=r().text(),a=r().size();r().setText(""),r().size(a),r().textAlign("left"),t&&(yield*ae(t));let h=(e-s)/n.length;yield*ae(h);for(let l=n.length;l>=0;l--)yield*ae(h),r().setText(n.substring(0,l))}},aS={name:"stream-word",*run({elementRef:r,duration:e,delay:t,bufferTime:s=.1}){const n=r().text(),a=r().size(),h=n.split(" ");r().setText(""),r().size(a),t&&(yield*ae(t)),r().textAlign("left");let l=(e-s)/h.length;for(let u=0;u<h.length;u++)yield*ae(l),r().setText(h.slice(0,u+1).join(" "))}},oS={name:"typewriter",*run({elementRef:r,duration:e,delay:t,bufferTime:s=.1}){const n=r().text(),a=r().size();r().setText(""),r().size(a),r().textAlign("left"),t&&(yield*ae(t));let h=(e-s)/n.length;yield*ae(h);for(let l=0;l<n.length;l++)yield*ae(h),r().setText(n.substring(0,l+1))}};class lS{constructor(){this.effects=new Map}register(e){this.effects.set(e.name,e)}get(e){return this.effects.get(e)}list(){return Array.from(this.effects.keys())}}const hS=()=>{Ss.register(oS),Ss.register(aS),Ss.register(rS),Ss.register(nS)},Ss=new lS;hS();const cS={name:"blur",*run({elementRef:r,containerRef:e,interval:t,duration:s,intensity:n=25,animate:a}){const h=e??r;let l=Math.min(t,s);a==="enter"?(h().filters.blur(n),yield*h().filters.blur(0,l)):a==="exit"?(yield*ae(s-l),yield*h().filters.blur(n,l)):a==="both"&&(l=Math.min(t,s/2),h().filters.blur(n),yield*h().filters.blur(0,l),yield*ae(s-l),yield*h().filters.blur(n,l))}};function Ct(r){switch(r){case"easeInSine":return ku;case"easeOutSine":return Mu;case"easeInOutSine":return Fu;case"easeInQuad":return Uu;case"easeOutQuad":return Ou;case"easeInOutQuad":return Bu;case"easeInCubic":return Nu;case"easeOutCubic":return $u;case"easeInOutCubic":return Ls;case"easeInQuart":return Gu;case"easeOutQuart":return zu;case"easeInOutQuart":return Hu;case"easeInQuint":return Vu;case"easeOutQuint":return Ku;case"easeInOutQuint":return Yu;case"easeInExpo":return Wu;case"easeOutExpo":return Yh;case"easeInOutExpo":return ju;case"easeInCirc":return qu;case"easeOutCirc":return Xu;case"easeInOutCirc":return Qu;case"easeInBack":return of;case"easeOutBack":return lf;case"easeInOutBack":return hf;case"easeInElastic":return ff;case"easeOutElastic":return jh;case"easeInOutElastic":return pf;case"easeInBounce":return cf;case"easeOutBounce":return df;case"easeInOutBounce":return uf;default:return Wh}}const dS={name:"breathe",*run({elementRef:r,containerRef:e,mode:t,duration:s,intensity:n=.5}){const a=e??r,h=a().scale();t==="in"&&(yield*a().scale(new R(h.x*n,h.y*n),s,Ct("easeInSine"))),t==="out"&&(a().scale(new R(h.x*n,h.y*n)),yield*a().scale(new R(h.x,h.y),s,Ct("easeOutSine")))}},uS={name:"fade",*run({elementRef:r,containerRef:e,interval:t,duration:s,animate:n}){const a=e??r;let h=Math.min(t,s);n==="enter"?(a().opacity(0),yield*a().opacity(1,h)):n==="exit"?(yield*ae(s-h),yield*a().opacity(0,h)):n==="both"&&(h=Math.min(t,s/2),a().opacity(0),yield*a().opacity(1,h),yield*ae(s-h),yield*a().opacity(0,h))}},fS={name:"photo-rise",*run({elementRef:r,containerRef:e,direction:t,duration:s,intensity:n=200}){if(e){const a=r().position();t==="up"?(r().y(a.y+n),yield*r().y(a.y,s)):t==="down"?(r().y(a.y-n),yield*r().y(a.y,s)):t==="left"?(r().x(a.x+n),yield*r().x(a.x,s)):t==="right"&&(r().x(a.x-n),yield*r().x(a.x,s))}}},pS={name:"photo-zoom",*run({elementRef:r,containerRef:e,mode:t,duration:s,intensity:n=1.5}){if(e){const a=r().scale();t==="in"&&(yield r().scale(new R(a.x*n,a.y*n)),yield*r().scale(new R(a.x,a.y),s)),t==="out"&&(r().scale(new R(a.x,a.y)),yield*r().scale(new R(a.x*n,a.y*n),s))}}},gS={name:"rise",*run({elementRef:r,containerRef:e,interval:t=.25,duration:s,animate:n,direction:a,intensity:h=200}){const l=e??r,u=l().position();let d=Math.min(t,s);n==="enter"?(l().opacity(0),a==="up"?(l().y(u.y+h),yield*_e(l().opacity(1,d/4),l().y(u.y,d))):a==="down"&&(l().y(u.y-h),yield*_e(l().opacity(1,d/4),l().y(u.y,d)))):n==="exit"?(yield*ae(s-d),a==="up"?yield*_e(wi(3*d/4,l().opacity(0,d/4)),l().y(u.y-h,d)):a==="down"&&(yield*_e(wi(3*d/4,l().opacity(0,d/4)),l().y(u.y+h,d)))):n==="both"&&(d=Math.min(t,s/2),l().opacity(0),a==="up"?(l().y(u.y+h),yield*_e(l().opacity(1,d/4),l().y(u.y,d)),yield*ae(s-d),yield*_e(wi(3*d/4,l().opacity(0,d/4)),l().y(u.y-h,d))):a==="down"&&(l().y(u.y-h),yield*_e(l().opacity(1,d/4),l().y(u.y,d)),yield*ae(s-d),yield*_e(wi(3*d/4,l().opacity(0,d/4)),l().y(u.y+h,d))))}},mS={name:"succession",*run({elementRef:r,containerRef:e,interval:t,duration:s,animate:n}){const a=e??r,h=a().scale();let l=Math.min(t,s);n==="enter"?(a().opacity(0),a().scale(new R(h.x/2,h.y/2)),yield*_e(a().scale(h,l),a().opacity(1,l/2))):n==="exit"?(yield*ae(s-l),yield*_e(a().scale(new R(h.x/2,h.y/2),l),wi(l/2,a().opacity(0,l/2)))):n==="both"&&(l=Math.min(t,s/2),a().opacity(0),a().scale(new R(h.x/2,h.y/2)),yield*_e(a().scale(h,l),a().opacity(1,l/2)),yield*ae(s-l),yield*_e(a().scale(new R(h.x/2,h.y/2),l),wi(l/2,a().opacity(0,l/2))))}};class yS{constructor(){this.animations=new Map}register(e){this.animations.set(e.name,e)}get(e){return this.animations.get(e)}list(){return Array.from(this.animations.keys())}}const xS=()=>{si.register(uS),si.register(gS),si.register(dS),si.register(mS),si.register(cS),si.register(pS),si.register(fS)},si=new yS;xS();const vS={name:"circle",*run({containerRef:r,elementRef:e,initFrameState:t,frameEffect:s}){yield*ae(s.s);const n=s.props,a=[];a.push(r().size({x:n.frameSize[0],y:n.frameSize[1]},n.transitionDuration,Ct(n.transitionEasing??ci))),a.push(r().position(n.framePosition??{x:0,y:0},n.transitionDuration,Ct(n.transitionEasing??ci))),a.push(e().position(n.elementPosition??cu,n.transitionDuration,Ct(n.transitionEasing??ci))),a.push(r().radius(n.frameSize[0]/2,n.transitionDuration,Ct(n.transitionEasing??ci))),n.objectFit&&a.push(qs({elementRef:e,containerSize:{x:n.frameSize[0],y:n.frameSize[1]},elementSize:t.element.size,objectFit:n.objectFit})),yield*_e(...a)}},SS={name:"rect",*run({containerRef:r,elementRef:e,initFrameState:t,frameEffect:s}){yield*ae(s.s);const n=s.props,a=[];a.push(r().size(n.frameSize,n.transitionDuration,Ct(n.transitionEasing??ci))),a.push(r().position(n.framePosition??{x:0,y:0},n.transitionDuration,Ct(n.transitionEasing??ci))),a.push(e().position(n.elementPosition??cu,n.transitionDuration,Ct(n.transitionEasing??ci))),a.push(r().radius(n.radius??0,n.transitionDuration,Ct(n.transitionEasing??ci))),n.objectFit&&a.push(qs({elementRef:e,containerSize:{x:n.frameSize[0],y:n.frameSize[1]},elementSize:t.element.size,objectFit:n.objectFit})),yield*_e(...a)}};class _S{constructor(){this.frameEffects=new Map}register(e){this.frameEffects.set(e.name,e)}get(e){return this.frameEffects.get(e)}list(){return Array.from(this.frameEffects.keys())}}const ES=()=>{Wa.register(vS),Wa.register(SS)},Wa=new _S;ES();function*qs({containerSize:r,elementSize:e,elementRef:t,objectFit:s}){const n=r.x/r.y,a=e.x/e.y;switch(s){case pa.CONTAIN:a>n?(yield t().size({x:r.x,y:r.x/a}),yield t().scale(r.x/e.x,r.x*a/e.y)):(yield t().size({x:r.y*a,y:r.y}),yield t().scale(r.y*a/e.x,r.y/e.y));break;case pa.COVER:a>n?(yield t().size({x:r.y*a,y:r.y}),yield t().scale(r.y*a/e.x,r.y/e.y)):(yield t().size({x:r.x,y:r.x/a}),yield t().scale(r.x/e.x,r.x*a/e.y));break;case pa.FILL:yield t().size(r),yield t().scale(r.x/e.x,r.x/e.y);break}}function*TS({elementRef:r,element:e}){if(yield r(),e.textEffect){const t=Ss.get(e.textEffect.name);t&&(yield*t.run({elementRef:r,duration:e.e-e.s,...e.textEffect}))}}function*fs({elementRef:r,containerRef:e,element:t,view:s}){if(yield r(),t.animation){const n=si.get(t.animation.name);n&&(yield*n.run({elementRef:r,containerRef:e,view:s,duration:t.e-t.s,...t.animation}))}}function*uu({containerRef:r,elementRef:e,element:t}){var n;const s=bS({containerRef:r,elementRef:e});for(let a=0;a<((n=t==null?void 0:t.frameEffects)==null?void 0:n.length);a++){const h=t.frameEffects[a],l=a===t.frameEffects.length-1||t.frameEffects[a+1].s!==h.e,u=Wa.get(h.name);u&&(yield*u.run({containerRef:r,elementRef:e,initFrameState:s,frameEffect:h}),l&&(yield*AS({containerRef:r,elementRef:e,duration:h.e-h.s,element:t,initProps:s})))}}function bS({containerRef:r,elementRef:e}){return{frame:{size:r().size(),pos:r().position(),radius:r().radius(),scale:r().scale(),rotation:r().rotation()},element:{size:r().size(),pos:e().position(),scale:e().scale()}}}function*AS({containerRef:r,elementRef:e,duration:t,element:s,initProps:n}){yield*ae(t),js(`restoreFrameState: ${JSON.stringify(n)}`);let a=[];a.push(r().size(n.frame.size)),a.push(r().position(n.frame.pos)),a.push(r().scale(n.frame.scale)),a.push(r().rotation(n.frame.rotation)),a.push(r().radius(n.frame.radius)),a.push(e().size(n.element.size)),a.push(e().position(n.element.pos)),a.push(e().scale(n.element.scale)),a.push(qs({elementRef:e,containerSize:n.frame.size,elementSize:n.element.size,objectFit:s.objectFit??"none"})),yield*_e(...a)}const IS={name:"circle",*create({containerRef:r,element:e,view:t}){const s=Fe();yield*ae(e==null?void 0:e.s),yield r().add(Ce(Pi,{ref:s,...e.props},e.id)),yield*_e(fs({elementRef:s,element:e,view:t}),ae(Math.max(0,e.e-e.s))),yield s().remove()}},wS={name:"icon",*create({containerRef:r,element:e,view:t}){const s=Fe();yield*ae(e==null?void 0:e.s),yield r().add(Ce(gr,{ref:s,...e.props},e.id)),yield*_e(fs({elementRef:s,element:e,view:t}),ae(Math.max(0,e.e-e.s))),yield s().remove()}},fu=(r,e)=>{switch(e){case We.SATURATED:r().filters.saturate(1.4),r().filters.contrast(1.1);break;case We.BRIGHT:r().filters.brightness(1.3),r().filters.contrast(1.05);break;case We.VIBRANT:r().filters.saturate(1.6),r().filters.brightness(1.15),r().filters.contrast(1.1);break;case We.RETRO:r().filters.sepia(.8),r().filters.contrast(1.3),r().filters.brightness(.85),r().filters.saturate(.8);break;case We.BLACK_WHITE:r().filters.grayscale(1),r().filters.contrast(1.25),r().filters.brightness(1.05);break;case We.COOL:r().filters.hue(15),r().filters.brightness(1.1),r().filters.saturate(1.3),r().filters.contrast(1.05);break;case We.WARM:r().filters.hue(-15),r().filters.brightness(1.15),r().filters.saturate(1.3),r().filters.contrast(1.05);break;case We.CINEMATIC:r().filters.contrast(1.4),r().filters.brightness(.95),r().filters.saturate(.85),r().filters.sepia(.2);break;case We.SOFT_GLOW:r().filters.brightness(1.2),r().filters.contrast(.95),r().filters.blur(1.2),r().filters.saturate(1.1);break;case We.MOODY:r().filters.brightness(1.05),r().filters.contrast(1.4),r().filters.saturate(.65),r().filters.sepia(.2);break;case We.DREAMY:r().filters.brightness(1.3),r().filters.blur(2),r().filters.saturate(1.4),r().filters.contrast(.95);break;case We.INVERTED:r().filters.invert(1),r().filters.hue(180);break;case We.VINTAGE:r().filters.sepia(.4),r().filters.saturate(1.4),r().filters.contrast(1.2),r().filters.brightness(1.1);break;case We.DRAMATIC:r().filters.contrast(1.5),r().filters.brightness(.9),r().filters.saturate(1.2);break;case We.FADED:r().filters.opacity(.9),r().filters.brightness(1.2),r().filters.saturate(.8),r().filters.contrast(.9);break}},pu={name:"image",*create({containerRef:r,element:e,view:t}){var a;yield*ae(e==null?void 0:e.s);const s=Fe(),n=Fe();yield r().add(Ce(Ke,{ref:s,...e.frame,children:Ce(ht,{ref:n,...e.props},`child-${e.id}`)},e.id)),s()&&(yield qs({elementRef:n,containerSize:s().size(),elementSize:n().size(),objectFit:e.objectFit}),(a=e==null?void 0:e.props)!=null&&a.mediaFilter&&fu(n,e.props.mediaFilter),yield*_e(fs({elementRef:n,containerRef:s,element:e,view:t}),uu({containerRef:s,elementRef:n,element:e}),ae(Math.max(0,e.e-e.s))),yield n().remove(),yield s().remove())}},LS={name:"rect",*create({containerRef:r,element:e,view:t}){const s=Fe();yield*ae(e==null?void 0:e.s),js(`RectElement: ${JSON.stringify(e)}`),yield r().add(Ce(Ke,{ref:s,...e.props},e.id)),yield*_e(fs({elementRef:s,element:e,view:t}),ae(Math.max(0,e.e-e.s))),yield s().remove()}},gu={name:"video",*create({containerRef:r,element:e,view:t}){var a;yield*ae(e==null?void 0:e.s);const s=Fe(),n=Fe();yield r().add(Ce(Ke,{ref:s,...e.frame,children:Ce(dt,{ref:n,play:!0,...e.props},`child-${e.id}`)},e.id)),s()&&(yield qs({elementRef:n,containerSize:s().size(),elementSize:n().size(),objectFit:e.objectFit}),(a=e==null?void 0:e.props)!=null&&a.mediaFilter&&fu(n,e.props.mediaFilter),yield*_e(fs({elementRef:n,containerRef:s,element:e,view:t}),uu({containerRef:s,elementRef:n,element:e}),ae(Math.max(0,e.e-e.s))),yield n().play(!1),yield n().remove(),yield s().remove())}},RS={name:"scene",*create({containerRef:r,element:e,view:t}){yield*ae(e==null?void 0:e.s);const s=Fe();js(`SceneElement: ${JSON.stringify(e)}`),yield r().add(Ce(Ke,{ref:s,fill:e.backgroundColor??hu,size:"100%"})),e.type===Bh.IMAGE?yield*pu.create({containerRef:r,element:e,view:t}):e.type===Bh.VIDEO&&(yield*gu.create({containerRef:r,element:e,view:t})),yield s().remove()}},CS={name:"text",*create({containerRef:r,element:e,view:t}){const s=Fe();yield*ae(e==null?void 0:e.s),yield r().add(Ce(kt,{ref:s,text:e.t,...e.props},e.id)),yield*_e(fs({elementRef:s,element:e,view:t}),TS({elementRef:s,element:e}),ae(Math.max(0,e.e-e.s))),yield s().remove()}};class DS{constructor(){this.elements=new Map}register(e){this.elements.set(e.name,e)}get(e){return this.elements.get(e)}list(){return Array.from(this.elements.keys())}}const PS=()=>{tt.register(gu),tt.register(sS),tt.register(RS),tt.register(pu),tt.register(CS),tt.register(tS),tt.register(IS),tt.register(wS),tt.register(LS)},tt=new DS;PS();function*kS({view:r,track:e}){var n;const t=Fe();let s=0;r.add(Ce(q,{size:"100%",ref:t,layout:!0}));for(const a of e.elements||[])yield*ae((a==null?void 0:a.s)-s),yield*(n=tt.get("video"))==null?void 0:n.create({containerRef:t,element:a,view:r}),s=a.e;yield t().remove()}function*MS({view:r,track:e}){let t=0;for(const s of e.elements){const n=Fe();yield*ae((s==null?void 0:s.s)-t),t=s==null?void 0:s.e,js(`Adding audio element ${s.id}`),r.add(Ce(Wt,{ref:n,...s.props},s.id)),yield*ae(Math.max(0,s.e-s.s)),yield n().playing(!1),yield n().remove()}}function*FS({view:r,track:e}){var l;let t=0;const s=Fe();r.add(Ce(q,{size:"100%",ref:s}));const n=e==null?void 0:e.props,a=(n==null?void 0:n.applyToAll)??!1,h=(Oh[(n==null?void 0:n.capStyle)??""]||{}).word||{};for(const u of e.elements){const d=u.props,p=(Oh[(d==null?void 0:d.capStyle)??(n==null?void 0:n.capStyle)??""]||{}).rect||{},g={...p,justifyContent:p.justifyContent,alignItems:p.alignItems},y=a?n==null?void 0:n.colors:(d==null?void 0:d.colors)??(n==null?void 0:n.colors)??Zv,v={...h,...(n==null?void 0:n.captionProps)||{},colors:y,font:a?n==null?void 0:n.font:(d==null?void 0:d.font)??(n==null?void 0:n.font)??Jv,fill:y.text,bgColor:y.bgColor,bgOpacity:(n==null?void 0:n.bgOpacity)??1};yield*ae((u==null?void 0:u.s)-t);const x=Fe();if(s().add(Ce(Ke,{ref:x,...g,x:a?n==null?void 0:n.x:(d==null?void 0:d.x)??(n==null?void 0:n.x),y:a?n==null?void 0:n.y:(d==null?void 0:d.y)??(n==null?void 0:n.y),layout:!0},u.id)),(n==null?void 0:n.capStyle)==="word_by_word_with_bg"){const E=new Le({...du(v.bgColor),a:(v==null?void 0:v.bgOpacity)??1});x().fill(E)}yield*(l=tt.get("caption"))==null?void 0:l.create({containerRef:x,caption:{...u,t:u.t??"",capStyle:(d==null?void 0:d.capStyle)??(n==null?void 0:n.capStyle),props:v},view:r}),t=u.e,yield x().remove()}}function*US({view:r,track:e}){var s;const t=Fe();r.add(Ce(q,{size:"100%",ref:t,layout:!0}));for(const n of e.elements||[])yield*(s=tt.get("scene"))==null?void 0:s.create({containerRef:t,element:n,view:r});yield t().remove()}function*OS({view:r,track:e}){var n;const t=Fe();r.add(Ce(q,{size:"100%",ref:t}));const s=[];try{for(const a of e.elements)s.push((n=tt.get(a.type))==null?void 0:n.create({containerRef:t,element:a,view:r}))}catch(a){js("Error creating element track",a)}yield*_e(...s),yield t().remove()}const $h=(r,e)=>{if(typeof window<"u"){const t=new CustomEvent(r,e);return window.dispatchEvent(t)}},BS=Qv("scene",function*(r){const e=Dn().variables.get("input",null)(),t=Dn().variables.get("playerId",null)();if(e)if(console.log("Scene updated",{playerId:t,input:e}),yield r.add(Ce(Ke,{fill:e.backgroundColor??hu,size:"100%"})),e.tracks){const s=[];for(const n of e.tracks)switch(n.type){case xs.VIDEO:s.push(kS({view:r,track:n}));break;case xs.AUDIO:s.push(MS({view:r,track:n}));break;case xs.CAPTION:s.push(FS({view:r,track:n}));break;case xs.SCENE:s.push(US({view:r,track:n}));break;case xs.ELEMENT:s.push(OS({view:r,track:n}));break}yield*_e(...s),$h(Nh.PLAYER_UPDATE,{detail:{status:"ready",playerId:t,message:"All elements created"}})}else $h(Nh.PLAYER_UPDATE,{detail:{status:"ready",playerId:t,message:"No elements to create"}})}),s_=ug({scenes:[BS]});export{s_ as default};
|
|
142
|
+
`),d=[],p=e?Xy(e.baseTime,e.timescale):0;let g="00:00.000",y=0,x=0,v,_=!0;l.oncue=function(o){const c=t[s];let f=t.ccOffset;const m=(y-p)/9e4;if(c!=null&&c.new&&(x!==void 0?f=t.ccOffset=c.start:Hx(t,s,m)),m){if(!e){v=new Error("Missing initPTS for VTT MPEGTS");return}f=m-t.presentationOffset}const S=o.endTime-o.startTime,T=lt((o.startTime+f-x)*9e4,n*9e4)/9e4;o.startTime=Math.max(T,0),o.endTime=Math.max(T+S,0);const b=o.text.trim();o.text=decodeURIComponent(encodeURIComponent(b)),o.id||(o.id=Xo(o.startTime,o.endTime,b)),o.endTime>0&&d.push(o)},l.onparsingerror=function(o){v=o},l.onflush=function(){if(v){h(v);return}a(d)},u.forEach(o=>{if(_)if(va(o,"X-TIMESTAMP-MAP=")){_=!1,o.slice(16).split(",").forEach(c=>{va(c,"LOCAL:")?g=c.slice(6):va(c,"MPEGTS:")&&(y=parseInt(c.slice(7)))});try{x=zx(g)/1e3}catch(c){v=c}return}else o===""&&(_=!1);l.parse(o+`
|
|
143
|
+
`)}),l.flush()}const xa="stpp.ttml.im1t",Lu=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Ru=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Kx={left:"start",center:"center",right:"end",start:"start",end:"end"};function zh(r,e,t,s){const n=de(new Uint8Array(r),["mdat"]);if(n.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const a=n.map(l=>dt(l)),h=qy(e.baseTime,1,e.timescale);try{a.forEach(l=>t(Yx(l,h)))}catch(l){s(l)}}function Yx(r,e){const n=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const a={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},h=Object.keys(a).reduce((g,y)=>(g[y]=n.getAttribute(`ttp:${y}`)||a[y],g),{}),l=n.getAttribute("xml:space")!=="preserve",u=Hh(Sa(n,"styling","style")),d=Hh(Sa(n,"layout","region")),p=Sa(n,"body","[begin]");return[].map.call(p,g=>{const y=Cu(g,l);if(!y||!g.hasAttribute("begin"))return null;const x=Ea(g.getAttribute("begin"),h),v=Ea(g.getAttribute("dur"),h);let _=Ea(g.getAttribute("end"),h);if(x===null)throw Vh(g);if(_===null){if(v===null)throw Vh(g);_=x+v}const o=new qo(x-e,_-e,y);o.id=Xo(o.startTime,o.endTime,o.text);const c=d[g.getAttribute("region")],f=u[g.getAttribute("style")],m=Wx(c,f,u),{textAlign:S}=m;if(S){const T=Kx[S];T&&(o.lineAlign=T),o.align=S}return Ee(o,m),o}).filter(g=>g!==null)}function Sa(r,e,t){const s=r.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Hh(r){return r.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Cu(r,e){return[].slice.call(r.childNodes).reduce((t,s,n)=>{var a;return s.nodeName==="br"&&n?t+`
|
|
144
|
+
`:(a=s.childNodes)!=null&&a.length?Cu(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function Wx(r,e,t){const s="http://www.w3.org/ns/ttml#styling";let n=null;const a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],h=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return h&&t.hasOwnProperty(h)&&(n=t[h]),a.reduce((l,u)=>{const d=_a(e,s,u)||_a(r,s,u)||_a(n,s,u);return d&&(l[u]=d),l},{})}function _a(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function Vh(r){return new Error(`Could not parse ttml timestamp ${r}`)}function Ea(r,e){if(!r)return null;let t=Au(r);return t===null&&(Lu.test(r)?t=jx(r,e):Ru.test(r)&&(t=qx(r,e))),t}function jx(r,e){const t=Lu.exec(r),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function qx(r,e){const t=Ru.exec(r),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}class An{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class Xx{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Yh(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new An(this,"textTrack1"),t=new An(this,"textTrack2"),s=new An(this,"textTrack3"),n=new An(this,"textTrack4");this.cea608Parser1=new Gh(1,e,t),this.cea608Parser2=new Gh(3,s,n)}addCues(e,t,s,n,a){let h=!1;for(let l=a.length;l--;){const u=a[l],d=Qx(u[0],u[1],t,s);if(d>=0&&(u[0]=Math.min(u[0],t),u[1]=Math.max(u[1],s),h=!0,d/(s-t)>.5))return}if(h||a.push([t,s]),this.config.renderTextTracksNatively){const l=this.captionsTracks[e];this.Cues.newCue(l,t,s,n)}else{const l=this.Cues.newCue(null,t,s,n);this.hls.trigger(E.CUES_PARSED,{type:"captions",cues:l,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:n,timescale:a,trackId:h}){const{unparsedVttFrags:l}=this;s===X.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:a,trackId:h}),l.length&&(this.unparsedVttFrags=[],l.forEach(u=>{this.initPTS[u.frag.cc]?this.onFragLoaded(E.FRAG_LOADED,u):this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:u.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let n=0;n<s.textTracks.length;n++){const a=s.textTracks[n];if(Kh(a,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return a}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:n}=this,{label:a,languageCode:h}=t[e],l=this.getExistingTrack(a,h);if(l)s[e]=l,ss(s[e]),Su(s[e],n);else{const u=this.createTextTrack("captions",a,h);u&&(u[e]=!0,s[e]=u)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,n={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}createTextTrack(e,t,s){const n=this.media;if(n)return n.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:n}=this;Object.keys(n).forEach(a=>{ss(n[a]),delete n[a]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Yh(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let s=0;s<t.length;s++)ss(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],n=s.some(a=>a.textCodec===xa);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(ou(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const h=this.media,l=h?$n(h.textTracks):null;if(this.tracks.forEach((u,d)=>{let p;if(l){let g=null;for(let y=0;y<l.length;y++)if(l[y]&&Kh(l[y],u)){g=l[y],l[y]=null;break}g&&(p=g)}if(p)ss(p);else{const g=Pu(u);p=this.createTextTrack(g,u.name,u.lang),p&&(p.mode="disabled")}p&&this.textTracks.push(p)}),l!=null&&l.length){const u=l.filter(d=>d!==null).map(d=>d.label);u.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${u.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const h=this.tracks.map(l=>({label:l.name,kind:l.type.toLowerCase(),default:l.default,subtitleTrack:l}));this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:h})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const n=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!n)return;const a=`textTrack${n[1]}`,h=this.captionsProperties[a];h&&(h.label=s.name,s.lang&&(h.languageCode=s.lang),h.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===X.MAIN){var s,n;const{cea608Parser1:a,cea608Parser2:h,lastSn:l}=this,{cc:u,sn:d}=t.frag,p=(s=(n=t.part)==null?void 0:n.index)!=null?s:-1;a&&h&&(d!==l+1||d===l&&p!==this.lastPartIndex+1||u!==this.lastCc)&&(a.reset(),h.reset()),this.lastCc=u,this.lastSn=d,this.lastPartIndex=p}}onFragLoaded(e,t){const{frag:s,payload:n}=t;if(s.type===X.SUBTITLE)if(n.byteLength){const a=s.decryptdata,h="stats"in t;if(a==null||!a.encrypted||h){const l=this.tracks[s.level],u=this.vttCCs;u[s.cc]||(u[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),l&&l.textCodec===xa?this._parseIMSC1(s,n):this._parseVTTs(t)}}else this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;zh(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),s.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{s.logger.log(`Failed to parse IMSC1: ${n}`),s.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:s,payload:n}=e,{initPTS:a,unparsedVttFrags:h}=this,l=a.length-1;if(!a[s.cc]&&l===-1){h.push(e);return}const u=this.hls,d=(t=s.initSegment)!=null&&t.data?yt(s.initSegment.data,new Uint8Array(n)).buffer:n;Vx(d,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,p=>{this._appendCues(p,s.level),u.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},p=>{const g=p.message==="Missing initPTS for VTT MPEGTS";g?h.push(e):this._fallbackToIMSC1(s,n),u.logger.log(`Failed to parse VTT cue: ${p}`),!(g&&l>s.cc)&&u.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:p})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||zh(t,this.initPTS[e.cc],()=>{s.textCodec=xa,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||n.mode==="disabled")return;e.forEach(a=>_u(n,a))}else{const n=this.tracks[t];if(!n)return;const a=n.default?"default":"subtitles"+t;s.trigger(E.CUES_PARSED,{type:"subtitles",cues:e,track:a})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===X.SUBTITLE&&this.onFragLoaded(E.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:n}=t;if(!(s.type===X.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let a=0;a<n.length;a++){const h=n[a].bytes;if(h){this.cea608Parser1||this.initCea608Parsers();const l=this.extractCea608Data(h);this.cea608Parser1.addData(n[a].pts,l[0]),this.cea608Parser2.addData(n[a].pts,l[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:n,type:a}){const{media:h}=this;if(!(!h||h.currentTime<s)){if(!a||a==="video"){const{captionsTracks:l}=this;Object.keys(l).forEach(u=>io(l[u],t,s))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:l}=this;Object.keys(l).forEach(u=>io(l[u],t,n))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let n=2;for(let a=0;a<s;a++){const h=e[n++],l=127&e[n++],u=127&e[n++];if(l===0&&u===0)continue;if((4&h)!==0){const p=3&h;(p===0||p===1)&&(t[p].push(l),t[p].push(u))}}return t}}function Pu(r){return r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function Kh(r,e){return!!r&&r.kind===Pu(e)&&Za(e,r)}function Qx(r,e,t,s){return Math.min(e,s)-Math.max(r,t)}function Yh(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const Zx=/\s/,Jx={newCue(r,e,t,s){const n=[];let a,h,l,u,d;const p=self.VTTCue||self.TextTrackCue;for(let y=0;y<s.rows.length;y++)if(a=s.rows[y],l=!0,u=0,d="",!a.isEmpty()){var g;for(let _=0;_<a.chars.length;_++)Zx.test(a.chars[_].uchar)&&l?u++:(d+=a.chars[_].uchar,l=!1);a.cueStartTime=e,e===t&&(t+=1e-4),u>=16?u--:u++;const x=wu(d.trim()),v=Xo(e,t,x);r!=null&&(g=r.cues)!=null&&g.getCueById(v)||(h=new p(e,t,x),h.id=v,h.line=y+1,h.align="left",h.position=10+Math.min(80,Math.floor(u*8/32)*10),n.push(h))}return r&&n.length&&(n.sort((y,x)=>y.line==="auto"||x.line==="auto"?0:y.line>8&&x.line>8?x.line-y.line:y.line-x.line),n.forEach(y=>_u(r,y))),n}};function eS(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const tS=/(\d+)-(\d+)\/(\d+)/;class Wh{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||rS,this.controller=new self.AbortController,this.stats=new Lo}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const a=iS(e,this.controller.signal),h=e.responseType==="arraybuffer",l=h?"byteLength":"length",{maxTimeToFirstByteMs:u,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,a),self.clearTimeout(this.requestTimeout),t.timeout=u&&q(u)?u:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(Ys(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(g=>{var y;this.response=this.loader=g;const x=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},d-(x-n.loading.start)),!g.ok){const{status:_,statusText:o}=g;throw new aS(o||"fetch, bad network response",_,g)}n.loading.first=x,n.total=nS(g.headers)||n.total;const v=(y=this.callbacks)==null?void 0:y.onProgress;return v&&q(t.highWaterMark)?this.loadProgressively(g,n,e,t.highWaterMark,v):h?g.arrayBuffer():e.responseType==="json"?g.json():g.text()}).then(g=>{var y,x;const v=this.response;if(!v)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const _=g[l];_&&(n.loaded=n.total=_);const o={url:v.url,data:g,code:v.status},c=(y=this.callbacks)==null?void 0:y.onProgress;c&&!q(t.highWaterMark)&&c(n,e,g,v),(x=this.callbacks)==null||x.onSuccess(o,n,e,v)}).catch(g=>{var y;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const x=g&&g.code||0,v=g?g.message:null;(y=this.callbacks)==null||y.onError({code:x,text:v},e,g?g.details:null,n)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,n=0,a){const h=new Gd,l=e.body.getReader(),u=()=>l.read().then(d=>{if(d.done)return h.dataLength&&a(t,s,h.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const p=d.value,g=p.length;return t.loaded+=g,g<n||h.dataLength?(h.push(p),h.dataLength>=n&&a(t,s,h.flush().buffer,e)):a(t,s,p.buffer,e),u()}).catch(()=>Promise.reject());return u()}}function iS(r,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Ee({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function sS(r){const e=tS.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function nS(r){const e=r.get("Content-Range");if(e){const s=sS(e);if(q(s))return s}const t=r.get("Content-Length");if(t)return parseInt(t)}function rS(r,e){return new self.Request(r.url,e)}class aS extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const oS=/^age:\s*[\d.]+\s*$/im;class Du{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Lo,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const a=this.xhrSetup;a?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return a(s,t.url)}).catch(h=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),a(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(h=>{var l;(l=this.callbacks)==null||l.onError({code:s.status,text:h.message},t,s,n)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const n=t.headers,{maxTimeToFirstByteMs:a,maxLoadTimeMs:h}=s.loadPolicy;if(n)for(const l in n)e.setRequestHeader(l,n[l]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=a&&q(a)?a:h,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const n=t.readyState,a=this.config;if(!s.aborted&&n>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),a.timeout!==a.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),a.timeout=a.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),a.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),n===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const d=t.status,p=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){const v=p??t.response;if(v!=null){var h,l;s.loading.end=Math.max(self.performance.now(),s.loading.first);const _=t.responseType==="arraybuffer"?v.byteLength:v.length;s.loaded=s.total=_,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const o=(h=this.callbacks)==null?void 0:h.onProgress;o&&o(s,e,v,t);const c={url:t.responseURL,data:v,code:d};(l=this.callbacks)==null||l.onSuccess(c,s,e,t);return}}const g=a.loadPolicy.errorRetry,y=s.retry,x={url:e.url,data:void 0,code:d};if(tr(g,y,!1,x))this.retry(g);else{var u;_e.error(`${d} while loading ${e.url}`),(u=this.callbacks)==null||u.onError({code:d,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(tr(e,t,!0))this.retry(e);else{var s;_e.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=Do(e,s.retry),s.retry++,_e.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&oS.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const lS={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},hS=xe(xe({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Du,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:_m,bufferController:dv,capLevelController:Yo,errorController:Im,fpsController:ux,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Cd,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:lS},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},cS()),{},{subtitleStreamController:bx,subtitleTrackController:gx,timelineController:Xx,audioStreamController:ov,audioTrackController:lv,emeController:cs,cmcdController:lx,contentSteeringController:cx,interstitialsController:Tx});function cS(){return{cueHandler:Jx,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function dS(r,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=no(r),n=["manifest","level","frag"],a=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(h=>{const l=`${h==="level"?"playlist":h}LoadPolicy`,u=e[l]===void 0,d=[];a.forEach(p=>{const g=`${h}Loading${p}`,y=e[g];if(y!==void 0&&u){d.push(g);const x=s[l].default;switch(e[l]={default:x},p){case"TimeOut":x.maxLoadTimeMs=y,x.maxTimeToFirstByteMs=y;break;case"MaxRetry":x.errorRetry.maxNumRetry=y,x.timeoutRetry.maxNumRetry=y;break;case"RetryDelay":x.errorRetry.retryDelayMs=y,x.timeoutRetry.retryDelayMs=y;break;case"MaxRetryTimeout":x.errorRetry.maxRetryDelayMs=y,x.timeoutRetry.maxRetryDelayMs=y;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${l}": ${be(e[l])}`)}),xe(xe({},s),e)}function no(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(no):Object.keys(r).reduce((e,t)=>(e[t]=no(r[t]),e),{}):r}function uS(r,e){const t=r.loader;t!==Wh&&t!==Du?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):eS()&&(r.loader=Wh,r.progressive=!0,r.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Gn=2,fS=.1,pS=.05,gS=100;class mS extends Ad{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(gS),this.mediaSource=t.mediaSource;const s=this.media=t.media;Je(s,"playing",this.onMediaPlaying),Je(s,"waiting",this.onMediaWaiting),Je(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(it(s,"playing",this.onMediaPlaying),it(s,"waiting",this.onMediaWaiting),it(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,n;const a=(s=this.hls)==null?void 0:s.config;if(!a)return;const h=this.media;if(!h)return;const{seeking:l}=h,u=this.seeking&&!l,d=!this.seeking&&l,p=h.paused&&!l||h.ended||h.playbackRate===0;if(this.seeking=l,e!==t){t&&(this.ended=0),this.moved=!0,l||(this.nudgeRetry=0,a.nudgeOnVideoHole&&!p&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||u){u&&this.stallResolved(e);return}if(p){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&h.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1}));return}if(!ae.getBuffered(h).length){this.nudgeRetry=0;return}const g=ae.bufferInfo(h,e,0),y=g.nextStart||0,x=this.fragmentTracker;if(l&&x&&this.hls){const b=jh(this.hls.inFlightFragments,e),A=g.len>Gn,I=!y||b||y-e>Gn&&!x.getPartialFragment(e);if(A||I)return;this.moved=!1}const v=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&x){if(!(g.len>0)&&!y)return;const A=Math.max(y,g.start||0)-e,L=!!(v!=null&&v.live)?v.targetduration*2:Gn,w=In(e,x);if(A>0&&(A<=L||w)){h.paused||this._trySkipBufferHole(w);return}}const _=a.detectStallWithCurrentTimeMs,o=self.performance.now(),c=this.waiting;let f=this.stalled;if(f===null)if(c>0&&o-c<_)f=this.stalled=c;else{this.stalled=o;return}const m=o-f;if(!l&&(m>=_||c)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(v!=null&&v.live)&&Math.abs(e-((v==null?void 0:v.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(g),!this.media||!this.hls)return}const T=ae.bufferInfo(h,e,a.maxBufferHole);this._tryFixBufferStall(T,m,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(E.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&n&&n.length>1&&e>n.end(0)){const a=ae.bufferedInfo(ae.timeRangesToArray(this.buffered.audio),e,0);if(a.len>1&&t>=a.start){const h=ae.timeRangesToArray(n),l=ae.bufferedInfo(h,t,0).bufferedIndex;if(l>-1&&l<h.length-1){const u=ae.bufferedInfo(h,e,0).bufferedIndex,d=h[l].end,p=h[l+1].start;if((u===-1||u>l)&&p-d<1&&e-d<2){const g=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${p} buffered index: ${u}`);this.warn(g.message),this.media.currentTime+=1e-6;let y=In(e,this.fragmentTracker);y&&"fragment"in y?y=y.fragment:y||(y=void 0);const x=ae.bufferInfo(this.media,e,0);this.hls.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:g,reason:g.message,frag:y,buffer:x.len,bufferInfo:x})}}}}}_tryFixBufferStall(e,t,s){var n,a;const{fragmentTracker:h,media:l}=this,u=(n=this.hls)==null?void 0:n.config;if(!l||!h||!u)return;const d=(a=this.hls)==null?void 0:a.latestLevelDetails,p=In(s,h);if((p||d!=null&&d.live&&s<d.fragmentStart)&&(this._trySkipBufferHole(p)||!this.media))return;const g=e.buffered,y=this.adjacentTraversal(e,s);(g&&g.length>1&&e.len>u.maxBufferHole||e.nextStart&&(e.nextStart-s<u.maxBufferHole||y))&&(t>u.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,n=e.nextStart;if(s&&n){const a=s.getFragAtPos(t,X.MAIN),h=s.getFragAtPos(n,X.MAIN);if(a&&h)return h.sn-a.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:n,stalled:a}=this;if(!n&&a!==null&&s&&t){this.stallReported=!0;const h=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${be(e)})`);this.warn(h.message),t.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,fatal:!1,error:h,buffer:e.len,bufferInfo:e,stalled:{start:a}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:n}=this,a=(t=this.hls)==null?void 0:t.config;if(!n||!s||!a)return 0;const h=n.currentTime,l=ae.bufferInfo(n,h,0),u=h<l.start?l.start:l.nextStart;if(u&&this.hls){const p=l.len<=a.maxBufferHole,g=l.len>0&&l.len<1&&n.readyState<3,y=u-h;if(y>0&&(p||g)){if(y>a.maxBufferHole){let v=!1;if(h===0){const _=s.getAppendedFrag(0,X.MAIN);_&&u<_.end&&(v=!0)}if(!v&&e){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||jh(this.hls.inFlightFragments,u))return 0;let o=!1,c=e.end;for(;c<u;){const f=In(c,s);if(f)c+=f.duration;else{o=!0;break}}if(o)return 0}}const x=Math.max(u+pS,h+fS);if(this.warn(`skipping hole, adjusting currentTime from ${h} to ${x}`),this.moved=!0,n.currentTime=x,!(e!=null&&e.gap)){const v=new Error(`fragment loaded with buffer holes, seeking from ${h} to ${x}`),_={type:Z.MEDIA_ERROR,details:D.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:v,reason:v.message,buffer:l.len,bufferInfo:l};e&&("fragment"in e?_.part=e:_.frag=e),this.hls.trigger(E.ERROR,_)}return x}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:n}=this,a=t==null?void 0:t.config;if(!s||!a)return 0;const h=s.currentTime;if(this.nudgeRetry++,n<a.nudgeMaxRetry){const l=h+(n+1)*a.nudgeOffset,u=new Error(`Nudging 'currentTime' from ${h} to ${l}`);this.warn(u.message),s.currentTime=l,t.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.BUFFER_NUDGE_ON_STALL,error:u,fatal:!1,buffer:e.len,bufferInfo:e})}else{const l=new Error(`Playhead still not moving while enough data buffered @${h} after ${a.nudgeMaxRetry} nudges`);this.error(l.message),t.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}}}function jh(r,e){const t=qh(r.main);if(t&&t.start<=e)return t;const s=qh(r.audio);return s&&s.start<=e?s:null}function qh(r){if(!r)return null;switch(r.state){case F.IDLE:case F.STOPPED:case F.ENDED:case F.ERROR:return null}return r.frag}function In(r,e){return e.getAppendedFrag(r,X.MAIN)||e.getPartialFragment(r)}const yS=.25;function ro(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Ta(r,e,t,s,n){let a=new r(e,t,"");try{a.value=s,n&&(a.type=n)}catch{a=new r(e,t,be(n?xe({type:n},s):s))}return a}const wn=(()=>{const r=ro();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class vS{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(E.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&ss(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return Su(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:n}=this.hls.config;if(!s&&!n)return;const{samples:a}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const h=ro();if(h)for(let l=0;l<a.length;l++){const u=a[l].type;if(u===ct.emsg&&!s||!n)continue;const d=jd(a[l].data),p=a[l].pts;let g=p+a[l].duration;g>wn&&(g=wn),g-p<=0&&(g=p+yS);for(let x=0;x<d.length;x++){const v=d[x];if(!qd(v)){this.updateId3CueEnds(p,u);const _=Ta(h,p,g,v,u);_&&this.id3Track.addCue(_)}}}}updateId3CueEnds(e,t){var s;const n=(s=this.id3Track)==null?void 0:s.cues;if(n)for(let a=n.length;a--;){const h=n[a];h.type===t&&h.startTime<e&&h.endTime===wn&&(h.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:n}){const{id3Track:a,hls:h}=this;if(!h)return;const{config:{enableEmsgMetadataCues:l,enableID3MetadataCues:u}}=h;if(a&&(l||u)){let d;n==="audio"?d=p=>p.type===ct.audioId3&&u:n==="video"?d=p=>p.type===ct.emsg&&l:d=p=>p.type===ct.audioId3&&u||p.type===ct.emsg&&l,io(a,t,s,d)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:n,enableDateRangeMetadataCues:a,interstitialsController:h}=this.hls.config;if(!a)return;const l=ro();if(s&&n&&!h){const{fragmentStart:_,fragmentEnd:o}=e;let c=this.assetCue;c?(c.startTime=_,c.endTime=o):l&&(c=this.assetCue=Ta(l,_,o,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),c&&(c.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(c),c.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:u}=this,{dateRanges:d}=e,p=Object.keys(d);let g=this.dateRangeCuesAppended;if(u&&t){var y;if((y=u.cues)!=null&&y.length){const _=Object.keys(g).filter(o=>!p.includes(o));for(let o=_.length;o--;){var x;const c=_[o],f=(x=g[c])==null?void 0:x.cues;delete g[c],f&&Object.keys(f).forEach(m=>{const S=f[m];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{u.removeCue(S)}catch{}}})}}else g=this.dateRangeCuesAppended={}}const v=e.fragments[e.fragments.length-1];if(!(p.length===0||!q(v==null?void 0:v.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let _=0;_<p.length;_++){const o=p[_],c=d[o],f=c.startTime,m=g[o],S=(m==null?void 0:m.cues)||{};let T=(m==null?void 0:m.durationKnown)||!1,b=wn;const{duration:A,endDate:I}=c;if(I&&A!==null)b=f+A,T=!0;else if(c.endOnNext&&!T){const w=p.reduce((R,M)=>{if(M!==c.id){const k=d[M];if(k.class===c.class&&k.startDate>c.startDate&&(!R||c.startDate<R.startDate))return k}return R},null);w&&(b=w.startTime,T=!0)}const L=Object.keys(c.attr);for(let w=0;w<L.length;w++){const R=L[w];if(!Nm(R))continue;const M=S[R];if(M)T&&!(m!=null&&m.durationKnown)?M.endTime=b:Math.abs(M.startTime-f)>.01&&(M.startTime=f,M.endTime=b);else if(l){let k=c.attr[R];$m(R)&&(k=rd(k));const O=Ta(l,f,b,{key:R,data:k},ct.dateRange);O&&(O.id=o,this.id3Track.addCue(O),S[R]=O,h&&(R==="X-ASSET-LIST"||R==="X-ASSET-URL")&&O.addEventListener("enter",this.onEventCueEnter))}}g[o]={cues:S,dateRange:c,durationKnown:T}}}}}class xS{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:a,maxLiveSyncPlaybackRate:h}=this.config;if(!a||h===1||!s.live)return;const l=this.targetLatency;if(l===null)return;const u=n-l,d=Math.min(this.maxLatency,l+s.targetduration);if(u<d&&u>.05&&this.forwardBufferLength>1){const g=Math.min(2,Math.max(1,h)),y=Math.round(2/(1+Math.exp(-.75*u-this.edgeStalled))*20)/20,x=Math.min(g,Math.max(1,y));this.changeMediaPlaybackRate(t,x)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:s,targetduration:n}=e,{liveSyncDuration:a,liveSyncDurationCount:h,lowLatencyMode:l}=this.config,u=this.hls.userConfig;let d=l&&s||t;(this._targetLatencyUpdated||u.liveSyncDuration||u.liveSyncDurationCount||d===0)&&(d=a!==void 0?a:h*n);const p=n;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,p)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const s=this.levelDetails;if(s===null)return null;const n=s.edge,a=e-t-this.edgeStalled,h=n-s.totalduration,l=n-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(h,a),l)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===D.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,n;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(n=this.targetLatency)==null?void 0:n.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class SS extends Ko{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,n=[],a={},h={};let l=!1,u=!1,d=!1;t.levels.forEach(p=>{const g=p.attrs;let{audioCodec:y,videoCodec:x}=p;y&&(p.audioCodec=y=Qn(y,s)||void 0),x&&(x=p.videoCodec=im(x));const{width:v,height:_,unknownCodecs:o}=p,c=(o==null?void 0:o.length)||0;if(l||(l=!!(v&&_)),u||(u=!!x),d||(d=!!y),c||y&&!this.isAudioSupported(y)||x&&!this.isVideoSupported(x)){this.log(`Some or all CODECS not supported "${g.CODECS}"`);return}const{CODECS:f,"FRAME-RATE":m,"HDCP-LEVEL":S,"PATHWAY-ID":T,RESOLUTION:b,"VIDEO-RANGE":A}=g,L=`${`${T||"."}-`}${p.bitrate}-${b}-${m}-${f}-${A}-${S}`;if(a[L])if(a[L].uri!==p.url&&!p.attrs["PATHWAY-ID"]){const w=h[L]+=1;p.attrs["PATHWAY-ID"]=new Array(w+1).join(".");const R=this.createLevel(p);a[L]=R,n.push(R)}else a[L].addGroupId("audio",g.AUDIO),a[L].addGroupId("text",g.SUBTITLES);else{const w=this.createLevel(p);a[L]=w,h[L]=1,n.push(w)}}),this.filterAndSortMediaOptions(n,t,l,u,d)}createLevel(e){const t=new Hs(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const n=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(n.message),t.supportedResult=yd(n,[])}return t}isAudioSupported(e){return Gs(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Gs(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,n,a){var h;let l=[],u=[],d=e;const p=((h=t.stats)==null?void 0:h.parsing)||{};if((s||n)&&a&&(d=d.filter(({videoCodec:f,videoRange:m,width:S,height:T})=>(!!f||!!(S&&T))&&um(m))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let f="no level with compatible codecs found in manifest",m=f;t.levels.length&&(m=`one or more CODECS in variant not supported: ${be(t.levels.map(T=>T.attrs.CODECS).filter((T,b,A)=>A.indexOf(T)===b))}`,this.warn(m),f+=` (${m})`);const S=new Error(f);this.hls.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:S,reason:m})}}),p.end=performance.now();return}t.audioTracks&&(l=t.audioTracks.filter(f=>!f.audioCodec||this.isAudioSupported(f.audioCodec)),Xh(l)),t.subtitles&&(u=t.subtitles,Xh(u));const g=d.slice(0);d.sort((f,m)=>{if(f.attrs["HDCP-LEVEL"]!==m.attrs["HDCP-LEVEL"])return(f.attrs["HDCP-LEVEL"]||"")>(m.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&f.height!==m.height)return f.height-m.height;if(f.frameRate!==m.frameRate)return f.frameRate-m.frameRate;if(f.videoRange!==m.videoRange)return Zn.indexOf(f.videoRange)-Zn.indexOf(m.videoRange);if(f.videoCodec!==m.videoCodec){const S=Gl(f.videoCodec),T=Gl(m.videoCodec);if(S!==T)return T-S}if(f.uri===m.uri&&f.codecSet!==m.codecSet){const S=Xn(f.codecSet),T=Xn(m.codecSet);if(S!==T)return T-S}return f.averageBitrate!==m.averageBitrate?f.averageBitrate-m.averageBitrate:0});let y=g[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==g.length)){for(let f=0;f<g.length;f++)if(g[f].pathwayId===d[0].pathwayId){y=g[f];break}}this._levels=d;for(let f=0;f<d.length;f++)if(d[f]===y){var x;this._firstLevel=f;const m=y.bitrate,S=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${m}`),((x=this.hls.userConfig)==null?void 0:x.abrEwmaDefaultEstimate)===void 0){const T=Math.min(m,this.hls.config.abrEwmaDefaultEstimateMax);T>S&&S===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=T)}break}const v=a&&!n,_=this.hls.config,o=!!(_.audioStreamController&&_.audioTrackController),c={levels:d,audioTracks:l,subtitleTracks:u,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:a,video:n,altAudio:o&&!v&&l.some(f=>!!f.url)};p.end=performance.now(),this.hls.trigger(E.MANIFEST_PARSED,c)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const p=new Error("invalid level idx"),g=e<0;if(this.hls.trigger(E.ERROR,{type:Z.OTHER_ERROR,details:D.LEVEL_SWITCH_ERROR,level:e,fatal:g,error:p,reason:p.message}),g)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,n=this.currentLevel,a=n?n.attrs["PATHWAY-ID"]:void 0,h=t[e],l=h.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=h,s===e&&n&&a===l)return;this.log(`Switching to level ${e} (${h.height?h.height+"p ":""}${h.videoRange?h.videoRange+" ":""}${h.codecSet?h.codecSet+" ":""}@${h.bitrate})${l?" with Pathway "+l:""} from level ${s}${a?" with Pathway "+a:""}`);const u={level:e,attrs:h.attrs,details:h.details,bitrate:h.bitrate,averageBitrate:h.averageBitrate,maxBitrate:h.maxBitrate,realBitrate:h.realBitrate,width:h.width,height:h.height,codecSet:h.codecSet,audioCodec:h.audioCodec,videoCodec:h.videoCodec,audioGroups:h.audioGroups,subtitleGroups:h.subtitleGroups,loaded:h.loaded,loadError:h.loadError,fragmentError:h.fragmentError,name:h.name,id:h.id,uri:h.uri,url:h.url,urlId:0,audioGroupIds:h.audioGroupIds,textGroupIds:h.textGroupIds};this.hls.trigger(E.LEVEL_SWITCHING,u);const d=h.details;if(!d||d.live){const p=this.switchParams(h.uri,n==null?void 0:n.details,d);this.loadPlaylist(p)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(n=>t.indexOf(n)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===fe.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===X.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(a=>!!s[a]))return;const n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var s;const{level:n,details:a}=t,h=t.levelInfo;if(!h){var l;this.warn(`Invalid level index ${n}`),(l=t.deliveryDirectives)!=null&&l.skip&&(a.deltaUpdateFailed=!0);return}if(h===this.currentLevel||t.withoutMultiVariant){h.fragmentError===0&&(h.loadError=0);let u=h.details;u===t.details&&u.advanced&&(u=void 0),this.playlistLoaded(n,t,u)}else(s=t.deliveryDirectives)!=null&&s.skip&&(a.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),n=this.currentLevelIndex,a=e.attrs["PATHWAY-ID"],h=e.details,l=h==null?void 0:h.age;this.log(`Loading level index ${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${a?" Pathway "+a:""}${l&&h.live?" age "+l.toFixed(1)+(h.type&&" "+h.type||""):""} ${s}`),this.hls.trigger(E.LEVEL_LOADING,{url:s,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const s=this._levels.filter((a,h)=>h!==e?!0:(this.steering&&this.steering.removeLevel(a),a===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,a.details&&a.details.fragments.forEach(l=>l.level=-1)),!1));Bd(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const n=s.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(E.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function Xh(r){const e={};r.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function ku(){return self.SourceBuffer||self.WebKitSourceBuffer}function Mu(){if(!Si())return!1;const e=ku();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function _S(){if(!Mu())return!1;const r=Si();return typeof(r==null?void 0:r.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>r.isTypeSupported(zs(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(zs(e,"audio"))))}function ES(){var r;const e=ku();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}const TS=100;class bS extends Oo{constructor(e,t,s){super(e,t,s,"stream-controller",X.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const n=this.media,a=n?n.currentTime:null;if(a===null||!q(a)||(this.log(`Media seeked to ${a.toFixed(3)}`),!this.getBufferedFrag(a)))return;const h=this.getFwdBufferInfoAtPos(n,a,X.MAIN,0);if(h===null||h.len===0){this.warn(`Main forward buffer length at ${a} on "seeked" event ${h?h.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:n}=this;if(this.stopLoad(),this.setInterval(TS),this.level=-1,!this.startFragRequested){let a=n.startLevel;a===-1&&(n.config.testBandwidth&&this.levels.length>1?(a=0,this.bitrateTest=!0):a=n.firstAutoLevel),n.nextLoadLevel=a,this.level=n.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=F.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=F.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case F.WAITING_LEVEL:{const{levels:e,level:t}=this,s=e==null?void 0:e[t],n=s==null?void 0:s.details;if(n&&(!n.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(n))break;this.state=F.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=F.IDLE;break}break}case F.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===F.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:n}=this;if(t===null||!n&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const a=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[a]))return;const h=s[a],l=this.getMainFwdBufferInfo();if(l===null)return;const u=this.getLevelDetails();if(u&&this._streamEnded(l,u)){const _={};this.altAudio===2&&(_.type="video"),this.hls.trigger(E.BUFFER_EOS,_),this.state=F.ENDED;return}if(!this.buffering)return;e.loadLevel!==a&&e.manualLevel===-1&&this.log(`Adapting to level ${a} from level ${this.level}`),this.level=e.nextLoadLevel=a;const d=h.details;if(!d||this.state===F.WAITING_LEVEL||this.waitForLive(h)){this.level=a,this.state=F.WAITING_LEVEL,this.startFragRequested=!1;return}const p=l.len,g=this.getMaxBufferLength(h.maxBitrate);if(p>=g)return;this.backtrackFragment&&this.backtrackFragment.start>l.end&&(this.backtrackFragment=null);const y=this.backtrackFragment?this.backtrackFragment.start:l.end;let x=this.getNextFragment(y,d);if(this.couldBacktrack&&!this.fragPrevious&&x&&Pe(x)&&this.fragmentTracker.getState(x)!==Fe.OK){var v;const o=((v=this.backtrackFragment)!=null?v:x).sn-d.startSN,c=d.fragments[o-1];c&&x.cc===c.cc&&(x=c,this.fragmentTracker.removeFragment(c))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(x&&this.isLoopLoading(x,y)){if(!x.gap){const o=this.audioOnly&&!this.altAudio?Te.AUDIO:Te.VIDEO,c=(o===Te.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;c&&this.afterBufferFlushed(c,o,X.MAIN)}x=this.getNextFragmentLoopLoading(x,d,l,X.MAIN,g)}x&&(x.initSegment&&!x.initSegment.data&&!this.bitrateTest&&(x=x.initSegment),this.loadFragment(x,h,y))}loadFragment(e,t,s){const n=this.fragmentTracker.getState(e);n===Fe.NOT_LOADED||n===Fe.PARTIAL?Pe(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,X.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const a=this.getLevelDetails();if(a!=null&&a.live){const l=this.getMainFwdBufferInfo();if(!l||l.len<a.targetduration*2)return}if(!t.paused&&e){const l=this.hls.nextLoadLevel,u=e[l],d=this.fragLastKbps;d&&this.fragCurrent?s=this.fragCurrent.duration*u.maxBitrate/(1e3*d)+1:s=0}else s=0;const h=this.getBufferedFrag(t.currentTime+s);if(h){const l=this.followingBufferedFrag(h);if(l){this.abortCurrentFrag();const u=l.maxStartPTS?l.maxStartPTS:l.start,d=l.duration,p=Math.max(h.end,u+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(p,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case F.KEY_LOADING:case F.FRAG_LOADING:case F.FRAG_LOADING_WAITING_RETRY:case F.PARSING:case F.PARSED:this.state=F.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;Je(s,"playing",this.onMediaPlaying),Je(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(it(s,"playing",this.onMediaPlaying),it(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(E.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,n=!1;for(let a=0;a<t.levels.length;a++){const h=t.levels[a].audioCodec;h&&(s=s||h.indexOf("mp4a.40.2")!==-1,n=n||h.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&n&&!ES(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==F.IDLE)return;const n=t.levelInfo;(!n.details||n.details.live&&(this.levelLastLoaded!==n||n.details.expired)||this.waitForCdnTuneIn(n.details))&&(this.state=F.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:n,startFragRequested:a}=this,h=t.level,l=t.details,u=l.totalduration;if(!n){this.warn(`Levels were reset while loading level ${h}`);return}this.log(`Level ${h} loaded [${l.startSN},${l.endSN}]${l.lastPartSn?`[part-${l.lastPartSn}-${l.lastPartIndex}]`:""}, cc [${l.startCC}, ${l.endCC}] duration:${u}`);const d=t.levelInfo,p=this.fragCurrent;p&&(this.state===F.FRAG_LOADING||this.state===F.FRAG_LOADING_WAITING_RETRY)&&p.level!==t.level&&p.loader&&this.abortCurrentFrag();let g=0;if(l.live||(s=d.details)!=null&&s.live){var y;if(this.checkLiveUpdate(l),l.deltaUpdateFailed)return;g=this.alignPlaylists(l,d.details,(y=this.levelLastLoaded)==null?void 0:y.details)}if(d.details=l,this.levelLastLoaded=d,a||this.setStartPosition(l,g),this.hls.trigger(E.LEVEL_UPDATED,{details:l,level:h}),this.state===F.WAITING_LEVEL){if(this.waitForCdnTuneIn(l))return;this.state=F.IDLE}a&&l.live&&this.synchronizeToLiveEdge(l),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const n=this.hls.liveSyncPosition,a=this.getLoadPosition(),h=e.fragmentStart,l=e.edge,u=a>=h-t.maxFragLookUpTolerance&&a<=l;if(n!==null&&s.duration>n&&(a<n||!u)){const p=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!u&&s.readyState<4||a<l-p)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),s.readyState))if(this.warn(`Playback: ${a.toFixed(3)} is located too far from the end of live sliding playlist: ${l}, reset currentTime to : ${n.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var d;const g=ae.bufferInfo(s,n,0);if(!((d=g.buffered)!=null&&d.length)){s.currentTime=n;return}if(g.start<=a){s.currentTime=n;return}const{nextStart:x}=ae.bufferedInfo(g.buffered,a,0);x&&(s.currentTime=x)}else s.currentTime=n}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:n,payload:a}=e,{levels:h}=this;if(!h){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const l=h[s.level];if(!l){this.warn(`Level ${s.level} not found on progress`);return}const u=l.details;if(!u){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const d=l.videoCodec,p=u.PTSKnown||!u.live,g=(t=s.initSegment)==null?void 0:t.data,y=this._getAudioCodec(l),x=this.transmuxer=this.transmuxer||new au(this.hls,X.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),v=n?n.index:-1,_=v!==-1,o=new Mo(s.level,s.sn,s.stats.chunkCount,a.byteLength,v,_),c=this.initPTS[s.cc];x.push(a,g,y,d,s,n,u.totalduration,p,o,c)}onAudioTrackSwitching(e,t){const s=this.hls,n=this.altAudio===2;if(Jn(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const h=this.fragCurrent;h&&(this.log("Switching to main audio track, cancel main fragment load"),h.abortRequests(),this.fragmentTracker.removeFragment(h)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n){this.fragmentTracker.removeAllFragments(),s.once(E.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(E.AUDIO_TRACK_SWITCHED,t)}),s.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(E.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=Jn(t.url,this.hls);if(s){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let n,a,h=!1;for(const l in s){const u=s[l];if(u.id==="main"){if(a=l,n=u,l==="video"){const d=s[l];d&&(this.videoBuffer=d.buffer)}}else h=!0}h&&n?(this.log(`Alternate track found, use ${a}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:n}=t,a=s.type===X.MAIN;if(a){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${n?" p: "+n.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===F.PARSED&&(this.state=F.IDLE);return}const l=n?n.stats:s.stats;this.fragLastKbps=Math.round(8*l.total/(l.buffering.end-l.loading.first)),Pe(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,n)}const h=this.media;h&&(!this._hasEnoughToStart&&ae.getBuffered(h).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),a&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=F.ERROR;return}switch(t.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(X.MAIN,t);break;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===F.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===fe.LEVEL&&(this.state=F.IDLE);break;case D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case D.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case D.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=F.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Te.AUDIO||!this.altAudio){const s=(t===Te.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,X.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const n=this.timelineOffset;n&&s&&(s+=n);const a=this.getLevelDetails(),h=ae.getBuffered(e),l=h.length?h.start(0):0,u=l-s,d=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||u>0&&(u<d||this.loadingParts&&u<2*((a==null?void 0:a.partTarget)||0)))&&(this.log(`adjusting start position by ${u} to match buffer start`),s+=u,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${l}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:n}=this,a=s==null?void 0:s.frag;if(!a||this.fragContextChanged(a))return;t.fragmentError=0,this.state=F.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const h=a.stats;h.parsing.start=h.parsing.end=h.buffering.start=h.buffering.end=self.performance.now(),n.trigger(E.FRAG_LOADED,s),a.bitrateTest=!1}).catch(s=>{this.state===F.STOPPED||this.state===F.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:n,chunkMeta:a}=e,h=this.getCurrentContext(a);if(!h){this.resetWhenMissingContext(a);return}const{frag:l,part:u,level:d}=h,{video:p,text:g,id3:y,initSegment:x}=n,{details:v}=d,_=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=F.PARSING,x){const o=x.tracks;if(o){const S=l.initSegment||l;if(this.unhandledEncryptionError(x,l))return;this._bufferInitSegment(d,o,S,a),s.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:t,tracks:o})}const c=x.initPTS,f=x.timescale,m=this.initPTS[l.cc];if(q(c)&&(!m||m.baseTime!==c||m.timescale!==f)){const S=x.trackId;this.initPTS[l.cc]={baseTime:c,timescale:f,trackId:S},s.trigger(E.INIT_PTS_FOUND,{frag:l,id:t,initPTS:c,timescale:f,trackId:S})}}if(p&&v){_&&p.type==="audiovideo"&&this.logMuxedErr(l);const o=v.fragments[l.sn-1-v.startSN],c=l.sn===v.startSN,f=!o||l.cc>o.cc;if(n.independent!==!1){const{startPTS:m,endPTS:S,startDTS:T,endDTS:b}=p;if(u)u.elementaryStreams[p.type]={startPTS:m,endPTS:S,startDTS:T,endDTS:b};else if(p.firstKeyFrame&&p.independent&&a.id===1&&!f&&(this.couldBacktrack=!0),p.dropped&&p.independent){const A=this.getMainFwdBufferInfo(),I=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,L=p.firstKeyFramePTS?p.firstKeyFramePTS:m;if(!c&&I<L-this.config.maxBufferHole&&!f){this.backtrack(l);return}else f&&(l.gap=!0);l.setElementaryStreamInfo(p.type,l.start,S,l.start,b,!0)}else c&&m-(v.appliedTimelineOffset||0)>Gn&&(l.gap=!0);l.setElementaryStreamInfo(p.type,m,S,T,b),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(p,l,u,a,c||f)}else if(c||f)l.gap=!0;else{this.backtrack(l);return}}if(_){const{startPTS:o,endPTS:c,startDTS:f,endDTS:m}=_;u&&(u.elementaryStreams[Te.AUDIO]={startPTS:o,endPTS:c,startDTS:f,endDTS:m}),l.setElementaryStreamInfo(Te.AUDIO,o,c,f,m),this.bufferFragmentData(_,l,u,a)}if(v&&y!=null&&y.samples.length){const o={id:t,frag:l,details:v,samples:y.samples};s.trigger(E.FRAG_PARSING_METADATA,o)}if(v&&g){const o={id:t,frag:l,details:v,samples:g.samples};s.trigger(E.FRAG_PARSING_USERDATA,o)}}logMuxedErr(e){this.warn(`${Pe(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,n){if(this.state!==F.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:a,video:h,audiovideo:l}=t;if(a){const d=e.audioCodec;let p=Mn(a.codec,d);p==="mp4a"&&(p="mp4a.40.5");const g=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){p&&(p.indexOf("mp4a.40.5")!==-1?p="mp4a.40.2":p="mp4a.40.5");const y=a.metadata;y&&"channelCount"in y&&(y.channelCount||1)!==1&&g.indexOf("firefox")===-1&&(p="mp4a.40.5")}p&&p.indexOf("mp4a.40.5")!==-1&&g.indexOf("android")!==-1&&a.container!=="audio/mpeg"&&(p="mp4a.40.2",this.log(`Android: force audio codec to ${p}`)),d&&d!==p&&this.log(`Swapping manifest audio codec "${d}" for "${p}"`),a.levelCodec=p,a.id=X.MAIN,this.log(`Init audio buffer, container:${a.container}, codecs[selected/level/parsed]=[${p||""}/${d||""}/${a.codec}]`),delete t.audiovideo}if(h){h.levelCodec=e.videoCodec,h.id=X.MAIN;const d=h.codec;if((d==null?void 0:d.length)===4)switch(d){case"hvc1":case"hev1":h.codec="hvc1.1.6.L120.90";break;case"av01":h.codec="av01.0.04M.08";break;case"avc1":h.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${h.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${h.codec!==d?" parsed-corrected="+h.codec:""}${h.supplemental?" supplemental="+h.supplemental:""}`),delete t.audiovideo}l&&(this.log(`Init audiovideo buffer, container:${l.container}, codecs[level/parsed]=[${e.codecs}/${l.codec}]`),delete t.video,delete t.audio);const u=Object.keys(t);if(u.length){if(this.hls.trigger(E.BUFFER_CODECS,t),!this.hls)return;u.forEach(d=>{const g=t[d].initSegment;g!=null&&g.byteLength&&this.hls.trigger(E.BUFFER_APPENDING,{type:d,data:g,frag:s,part:null,chunkMeta:n,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,X.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e==null?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=F.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(ae.isBuffered(e,s)?t=this.getAppendedFrag(s):ae.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const n=this.fragPlaying,a=t.level;(!n||t.sn!==n.sn||n.level!==a)&&(this.fragPlaying=t,this.hls.trigger(E.FRAG_CHANGED,{frag:t}),(!n||n.level!==a)&&this.hls.trigger(E.LEVEL_SWITCHED,{level:a}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return q(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(q(t)){const s=this.getLevelDetails(),n=this.currentFrag||(s?zi(null,s.fragments,t):null);if(n){const a=n.programDateTime;if(a!==null){const h=a+(t-n.start)*1e3;return new Date(h)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class AS extends xt{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[s].loader;if(n){var t;if(e&&e!==((t=n.context)==null?void 0:t.frag.type))return;n.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=D.KEY_LOAD_ERROR,s,n,a){return new qt({type:Z.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:a,error:s,networkDetails:n})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let n=0,a=t.length;n<a;n++){const h=t[n];if(e.cc<=h.cc&&(!Pe(e)||!Pe(h)||e.sn<h.sn)||!s&&n==a-1)return this.emeController.selectKeySystemFormat(h).then(l=>{if(!this.emeController)return;h.setKeyFormat(l);const u=Un(l);if(u)return this.emeController.getKeySystemAccess([u])})}if(this.config.requireKeySystemAccessOnStart){const n=Rs(this.config);if(n.length)return this.emeController.getKeySystemAccess(n)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,n;t&&e.setKeyFormat(t);const a=e.decryptdata;if(!a){const d=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,d))}const h=a.uri;if(!h)return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${h}"`)));const l=ba(a);let u=this.keyIdToKeyInfo[l];if((s=u)!=null&&s.decryptdata.key)return a.key=u.decryptdata.key,Promise.resolve({frag:e,keyInfo:u});if(this.emeController&&(n=u)!=null&&n.keyLoadPromise)switch(this.emeController.getKeyStatus(u.decryptdata)){case"usable":case"usable-in-future":return u.keyLoadPromise.then(p=>{const{keyInfo:g}=p;return a.key=g.decryptdata.key,{frag:e,keyInfo:g}})}switch(this.log(`${this.keyIdToKeyInfo[l]?"Rel":"L"}oading${a.keyId?" keyId: "+Ze(a.keyId):""} URI: ${a.uri} from ${e.type} ${e.level}`),u=this.keyIdToKeyInfo[l]={decryptdata:a,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},a.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return a.keyFormat==="identity"?this.loadKeyHTTP(u,e):this.loadKeyEME(u,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(u,e);default:return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${a.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var n;if(!e.decryptdata.keyId&&(n=t.initSegment)!=null&&n.data){const h=V0(t.initSegment.data);if(h.length){const l=h[0];l.some(u=>u!==0)&&(this.log(`Using keyId found in init segment ${Ze(l)}`),e.decryptdata.keyId=l,Ni.setKeyIdForUri(e.decryptdata.uri,l))}}const a=this.emeController.loadKey(s);return(e.keyLoadPromise=a.then(h=>(e.mediaKeySessionContext=h,s))).catch(h=>{throw e.keyLoadPromise=null,"data"in h&&(h.data.frag=t),h})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,n=s.loader,a=new n(s);return t.keyLoader=e.loader=a,e.keyLoadPromise=new Promise((h,l)=>{const u={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=s.keyLoadPolicy.default,p={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(y,x,v,_)=>{const{frag:o,keyInfo:c}=v,f=ba(c.decryptdata);if(!o.decryptdata||c!==this.keyIdToKeyInfo[f])return l(this.createKeyLoadError(o,D.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),_));c.decryptdata.key=o.decryptdata.key=new Uint8Array(y.data),o.keyLoader=null,c.loader=null,h({frag:o,keyInfo:c})},onError:(y,x,v,_)=>{this.resetLoader(x),l(this.createKeyLoadError(t,D.KEY_LOAD_ERROR,new Error(`HTTP Error ${y.code} loading key ${y.text}`),v,xe({url:u.url,data:void 0},y)))},onTimeout:(y,x,v)=>{this.resetLoader(x),l(this.createKeyLoadError(t,D.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),v))},onAbort:(y,x,v)=>{this.resetLoader(x),l(this.createKeyLoadError(t,D.INTERNAL_ABORTED,new Error("key loading aborted"),v))}};a.load(u,p,g)})}resetLoader(e){const{frag:t,keyInfo:s,url:n}=e,a=s.loader;t.keyLoader===a&&(t.keyLoader=null,s.loader=null);const h=ba(s.decryptdata)||n;delete this.keyIdToKeyInfo[h],a&&a.destroy()}}function ba(r){if(r.keyFormat!==Ve.FAIRPLAY){const e=r.keyId;if(e)return Ze(e)}return r.uri}function Qh(r){const{type:e}=r;switch(e){case fe.AUDIO_TRACK:return X.AUDIO;case fe.SUBTITLE_TRACK:return X.SUBTITLE;default:return X.MAIN}}function Aa(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class IS{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,n=t.loader,a=s||n,h=new a(t);return this.loaders[e.type]=h,h}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:fe.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:n,pathwayId:a,url:h,deliveryDirectives:l,levelInfo:u}=t;this.load({id:s,level:n,pathwayId:a,responseType:"text",type:fe.LEVEL,url:h,deliveryDirectives:l,levelOrTrack:u})}onAudioTrackLoading(e,t){const{id:s,groupId:n,url:a,deliveryDirectives:h,track:l}=t;this.load({id:s,groupId:n,level:null,responseType:"text",type:fe.AUDIO_TRACK,url:a,deliveryDirectives:h,levelOrTrack:l})}onSubtitleTrackLoading(e,t){const{id:s,groupId:n,url:a,deliveryDirectives:h,track:l}=t;this.load({id:s,groupId:n,level:null,responseType:"text",type:fe.SUBTITLE_TRACK,url:a,deliveryDirectives:h,levelOrTrack:l})}onLevelsUpdated(e,t){const s=this.loaders[fe.LEVEL];if(s){const n=s.context;n&&!t.levels.some(a=>a===n.levelOrTrack)&&(s.abort(),delete this.loaders[fe.LEVEL])}}load(e){var t;const s=this.hls.config;let n=this.getInternalLoader(e);if(n){const d=this.hls.logger,p=n.context;if(p&&p.levelOrTrack===e.levelOrTrack&&(p.url===e.url||p.deliveryDirectives&&!e.deliveryDirectives)){p.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${p.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let a;if(e.type===fe.MANIFEST?a=s.manifestLoadPolicy.default:a=Ee({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),q((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===fe.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===fe.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===fe.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){const p=d.partTarget,g=d.targetduration;if(p&&g){const y=Math.max(p*3,g*.8)*1e3;a=Ee({},a,{maxTimeToFirstByteMs:Math.min(y,a.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(y,a.maxTimeToFirstByteMs)})}}}const h=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:h.maxNumRetry||0,retryDelay:h.retryDelayMs||0,maxRetryDelay:h.maxRetryDelayMs||0},u={onSuccess:(d,p,g,y)=>{const x=this.getInternalLoader(g);this.resetInternalLoader(g.type);const v=d.data;p.parsing.start=performance.now(),Ut.isMediaPlaylist(v)||g.type!==fe.MANIFEST?this.handleTrackOrLevelPlaylist(d,p,g,y||null,x):this.handleMasterPlaylist(d,p,g,y)},onError:(d,p,g,y)=>{this.handleNetworkError(p,g,!1,d,y)},onTimeout:(d,p,g)=>{this.handleNetworkError(p,g,!0,void 0,d)}};n.load(e,l,u)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,n){const a=this.hls,h=e.data,l=Aa(e,s),u=Ut.parseMasterPlaylist(h,l);if(u.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,u.playlistParsingError,n,t);return}const{contentSteering:d,levels:p,sessionData:g,sessionKeys:y,startTimeOffset:x,variableList:v}=u;this.variableList=v,p.forEach(f=>{const{unknownCodecs:m}=f;if(m){const{preferManagedMediaSource:S}=this.hls.config;let{audioCodec:T,videoCodec:b}=f;for(let A=m.length;A--;){const I=m[A];Gs(I,"audio",S)?(f.audioCodec=T=T?`${T},${I}`:I,ms.audio[T.substring(0,4)]=2,m.splice(A,1)):Gs(I,"video",S)&&(f.videoCodec=b=b?`${b},${I}`:I,ms.video[b.substring(0,4)]=2,m.splice(A,1))}}});const{AUDIO:_=[],SUBTITLES:o,"CLOSED-CAPTIONS":c}=Ut.parseMasterPlaylistMedia(h,l,u);_.length&&!_.some(m=>!m.url)&&p[0].audioCodec&&!p[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),_.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ae({}),bitrate:0,url:""})),a.trigger(E.MANIFEST_LOADED,{levels:p,audioTracks:_,subtitles:o,captions:c,contentSteering:d,url:l,stats:t,networkDetails:n,sessionData:g,sessionKeys:y,startTimeOffset:x,variableList:v})}handleTrackOrLevelPlaylist(e,t,s,n,a){const h=this.hls,{id:l,level:u,type:d}=s,p=Aa(e,s),g=q(u)?u:q(l)?l:0,y=Qh(s),x=Ut.parseLevelPlaylist(e.data,p,g,y,0,this.variableList);if(d===fe.MANIFEST){const v={attrs:new Ae({}),bitrate:0,details:x,name:"",url:p};x.requestScheduled=t.loading.start+Fd(x,0),h.trigger(E.MANIFEST_LOADED,{levels:[v],audioTracks:[],url:p,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=x,this.handlePlaylistLoaded(x,e,t,s,n,a)}handleManifestParsingError(e,t,s,n,a){this.hls.trigger(E.ERROR,{type:Z.NETWORK_ERROR,details:D.MANIFEST_PARSING_ERROR,fatal:t.type===fe.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:n,stats:a})}handleNetworkError(e,t,s=!1,n,a){let h=`A network ${s?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===fe.LEVEL?h+=`: ${e.level} id: ${e.id}`:(e.type===fe.AUDIO_TRACK||e.type===fe.SUBTITLE_TRACK)&&(h+=` id: ${e.id} group-id: "${e.groupId}"`);const l=new Error(h);this.hls.logger.warn(`[playlist-loader]: ${h}`);let u=D.UNKNOWN,d=!1;const p=this.getInternalLoader(e);switch(e.type){case fe.MANIFEST:u=s?D.MANIFEST_LOAD_TIMEOUT:D.MANIFEST_LOAD_ERROR,d=!0;break;case fe.LEVEL:u=s?D.LEVEL_LOAD_TIMEOUT:D.LEVEL_LOAD_ERROR,d=!1;break;case fe.AUDIO_TRACK:u=s?D.AUDIO_TRACK_LOAD_TIMEOUT:D.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case fe.SUBTITLE_TRACK:u=s?D.SUBTITLE_TRACK_LOAD_TIMEOUT:D.SUBTITLE_LOAD_ERROR,d=!1;break}p&&this.resetInternalLoader(e.type);const g={type:Z.NETWORK_ERROR,details:u,fatal:d,url:e.url,loader:p,context:e,error:l,networkDetails:t,stats:a};if(n){const y=(t==null?void 0:t.url)||e.url;g.response=xe({url:y,data:void 0},n)}this.hls.trigger(E.ERROR,g)}handlePlaylistLoaded(e,t,s,n,a,h){const l=this.hls,{type:u,level:d,levelOrTrack:p,id:g,groupId:y,deliveryDirectives:x}=n,v=Aa(t,n),_=Qh(n);let o=typeof n.level=="number"&&_===X.MAIN?d:void 0;const c=e.playlistParsingError;if(c){if(this.hls.logger.warn(`${c} ${e.url}`),!l.config.ignorePlaylistParsingErrors){l.trigger(E.ERROR,{type:Z.NETWORK_ERROR,details:D.LEVEL_PARSING_ERROR,fatal:!1,url:v,error:c,reason:c.message,response:t,context:n,level:o,parent:_,networkDetails:a,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const f=e.playlistParsingError=new Error("No Segments found in Playlist");l.trigger(E.ERROR,{type:Z.NETWORK_ERROR,details:D.LEVEL_EMPTY_ERROR,fatal:!1,url:v,error:f,reason:f.message,response:t,context:n,level:o,parent:_,networkDetails:a,stats:s});return}switch(e.live&&h&&(h.getCacheAge&&(e.ageHeader=h.getCacheAge()||0),(!h.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),u){case fe.MANIFEST:case fe.LEVEL:if(o){if(!p)o=0;else if(p!==l.levels[o]){const f=l.levels.indexOf(p);f>-1&&(o=f)}}l.trigger(E.LEVEL_LOADED,{details:e,levelInfo:p||l.levels[0],level:o||0,id:g||0,stats:s,networkDetails:a,deliveryDirectives:x,withoutMultiVariant:u===fe.MANIFEST});break;case fe.AUDIO_TRACK:l.trigger(E.AUDIO_TRACK_LOADED,{details:e,track:p,id:g||0,groupId:y||"",stats:s,networkDetails:a,deliveryDirectives:x});break;case fe.SUBTITLE_TRACK:l.trigger(E.SUBTITLE_TRACK_LOADED,{details:e,track:p,id:g||0,groupId:y||"",stats:s,networkDetails:a,deliveryDirectives:x});break}}}class Qt{static get version(){return Vs}static isMSESupported(){return Mu()}static isSupported(){return _S()}static getMediaSource(){return Si()}static get Events(){return E}static get MetadataSchema(){return ct}static get ErrorTypes(){return Z}static get ErrorDetails(){return D}static get DefaultConfig(){return Qt.defaultConfig?Qt.defaultConfig:hS}static set DefaultConfig(e){Qt.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Bo,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=D0(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=dS(Qt.DefaultConfig,e,t);this.userConfig=e,s.progressive&&uS(s,t);const{abrController:n,bufferController:a,capLevelController:h,errorController:l,fpsController:u}=s,d=new l(this),p=this.abrController=new n(this),g=new wm(this),y=s.interstitialsController,x=y?this.interstitialsController=new y(this,Qt):null,v=this.bufferController=new a(this,g),_=this.capLevelController=new h(this),o=new u(this),c=new IS(this),f=s.contentSteeringController,m=f?new f(this):null,S=this.levelController=new SS(this,m),T=new vS(this),b=new AS(this.config,this.logger),A=this.streamController=new bS(this,g,b),I=this.gapController=new mS(this,g);_.setStreamController(A),o.setStreamController(A);const L=[c,S,A];x&&L.splice(1,0,x),m&&L.splice(1,0,m),this.networkControllers=L;const w=[p,v,I,_,o,T,g];this.audioTrackController=this.createController(s.audioTrackController,L);const R=s.audioStreamController;R&&L.push(this.audioStreamController=new R(this,g,b)),this.subtitleTrackController=this.createController(s.subtitleTrackController,L);const M=s.subtitleStreamController;M&&L.push(this.subtititleStreamController=new M(this,g,b)),this.createController(s.timelineController,w),b.emeController=this.emeController=this.createController(s.emeController,w),this.cmcdController=this.createController(s.cmcdController,w),this.latencyController=this.createController(xS,w),this.coreComponents=w,L.push(d);const k=d.onErrorOut;typeof k=="function"&&this.on(E.ERROR,k,d),this.on(E.MANIFEST_LOADED,c.onManifestLoaded,c)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,n){this._emitter.off(e,t,s,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const n=e===E.ERROR;this.trigger(E.ERROR,{type:Z.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:n,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(E.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const a=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(E.ERROR,{type:Z.OTHER_ERROR,details:D.ATTACH_MEDIA_ERROR,fatal:!0,error:a});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,n=t?e:{media:s};this._media=s,this.trigger(E.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(E.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(E.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,n=this._url=wo.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),t&&s&&(s!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(E.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[X.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[X.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[X.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=mx()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){dm(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let n=0;n<s;n++)if(e[n].maxBitrate>=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let n;if(t===-1&&e!=null&&e.length?n=e.length-1:n=t,s)for(let a=n;a--;){const h=e[a].attrs["HDCP-LEVEL"];if(h&&h<=s)return a}return n}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const s=Sd(t);return vd(e,s,navigator.mediaCapabilities)}}Qt.defaultConfig=void 0;var or={};(function(r){var e=function(){var o=new Date,c=4,f=3,m=2,S=1,T=c,b={setLogLevel:function(A){A==this.debug?T=S:A==this.info?T=m:A==this.warn?T=f:(A==this.error,T=c)},debug:function(A,I){console.debug===void 0&&(console.debug=console.log),S>=T&&console.debug("["+e.getDurationString(new Date-o,1e3)+"]","["+A+"]",I)},log:function(A,I){this.debug(A.msg)},info:function(A,I){m>=T&&console.info("["+e.getDurationString(new Date-o,1e3)+"]","["+A+"]",I)},warn:function(A,I){f>=T&&console.warn("["+e.getDurationString(new Date-o,1e3)+"]","["+A+"]",I)},error:function(A,I){c>=T&&console.error("["+e.getDurationString(new Date-o,1e3)+"]","["+A+"]",I)}};return b}();e.getDurationString=function(o,c){var f;function m(L,w){for(var R=""+L,M=R.split(".");M[0].length<w;)M[0]="0"+M[0];return M.join(".")}o<0?(f=!0,o=-o):f=!1;var S=c||1,T=o/S,b=Math.floor(T/3600);T-=b*3600;var A=Math.floor(T/60);T-=A*60;var I=T*1e3;return T=Math.floor(T),I-=T*1e3,I=Math.floor(I),(f?"-":"")+b+":"+m(A,2)+":"+m(T,2)+"."+m(I,3)},e.printRanges=function(o){var c=o.length;if(c>0){for(var f="",m=0;m<c;m++)m>0&&(f+=","),f+="["+e.getDurationString(o.start(m))+","+e.getDurationString(o.end(m))+"]";return f}else return"(empty)"},r.Log=e;var t=function(o){if(o instanceof ArrayBuffer)this.buffer=o,this.dataview=new DataView(o);else throw"Needs an array buffer";this.position=0};t.prototype.getPosition=function(){return this.position},t.prototype.getEndPosition=function(){return this.buffer.byteLength},t.prototype.getLength=function(){return this.buffer.byteLength},t.prototype.seek=function(o){var c=Math.max(0,Math.min(this.buffer.byteLength,o));return this.position=isNaN(c)||!isFinite(c)?0:c,!0},t.prototype.isEos=function(){return this.getPosition()>=this.getEndPosition()},t.prototype.readAnyInt=function(o,c){var f=0;if(this.position+o<=this.buffer.byteLength){switch(o){case 1:c?f=this.dataview.getInt8(this.position):f=this.dataview.getUint8(this.position);break;case 2:c?f=this.dataview.getInt16(this.position):f=this.dataview.getUint16(this.position);break;case 3:if(c)throw"No method for reading signed 24 bits values";f=this.dataview.getUint8(this.position)<<16,f|=this.dataview.getUint8(this.position+1)<<8,f|=this.dataview.getUint8(this.position+2);break;case 4:c?f=this.dataview.getInt32(this.position):f=this.dataview.getUint32(this.position);break;case 8:if(c)throw"No method for reading signed 64 bits values";f=this.dataview.getUint32(this.position)<<32,f|=this.dataview.getUint32(this.position+4);break;default:throw"readInt method not implemented for size: "+o}return this.position+=o,f}else throw"Not enough bytes in buffer"},t.prototype.readUint8=function(){return this.readAnyInt(1,!1)},t.prototype.readUint16=function(){return this.readAnyInt(2,!1)},t.prototype.readUint24=function(){return this.readAnyInt(3,!1)},t.prototype.readUint32=function(){return this.readAnyInt(4,!1)},t.prototype.readUint64=function(){return this.readAnyInt(8,!1)},t.prototype.readString=function(o){if(this.position+o<=this.buffer.byteLength){for(var c="",f=0;f<o;f++)c+=String.fromCharCode(this.readUint8());return c}else throw"Not enough bytes in buffer"},t.prototype.readCString=function(){for(var o=[];;){var c=this.readUint8();if(c!==0)o.push(c);else break}return String.fromCharCode.apply(null,o)},t.prototype.readInt8=function(){return this.readAnyInt(1,!0)},t.prototype.readInt16=function(){return this.readAnyInt(2,!0)},t.prototype.readInt32=function(){return this.readAnyInt(4,!0)},t.prototype.readInt64=function(){return this.readAnyInt(8,!1)},t.prototype.readUint8Array=function(o){for(var c=new Uint8Array(o),f=0;f<o;f++)c[f]=this.readUint8();return c},t.prototype.readInt16Array=function(o){for(var c=new Int16Array(o),f=0;f<o;f++)c[f]=this.readInt16();return c},t.prototype.readUint16Array=function(o){for(var c=new Int16Array(o),f=0;f<o;f++)c[f]=this.readUint16();return c},t.prototype.readUint32Array=function(o){for(var c=new Uint32Array(o),f=0;f<o;f++)c[f]=this.readUint32();return c},t.prototype.readInt32Array=function(o){for(var c=new Int32Array(o),f=0;f<o;f++)c[f]=this.readInt32();return c},r.MP4BoxStream=t;var s=function(o,c,f){this._byteOffset=c||0,o instanceof ArrayBuffer?this.buffer=o:typeof o=="object"?(this.dataView=o,c&&(this._byteOffset+=c)):this.buffer=new ArrayBuffer(o||0),this.position=0,this.endianness=f??s.LITTLE_ENDIAN};s.prototype={},s.prototype.getPosition=function(){return this.position},s.prototype._realloc=function(o){if(this._dynamicSize){var c=this._byteOffset+this.position+o,f=this._buffer.byteLength;if(c<=f){c>this._byteLength&&(this._byteLength=c);return}for(f<1&&(f=1);c>f;)f*=2;var m=new ArrayBuffer(f),S=new Uint8Array(this._buffer),T=new Uint8Array(m,0,S.length);T.set(S),this.buffer=m,this._byteLength=c}},s.prototype._trimAlloc=function(){if(this._byteLength!=this._buffer.byteLength){var o=new ArrayBuffer(this._byteLength),c=new Uint8Array(o),f=new Uint8Array(this._buffer,0,c.length);c.set(f),this.buffer=o}},s.BIG_ENDIAN=!1,s.LITTLE_ENDIAN=!0,s.prototype._byteLength=0,Object.defineProperty(s.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}}),Object.defineProperty(s.prototype,"buffer",{get:function(){return this._trimAlloc(),this._buffer},set:function(o){this._buffer=o,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(s.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(o){this._byteOffset=o,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(s.prototype,"dataView",{get:function(){return this._dataView},set:function(o){this._byteOffset=o.byteOffset,this._buffer=o.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+o.byteLength}}),s.prototype.seek=function(o){var c=Math.max(0,Math.min(this.byteLength,o));this.position=isNaN(c)||!isFinite(c)?0:c},s.prototype.isEof=function(){return this.position>=this._byteLength},s.prototype.mapUint8Array=function(o){this._realloc(o*1);var c=new Uint8Array(this._buffer,this.byteOffset+this.position,o);return this.position+=o*1,c},s.prototype.readInt32Array=function(o,c){o=o??this.byteLength-this.position/4;var f=new Int32Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readInt16Array=function(o,c){o=o??this.byteLength-this.position/2;var f=new Int16Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readInt8Array=function(o){o=o??this.byteLength-this.position;var c=new Int8Array(o);return s.memcpy(c.buffer,0,this.buffer,this.byteOffset+this.position,o*c.BYTES_PER_ELEMENT),this.position+=c.byteLength,c},s.prototype.readUint32Array=function(o,c){o=o??this.byteLength-this.position/4;var f=new Uint32Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readUint16Array=function(o,c){o=o??this.byteLength-this.position/2;var f=new Uint16Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readUint8Array=function(o){o=o??this.byteLength-this.position;var c=new Uint8Array(o);return s.memcpy(c.buffer,0,this.buffer,this.byteOffset+this.position,o*c.BYTES_PER_ELEMENT),this.position+=c.byteLength,c},s.prototype.readFloat64Array=function(o,c){o=o??this.byteLength-this.position/8;var f=new Float64Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readFloat32Array=function(o,c){o=o??this.byteLength-this.position/4;var f=new Float32Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readInt32=function(o){var c=this._dataView.getInt32(this.position,o??this.endianness);return this.position+=4,c},s.prototype.readInt16=function(o){var c=this._dataView.getInt16(this.position,o??this.endianness);return this.position+=2,c},s.prototype.readInt8=function(){var o=this._dataView.getInt8(this.position);return this.position+=1,o},s.prototype.readUint32=function(o){var c=this._dataView.getUint32(this.position,o??this.endianness);return this.position+=4,c},s.prototype.readUint16=function(o){var c=this._dataView.getUint16(this.position,o??this.endianness);return this.position+=2,c},s.prototype.readUint8=function(){var o=this._dataView.getUint8(this.position);return this.position+=1,o},s.prototype.readFloat32=function(o){var c=this._dataView.getFloat32(this.position,o??this.endianness);return this.position+=4,c},s.prototype.readFloat64=function(o){var c=this._dataView.getFloat64(this.position,o??this.endianness);return this.position+=8,c},s.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>0,s.memcpy=function(o,c,f,m,S){var T=new Uint8Array(o,c,S),b=new Uint8Array(f,m,S);T.set(b)},s.arrayToNative=function(o,c){return c==this.endianness?o:this.flipArrayEndianness(o)},s.nativeToEndian=function(o,c){return this.endianness==c?o:this.flipArrayEndianness(o)},s.flipArrayEndianness=function(o){for(var c=new Uint8Array(o.buffer,o.byteOffset,o.byteLength),f=0;f<o.byteLength;f+=o.BYTES_PER_ELEMENT)for(var m=f+o.BYTES_PER_ELEMENT-1,S=f;m>S;m--,S++){var T=c[S];c[S]=c[m],c[m]=T}return o},s.prototype.failurePosition=0,String.fromCharCodeUint8=function(o){for(var c=[],f=0;f<o.length;f++)c[f]=o[f];return String.fromCharCode.apply(null,c)},s.prototype.readString=function(o,c){return c==null||c=="ASCII"?String.fromCharCodeUint8.apply(null,[this.mapUint8Array(o??this.byteLength-this.position)]):new TextDecoder(c).decode(this.mapUint8Array(o))},s.prototype.readCString=function(o){var c=this.byteLength-this.position,f=new Uint8Array(this._buffer,this._byteOffset+this.position),m=c;o!=null&&(m=Math.min(o,c));for(var S=0;S<m&&f[S]!==0;S++);var T=String.fromCharCodeUint8.apply(null,[this.mapUint8Array(S)]);return o!=null?this.position+=m-S:S!=c&&(this.position+=1),T};var n=Math.pow(2,32);s.prototype.readInt64=function(){return this.readInt32()*n+this.readUint32()},s.prototype.readUint64=function(){return this.readUint32()*n+this.readUint32()},s.prototype.readInt64=function(){return this.readUint32()*n+this.readUint32()},s.prototype.readUint24=function(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()},r.DataStream=s,s.prototype.save=function(o){var c=new Blob([this.buffer]);if(window.URL&&URL.createObjectURL){var f=window.URL.createObjectURL(c),m=document.createElement("a");document.body.appendChild(m),m.setAttribute("href",f),m.setAttribute("download",o),m.setAttribute("target","_self"),m.click(),window.URL.revokeObjectURL(f)}else throw"DataStream.save: Can't create object URL."},s.prototype._dynamicSize=!0,Object.defineProperty(s.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(o){o||this._trimAlloc(),this._dynamicSize=o}}),s.prototype.shift=function(o){var c=new ArrayBuffer(this._byteLength-o),f=new Uint8Array(c),m=new Uint8Array(this._buffer,o,f.length);f.set(m),this.buffer=c,this.position-=o},s.prototype.writeInt32Array=function(o,c){if(this._realloc(o.length*4),o instanceof Int32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt32Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeInt32(o[f],c)},s.prototype.writeInt16Array=function(o,c){if(this._realloc(o.length*2),o instanceof Int16Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt16Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeInt16(o[f],c)},s.prototype.writeInt8Array=function(o){if(this._realloc(o.length*1),o instanceof Int8Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt8Array(o.length);else for(var c=0;c<o.length;c++)this.writeInt8(o[c])},s.prototype.writeUint32Array=function(o,c){if(this._realloc(o.length*4),o instanceof Uint32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint32Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeUint32(o[f],c)},s.prototype.writeUint16Array=function(o,c){if(this._realloc(o.length*2),o instanceof Uint16Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint16Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeUint16(o[f],c)},s.prototype.writeUint8Array=function(o){if(this._realloc(o.length*1),o instanceof Uint8Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint8Array(o.length);else for(var c=0;c<o.length;c++)this.writeUint8(o[c])},s.prototype.writeFloat64Array=function(o,c){if(this._realloc(o.length*8),o instanceof Float64Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapFloat64Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeFloat64(o[f],c)},s.prototype.writeFloat32Array=function(o,c){if(this._realloc(o.length*4),o instanceof Float32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapFloat32Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeFloat32(o[f],c)},s.prototype.writeInt32=function(o,c){this._realloc(4),this._dataView.setInt32(this.position,o,c??this.endianness),this.position+=4},s.prototype.writeInt16=function(o,c){this._realloc(2),this._dataView.setInt16(this.position,o,c??this.endianness),this.position+=2},s.prototype.writeInt8=function(o){this._realloc(1),this._dataView.setInt8(this.position,o),this.position+=1},s.prototype.writeUint32=function(o,c){this._realloc(4),this._dataView.setUint32(this.position,o,c??this.endianness),this.position+=4},s.prototype.writeUint16=function(o,c){this._realloc(2),this._dataView.setUint16(this.position,o,c??this.endianness),this.position+=2},s.prototype.writeUint8=function(o){this._realloc(1),this._dataView.setUint8(this.position,o),this.position+=1},s.prototype.writeFloat32=function(o,c){this._realloc(4),this._dataView.setFloat32(this.position,o,c??this.endianness),this.position+=4},s.prototype.writeFloat64=function(o,c){this._realloc(8),this._dataView.setFloat64(this.position,o,c??this.endianness),this.position+=8},s.prototype.writeUCS2String=function(o,c,f){f==null&&(f=o.length);for(var m=0;m<o.length&&m<f;m++)this.writeUint16(o.charCodeAt(m),c);for(;m<f;m++)this.writeUint16(0)},s.prototype.writeString=function(o,c,f){var m=0;if(c==null||c=="ASCII")if(f!=null){var S=Math.min(o.length,f);for(m=0;m<S;m++)this.writeUint8(o.charCodeAt(m));for(;m<f;m++)this.writeUint8(0)}else for(m=0;m<o.length;m++)this.writeUint8(o.charCodeAt(m));else this.writeUint8Array(new TextEncoder(c).encode(o.substring(0,f)))},s.prototype.writeCString=function(o,c){var f=0;if(c!=null){var m=Math.min(o.length,c);for(f=0;f<m;f++)this.writeUint8(o.charCodeAt(f));for(;f<c;f++)this.writeUint8(0)}else{for(f=0;f<o.length;f++)this.writeUint8(o.charCodeAt(f));this.writeUint8(0)}},s.prototype.writeStruct=function(o,c){for(var f=0;f<o.length;f+=2){var m=o[f+1];this.writeType(m,c[o[f]],c)}},s.prototype.writeType=function(o,c,f){var m;if(typeof o=="function")return o(this,c);if(typeof o=="object"&&!(o instanceof Array))return o.set(this,c,f);var S=null,T="ASCII",b=this.position;switch(typeof o=="string"&&/:/.test(o)&&(m=o.split(":"),o=m[0],S=parseInt(m[1])),typeof o=="string"&&/,/.test(o)&&(m=o.split(","),o=m[0],T=parseInt(m[1])),o){case"uint8":this.writeUint8(c);break;case"int8":this.writeInt8(c);break;case"uint16":this.writeUint16(c,this.endianness);break;case"int16":this.writeInt16(c,this.endianness);break;case"uint32":this.writeUint32(c,this.endianness);break;case"int32":this.writeInt32(c,this.endianness);break;case"float32":this.writeFloat32(c,this.endianness);break;case"float64":this.writeFloat64(c,this.endianness);break;case"uint16be":this.writeUint16(c,s.BIG_ENDIAN);break;case"int16be":this.writeInt16(c,s.BIG_ENDIAN);break;case"uint32be":this.writeUint32(c,s.BIG_ENDIAN);break;case"int32be":this.writeInt32(c,s.BIG_ENDIAN);break;case"float32be":this.writeFloat32(c,s.BIG_ENDIAN);break;case"float64be":this.writeFloat64(c,s.BIG_ENDIAN);break;case"uint16le":this.writeUint16(c,s.LITTLE_ENDIAN);break;case"int16le":this.writeInt16(c,s.LITTLE_ENDIAN);break;case"uint32le":this.writeUint32(c,s.LITTLE_ENDIAN);break;case"int32le":this.writeInt32(c,s.LITTLE_ENDIAN);break;case"float32le":this.writeFloat32(c,s.LITTLE_ENDIAN);break;case"float64le":this.writeFloat64(c,s.LITTLE_ENDIAN);break;case"cstring":this.writeCString(c,S);break;case"string":this.writeString(c,T,S);break;case"u16string":this.writeUCS2String(c,this.endianness,S);break;case"u16stringle":this.writeUCS2String(c,s.LITTLE_ENDIAN,S);break;case"u16stringbe":this.writeUCS2String(c,s.BIG_ENDIAN,S);break;default:if(o.length==3){for(var A=o[1],I=0;I<c.length;I++)this.writeType(A,c[I]);break}else{this.writeStruct(o,c);break}}S!=null&&(this.position=b,this._realloc(S),this.position=b+S)},s.prototype.writeUint64=function(o){var c=Math.floor(o/n);this.writeUint32(c),this.writeUint32(o&4294967295)},s.prototype.writeUint24=function(o){this.writeUint8((o&16711680)>>16),this.writeUint8((o&65280)>>8),this.writeUint8(o&255)},s.prototype.adjustUint32=function(o,c){var f=this.position;this.seek(o),this.writeUint32(c),this.seek(f)},s.prototype.mapInt32Array=function(o,c){this._realloc(o*4);var f=new Int32Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*4,f},s.prototype.mapInt16Array=function(o,c){this._realloc(o*2);var f=new Int16Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*2,f},s.prototype.mapInt8Array=function(o){this._realloc(o*1);var c=new Int8Array(this._buffer,this.byteOffset+this.position,o);return this.position+=o*1,c},s.prototype.mapUint32Array=function(o,c){this._realloc(o*4);var f=new Uint32Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*4,f},s.prototype.mapUint16Array=function(o,c){this._realloc(o*2);var f=new Uint16Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*2,f},s.prototype.mapFloat64Array=function(o,c){this._realloc(o*8);var f=new Float64Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*8,f},s.prototype.mapFloat32Array=function(o,c){this._realloc(o*4);var f=new Float32Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*4,f};var a=function(o){this.buffers=[],this.bufferIndex=-1,o&&(this.insertBuffer(o),this.bufferIndex=0)};a.prototype=new s(new ArrayBuffer,0,s.BIG_ENDIAN),a.prototype.initialized=function(){var o;return this.bufferIndex>-1?!0:this.buffers.length>0?(o=this.buffers[0],o.fileStart===0?(this.buffer=o,this.bufferIndex=0,e.debug("MultiBufferStream","Stream ready for parsing"),!0):(e.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1)):(e.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1)},ArrayBuffer.concat=function(o,c){e.debug("ArrayBuffer","Trying to create a new buffer of size: "+(o.byteLength+c.byteLength));var f=new Uint8Array(o.byteLength+c.byteLength);return f.set(new Uint8Array(o),0),f.set(new Uint8Array(c),o.byteLength),f.buffer},a.prototype.reduceBuffer=function(o,c,f){var m;return m=new Uint8Array(f),m.set(new Uint8Array(o,c,f)),m.buffer.fileStart=o.fileStart+c,m.buffer.usedBytes=0,m.buffer},a.prototype.insertBuffer=function(o){for(var c=!0,f=0;f<this.buffers.length;f++){var m=this.buffers[f];if(o.fileStart<=m.fileStart){if(o.fileStart===m.fileStart)if(o.byteLength>m.byteLength){this.buffers.splice(f,1),f--;continue}else e.warn("MultiBufferStream","Buffer (fileStart: "+o.fileStart+" - Length: "+o.byteLength+") already appended, ignoring");else o.fileStart+o.byteLength<=m.fileStart||(o=this.reduceBuffer(o,0,m.fileStart-o.fileStart)),e.debug("MultiBufferStream","Appending new buffer (fileStart: "+o.fileStart+" - Length: "+o.byteLength+")"),this.buffers.splice(f,0,o),f===0&&(this.buffer=o);c=!1;break}else if(o.fileStart<m.fileStart+m.byteLength){var S=m.fileStart+m.byteLength-o.fileStart,T=o.byteLength-S;if(T>0)o=this.reduceBuffer(o,S,T);else{c=!1;break}}}c&&(e.debug("MultiBufferStream","Appending new buffer (fileStart: "+o.fileStart+" - Length: "+o.byteLength+")"),this.buffers.push(o),f===0&&(this.buffer=o))},a.prototype.logBufferLevel=function(o){var c,f,m,S,T=[],b,A="";for(m=0,S=0,c=0;c<this.buffers.length;c++)f=this.buffers[c],c===0?(b={},T.push(b),b.start=f.fileStart,b.end=f.fileStart+f.byteLength,A+="["+b.start+"-"):b.end===f.fileStart?b.end=f.fileStart+f.byteLength:(b={},b.start=f.fileStart,A+=T[T.length-1].end-1+"], ["+b.start+"-",b.end=f.fileStart+f.byteLength,T.push(b)),m+=f.usedBytes,S+=f.byteLength;T.length>0&&(A+=b.end-1+"]");var I=o?e.info:e.debug;this.buffers.length===0?I("MultiBufferStream","No more buffer in memory"):I("MultiBufferStream",""+this.buffers.length+" stored buffer(s) ("+m+"/"+S+" bytes), continuous ranges: "+A)},a.prototype.cleanBuffers=function(){var o,c;for(o=0;o<this.buffers.length;o++)c=this.buffers[o],c.usedBytes===c.byteLength&&(e.debug("MultiBufferStream","Removing buffer #"+o),this.buffers.splice(o,1),o--)},a.prototype.mergeNextBuffer=function(){var o;if(this.bufferIndex+1<this.buffers.length)if(o=this.buffers[this.bufferIndex+1],o.fileStart===this.buffer.fileStart+this.buffer.byteLength){var c=this.buffer.byteLength,f=this.buffer.usedBytes,m=this.buffer.fileStart;return this.buffers[this.bufferIndex]=ArrayBuffer.concat(this.buffer,o),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=f,this.buffer.fileStart=m,e.debug("ISOFile","Concatenating buffer for box parsing (length: "+c+"->"+this.buffer.byteLength+")"),!0}else return!1;else return!1},a.prototype.findPosition=function(o,c,f){var m,S=null,T=-1;for(o===!0?m=0:m=this.bufferIndex;m<this.buffers.length&&(S=this.buffers[m],S.fileStart<=c);){T=m,f&&(S.fileStart+S.byteLength<=c?S.usedBytes=S.byteLength:S.usedBytes=c-S.fileStart,this.logBufferLevel());m++}return T!==-1?(S=this.buffers[T],S.fileStart+S.byteLength>=c?(e.debug("MultiBufferStream","Found position in existing buffer #"+T),T):-1):-1},a.prototype.findEndContiguousBuf=function(o){var c,f,m,S=o!==void 0?o:this.bufferIndex;if(f=this.buffers[S],this.buffers.length>S+1)for(c=S+1;c<this.buffers.length&&(m=this.buffers[c],m.fileStart===f.fileStart+f.byteLength);c++)f=m;return f.fileStart+f.byteLength},a.prototype.getEndFilePositionAfter=function(o){var c=this.findPosition(!0,o,!1);return c!==-1?this.findEndContiguousBuf(c):o},a.prototype.addUsedBytes=function(o){this.buffer.usedBytes+=o,this.logBufferLevel()},a.prototype.setAllUsedBytes=function(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()},a.prototype.seek=function(o,c,f){var m;return m=this.findPosition(c,o,f),m!==-1?(this.buffer=this.buffers[m],this.bufferIndex=m,this.position=o-this.buffer.fileStart,e.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(e.debug("MultiBufferStream","Position "+o+" not found in buffered data"),!1)},a.prototype.getPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.position},a.prototype.getLength=function(){return this.byteLength},a.prototype.getEndPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.byteLength},r.MultiBufferStream=a;var h=function(){var o=3,c=4,f=5,m=6,S=[];S[o]="ES_Descriptor",S[c]="DecoderConfigDescriptor",S[f]="DecoderSpecificInfo",S[m]="SLConfigDescriptor",this.getDescriptorName=function(A){return S[A]};var T=this,b={};return this.parseOneDescriptor=function(A){var I=0,L,w,R;for(L=A.readUint8(),R=A.readUint8();R&128;)I=(I<<7)+(R&127),R=A.readUint8();return I=(I<<7)+(R&127),e.debug("MPEG4DescriptorParser","Found "+(S[L]||"Descriptor "+L)+", size "+I+" at position "+A.getPosition()),S[L]?w=new b[S[L]](I):w=new b.Descriptor(I),w.parse(A),w},b.Descriptor=function(A,I){this.tag=A,this.size=I,this.descs=[]},b.Descriptor.prototype.parse=function(A){this.data=A.readUint8Array(this.size)},b.Descriptor.prototype.findDescriptor=function(A){for(var I=0;I<this.descs.length;I++)if(this.descs[I].tag==A)return this.descs[I];return null},b.Descriptor.prototype.parseRemainingDescriptors=function(A){for(var I=A.position;A.position<I+this.size;){var L=T.parseOneDescriptor(A);this.descs.push(L)}},b.ES_Descriptor=function(A){b.Descriptor.call(this,o,A)},b.ES_Descriptor.prototype=new b.Descriptor,b.ES_Descriptor.prototype.parse=function(A){if(this.ES_ID=A.readUint16(),this.flags=A.readUint8(),this.size-=3,this.flags&128?(this.dependsOn_ES_ID=A.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,this.flags&64){var I=A.readUint8();this.URL=A.readString(I),this.size-=I+1}else this.URL="";this.flags&32?(this.OCR_ES_ID=A.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(A)},b.ES_Descriptor.prototype.getOTI=function(A){var I=this.findDescriptor(c);return I?I.oti:0},b.ES_Descriptor.prototype.getAudioConfig=function(A){var I=this.findDescriptor(c);if(!I)return null;var L=I.findDescriptor(f);if(L&&L.data){var w=(L.data[0]&248)>>3;return w===31&&L.data.length>=2&&(w=32+((L.data[0]&7)<<3)+((L.data[1]&224)>>5)),w}else return null},b.DecoderConfigDescriptor=function(A){b.Descriptor.call(this,c,A)},b.DecoderConfigDescriptor.prototype=new b.Descriptor,b.DecoderConfigDescriptor.prototype.parse=function(A){this.oti=A.readUint8(),this.streamType=A.readUint8(),this.upStream=(this.streamType>>1&1)!==0,this.streamType=this.streamType>>>2,this.bufferSize=A.readUint24(),this.maxBitrate=A.readUint32(),this.avgBitrate=A.readUint32(),this.size-=13,this.parseRemainingDescriptors(A)},b.DecoderSpecificInfo=function(A){b.Descriptor.call(this,f,A)},b.DecoderSpecificInfo.prototype=new b.Descriptor,b.SLConfigDescriptor=function(A){b.Descriptor.call(this,m,A)},b.SLConfigDescriptor.prototype=new b.Descriptor,this};r.MPEG4DescriptorParser=h;var l={ERR_INVALID_DATA:-1,ERR_NOT_ENOUGH_DATA:0,OK:1,BASIC_BOXES:[{type:"mdat",name:"MediaDataBox"},{type:"idat",name:"ItemDataBox"},{type:"free",name:"FreeSpaceBox"},{type:"skip",name:"FreeSpaceBox"},{type:"meco",name:"AdditionalMetadataContainerBox"},{type:"strk",name:"SubTrackBox"}],FULL_BOXES:[{type:"hmhd",name:"HintMediaHeaderBox"},{type:"nmhd",name:"NullMediaHeaderBox"},{type:"iods",name:"ObjectDescriptorBox"},{type:"xml ",name:"XMLBox"},{type:"bxml",name:"BinaryXMLBox"},{type:"ipro",name:"ItemProtectionBox"},{type:"mere",name:"MetaboxRelationBox"}],CONTAINER_BOXES:[[{type:"moov",name:"CompressedMovieBox"},["trak","pssh"]],[{type:"trak",name:"TrackBox"}],[{type:"edts",name:"EditBox"}],[{type:"mdia",name:"MediaBox"}],[{type:"minf",name:"MediaInformationBox"}],[{type:"dinf",name:"DataInformationBox"}],[{type:"stbl",name:"SampleTableBox"},["sgpd","sbgp"]],[{type:"mvex",name:"MovieExtendsBox"},["trex"]],[{type:"moof",name:"CompressedMovieFragmentBox"},["traf"]],[{type:"traf",name:"TrackFragmentBox"},["trun","sgpd","sbgp"]],[{type:"vttc",name:"VTTCueBox"}],[{type:"tref",name:"TrackReferenceBox"}],[{type:"iref",name:"ItemReferenceBox"}],[{type:"mfra",name:"MovieFragmentRandomAccessBox"},["tfra"]],[{type:"meco",name:"AdditionalMetadataContainerBox"}],[{type:"hnti",name:"trackhintinformation"}],[{type:"hinf",name:"hintstatisticsbox"}],[{type:"strk",name:"SubTrackBox"}],[{type:"strd",name:"SubTrackDefinitionBox"}],[{type:"sinf",name:"ProtectionSchemeInfoBox"}],[{type:"rinf",name:"RestrictedSchemeInfoBox"}],[{type:"schi",name:"SchemeInformationBox"}],[{type:"trgr",name:"TrackGroupBox"}],[{type:"udta",name:"UserDataBox"},["kind"]],[{type:"iprp",name:"ItemPropertiesBox"},["ipma"]],[{type:"ipco",name:"ItemPropertyContainerBox"}],[{type:"grpl",name:"GroupsListBox"}],[{type:"j2kH",name:"J2KHeaderInfoBox"}],[{type:"etyp",name:"ExtendedTypeBox"},["tyco"]]],boxCodes:[],fullBoxCodes:[],containerBoxCodes:[],sampleEntryCodes:{},sampleGroupEntryCodes:[],trackGroupTypes:[],UUIDBoxes:{},UUIDs:[],initialize:function(){l.FullBox.prototype=new l.Box,l.ContainerBox.prototype=new l.Box,l.SampleEntry.prototype=new l.Box,l.TrackGroupTypeBox.prototype=new l.FullBox,l.BASIC_BOXES.forEach(function(o){l.createBoxCtor(o.type,o.name)}),l.FULL_BOXES.forEach(function(o){l.createFullBoxCtor(o.type,o.name)}),l.CONTAINER_BOXES.forEach(function(o){l.createContainerBoxCtor(o[0].type,o[0].name,null,o[1])})},Box:function(o,c,f,m){this.type=o,this.box_name=f,this.size=c,this.uuid=m},FullBox:function(o,c,f,m){l.Box.call(this,o,c,f,m),this.flags=0,this.version=0},ContainerBox:function(o,c,f,m){l.Box.call(this,o,c,f,m),this.boxes=[]},SampleEntry:function(o,c,f,m){l.ContainerBox.call(this,o,c),this.hdr_size=f,this.start=m},SampleGroupEntry:function(o){this.grouping_type=o},TrackGroupTypeBox:function(o,c){l.FullBox.call(this,o,c)},createBoxCtor:function(o,c,f){l.boxCodes.push(o),l[o+"Box"]=function(m){l.Box.call(this,o,m,c)},l[o+"Box"].prototype=new l.Box,f&&(l[o+"Box"].prototype.parse=f)},createFullBoxCtor:function(o,c,f){l[o+"Box"]=function(m){l.FullBox.call(this,o,m,c)},l[o+"Box"].prototype=new l.FullBox,l[o+"Box"].prototype.parse=function(m){this.parseFullHeader(m),f&&f.call(this,m)}},addSubBoxArrays:function(o){if(o){this.subBoxNames=o;for(var c=o.length,f=0;f<c;f++)this[o[f]+"s"]=[]}},createContainerBoxCtor:function(o,c,f,m){l[o+"Box"]=function(S){l.ContainerBox.call(this,o,S,c),l.addSubBoxArrays.call(this,m)},l[o+"Box"].prototype=new l.ContainerBox,f&&(l[o+"Box"].prototype.parse=f)},createMediaSampleEntryCtor:function(o,c,f){l.sampleEntryCodes[o]=[],l[o+"SampleEntry"]=function(m,S){l.SampleEntry.call(this,m,S),l.addSubBoxArrays.call(this,f)},l[o+"SampleEntry"].prototype=new l.SampleEntry,c&&(l[o+"SampleEntry"].prototype.parse=c)},createSampleEntryCtor:function(o,c,f,m){l.sampleEntryCodes[o].push(c),l[c+"SampleEntry"]=function(S){l[o+"SampleEntry"].call(this,c,S),l.addSubBoxArrays.call(this,m)},l[c+"SampleEntry"].prototype=new l[o+"SampleEntry"],f&&(l[c+"SampleEntry"].prototype.parse=f)},createEncryptedSampleEntryCtor:function(o,c,f){l.createSampleEntryCtor.call(this,o,c,f,["sinf"])},createSampleGroupCtor:function(o,c){l[o+"SampleGroupEntry"]=function(f){l.SampleGroupEntry.call(this,o,f)},l[o+"SampleGroupEntry"].prototype=new l.SampleGroupEntry,c&&(l[o+"SampleGroupEntry"].prototype.parse=c)},createTrackGroupCtor:function(o,c){l[o+"TrackGroupTypeBox"]=function(f){l.TrackGroupTypeBox.call(this,o,f)},l[o+"TrackGroupTypeBox"].prototype=new l.TrackGroupTypeBox,c&&(l[o+"TrackGroupTypeBox"].prototype.parse=c)},createUUIDBox:function(o,c,f,m,S){l.UUIDs.push(o),l.UUIDBoxes[o]=function(T){f?l.FullBox.call(this,"uuid",T,c,o):m?l.ContainerBox.call(this,"uuid",T,c,o):l.Box.call(this,"uuid",T,c,o)},l.UUIDBoxes[o].prototype=f?new l.FullBox:m?new l.ContainerBox:new l.Box,S&&(f?l.UUIDBoxes[o].prototype.parse=function(T){this.parseFullHeader(T),S&&S.call(this,T)}:l.UUIDBoxes[o].prototype.parse=S)}};l.initialize(),l.TKHD_FLAG_ENABLED=1,l.TKHD_FLAG_IN_MOVIE=2,l.TKHD_FLAG_IN_PREVIEW=4,l.TFHD_FLAG_BASE_DATA_OFFSET=1,l.TFHD_FLAG_SAMPLE_DESC=2,l.TFHD_FLAG_SAMPLE_DUR=8,l.TFHD_FLAG_SAMPLE_SIZE=16,l.TFHD_FLAG_SAMPLE_FLAGS=32,l.TFHD_FLAG_DUR_EMPTY=65536,l.TFHD_FLAG_DEFAULT_BASE_IS_MOOF=131072,l.TRUN_FLAGS_DATA_OFFSET=1,l.TRUN_FLAGS_FIRST_FLAG=4,l.TRUN_FLAGS_DURATION=256,l.TRUN_FLAGS_SIZE=512,l.TRUN_FLAGS_FLAGS=1024,l.TRUN_FLAGS_CTS_OFFSET=2048,l.Box.prototype.add=function(o){return this.addBox(new l[o+"Box"])},l.Box.prototype.addBox=function(o){return this.boxes.push(o),this[o.type+"s"]?this[o.type+"s"].push(o):this[o.type]=o,o},l.Box.prototype.set=function(o,c){return this[o]=c,this},l.Box.prototype.addEntry=function(o,c){var f=c||"entries";return this[f]||(this[f]=[]),this[f].push(o),this},r.BoxParser=l,l.parseUUID=function(o){return l.parseHex16(o)},l.parseHex16=function(o){for(var c="",f=0;f<16;f++){var m=o.readUint8().toString(16);c+=m.length===1?"0"+m:m}return c},l.parseOneBox=function(o,c,f){var m,S=o.getPosition(),T=0,b,A;if(o.getEndPosition()-S<8)return e.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:l.ERR_NOT_ENOUGH_DATA};if(f&&f<8)return e.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:l.ERR_NOT_ENOUGH_DATA};var I=o.readUint32(),L=o.readString(4),w=L;if(e.debug("BoxParser","Found box of type '"+L+"' and size "+I+" at position "+S),T=8,L=="uuid"){if(o.getEndPosition()-o.getPosition()<16||f-T<16)return o.seek(S),e.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:l.ERR_NOT_ENOUGH_DATA};A=l.parseUUID(o),T+=16,w=A}if(I==1){if(o.getEndPosition()-o.getPosition()<8||f&&f-T<8)return o.seek(S),e.warn("BoxParser",'Not enough data in stream to parse the extended size of the "'+L+'" box'),{code:l.ERR_NOT_ENOUGH_DATA};I=o.readUint64(),T+=8}else if(I===0){if(f)I=f;else if(L!=="mdat")return e.error("BoxParser","Unlimited box size not supported for type: '"+L+"'"),m=new l.Box(L,I),{code:l.OK,box:m,size:m.size}}return I!==0&&I<T?(e.error("BoxParser","Box of type "+L+" has an invalid size "+I+" (too small to be a box)"),{code:l.ERR_NOT_ENOUGH_DATA,type:L,size:I,hdr_size:T,start:S}):I!==0&&f&&I>f?(e.error("BoxParser","Box of type '"+L+"' has a size "+I+" greater than its container size "+f),{code:l.ERR_NOT_ENOUGH_DATA,type:L,size:I,hdr_size:T,start:S}):I!==0&&S+I>o.getEndPosition()?(o.seek(S),e.info("BoxParser","Not enough data in stream to parse the entire '"+L+"' box"),{code:l.ERR_NOT_ENOUGH_DATA,type:L,size:I,hdr_size:T,start:S}):c?{code:l.OK,type:L,size:I,hdr_size:T,start:S}:(l[L+"Box"]?m=new l[L+"Box"](I):L!=="uuid"?(e.warn("BoxParser","Unknown box type: '"+L+"'"),m=new l.Box(L,I),m.has_unparsed_data=!0):l.UUIDBoxes[A]?m=new l.UUIDBoxes[A](I):(e.warn("BoxParser","Unknown uuid type: '"+A+"'"),m=new l.Box(L,I),m.uuid=A,m.has_unparsed_data=!0),m.hdr_size=T,m.start=S,m.write===l.Box.prototype.write&&m.type!=="mdat"&&(e.info("BoxParser","'"+w+"' box writing not yet implemented, keeping unparsed data in memory for later write"),m.parseDataAndRewind(o)),m.parse(o),b=o.getPosition()-(m.start+m.size),b<0?(e.warn("BoxParser","Parsing of box '"+w+"' did not read the entire indicated box data size (missing "+-b+" bytes), seeking forward"),o.seek(m.start+m.size)):b>0&&(e.error("BoxParser","Parsing of box '"+w+"' read "+b+" more bytes than the indicated box data size, seeking backwards"),m.size!==0&&o.seek(m.start+m.size)),{code:l.OK,box:m,size:m.size})},l.Box.prototype.parse=function(o){this.type!="mdat"?this.data=o.readUint8Array(this.size-this.hdr_size):this.size===0?o.seek(o.getEndPosition()):o.seek(this.start+this.size)},l.Box.prototype.parseDataAndRewind=function(o){this.data=o.readUint8Array(this.size-this.hdr_size),o.position-=this.size-this.hdr_size},l.FullBox.prototype.parseDataAndRewind=function(o){this.parseFullHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,o.position-=this.size-this.hdr_size},l.FullBox.prototype.parseFullHeader=function(o){this.version=o.readUint8(),this.flags=o.readUint24(),this.hdr_size+=4},l.FullBox.prototype.parse=function(o){this.parseFullHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size)},l.ContainerBox.prototype.parse=function(o){for(var c,f;o.getPosition()<this.start+this.size;)if(c=l.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),c.code===l.OK)if(f=c.box,this.boxes.push(f),this.subBoxNames&&this.subBoxNames.indexOf(f.type)!=-1)this[this.subBoxNames[this.subBoxNames.indexOf(f.type)]+"s"].push(f);else{var m=f.type!=="uuid"?f.type:f.uuid;this[m]?e.warn("Box of type "+m+" already stored in field of this type"):this[m]=f}else return},l.Box.prototype.parseLanguage=function(o){this.language=o.readUint16();var c=[];c[0]=this.language>>10&31,c[1]=this.language>>5&31,c[2]=this.language&31,this.languageString=String.fromCharCode(c[0]+96,c[1]+96,c[2]+96)},l.SAMPLE_ENTRY_TYPE_VISUAL="Visual",l.SAMPLE_ENTRY_TYPE_AUDIO="Audio",l.SAMPLE_ENTRY_TYPE_HINT="Hint",l.SAMPLE_ENTRY_TYPE_METADATA="Metadata",l.SAMPLE_ENTRY_TYPE_SUBTITLE="Subtitle",l.SAMPLE_ENTRY_TYPE_SYSTEM="System",l.SAMPLE_ENTRY_TYPE_TEXT="Text",l.SampleEntry.prototype.parseHeader=function(o){o.readUint8Array(6),this.data_reference_index=o.readUint16(),this.hdr_size+=8},l.SampleEntry.prototype.parse=function(o){this.parseHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size)},l.SampleEntry.prototype.parseDataAndRewind=function(o){this.parseHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,o.position-=this.size-this.hdr_size},l.SampleEntry.prototype.parseFooter=function(o){l.ContainerBox.prototype.parse.call(this,o)},l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_HINT),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_METADATA),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SYSTEM),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_TEXT),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,function(o){var c;this.parseHeader(o),o.readUint16(),o.readUint16(),o.readUint32Array(3),this.width=o.readUint16(),this.height=o.readUint16(),this.horizresolution=o.readUint32(),this.vertresolution=o.readUint32(),o.readUint32(),this.frame_count=o.readUint16(),c=Math.min(31,o.readUint8()),this.compressorname=o.readString(c),c<31&&o.readString(31-c),this.depth=o.readUint16(),o.readUint16(),this.parseFooter(o)}),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,function(o){this.parseHeader(o),o.readUint32Array(2),this.channel_count=o.readUint16(),this.samplesize=o.readUint16(),o.readUint16(),o.readUint16(),this.samplerate=o.readUint32()/65536,this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"avc1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"avc2"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"avc3"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"avc4"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"av01"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"dav1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"hvc1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"hev1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"hvt1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"lhe1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"dvh1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"dvhe"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vvc1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vvi1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vvs1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vvcN"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vp08"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vp09"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"avs3"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"j2ki"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"mjp2"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"mjpg"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"uncv"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"mp4a"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"ac-3"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"ac-4"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"ec-3"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"Opus"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"mha1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"mha2"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"mhm1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"mhm2"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"fLaC"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"encv"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"enca"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE,"encu"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SYSTEM,"encs"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_TEXT,"enct"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_METADATA,"encm"),l.createBoxCtor("a1lx","AV1LayeredImageIndexingProperty",function(o){var c=o.readUint8()&1,f=((c&1)+1)*16;this.layer_size=[];for(var m=0;m<3;m++)f==16?this.layer_size[m]=o.readUint16():this.layer_size[m]=o.readUint32()}),l.createBoxCtor("a1op","OperatingPointSelectorProperty",function(o){this.op_index=o.readUint8()}),l.createFullBoxCtor("auxC","AuxiliaryTypeProperty",function(o){this.aux_type=o.readCString();var c=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=o.readUint8Array(c)}),l.createBoxCtor("av1C","AV1CodecConfigurationBox",function(o){var c=o.readUint8();if((c>>7&1)!==1){e.error("av1C marker problem");return}if(this.version=c&127,this.version!==1){e.error("av1C version "+this.version+" not supported");return}if(c=o.readUint8(),this.seq_profile=c>>5&7,this.seq_level_idx_0=c&31,c=o.readUint8(),this.seq_tier_0=c>>7&1,this.high_bitdepth=c>>6&1,this.twelve_bit=c>>5&1,this.monochrome=c>>4&1,this.chroma_subsampling_x=c>>3&1,this.chroma_subsampling_y=c>>2&1,this.chroma_sample_position=c&3,c=o.readUint8(),this.reserved_1=c>>5&7,this.reserved_1!==0){e.error("av1C reserved_1 parsing problem");return}if(this.initial_presentation_delay_present=c>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=c&15;else if(this.reserved_2=c&15,this.reserved_2!==0){e.error("av1C reserved_2 parsing problem");return}var f=this.size-this.hdr_size-4;this.configOBUs=o.readUint8Array(f)});function u(o){var c="<table class='inner-table'>";c+="<thead><tr><th>length</th><th>nalu_data</th></tr></thead>",c+="<tbody>";for(var f=0;f<o.length;f++){var m=o[f];c+="<tr>",c+="<td>"+m.length+"</td>",c+="<td>",c+=m.nalu.reduce(function(S,T){return S+T.toString(16).padStart(2,"0")},"0x"),c+="</td></tr>"}return c+="</tbody></table>",c}l.createBoxCtor("avcC","AVCConfigurationBox",function(o){var c,f;for(this.configurationVersion=o.readUint8(),this.AVCProfileIndication=o.readUint8(),this.profile_compatibility=o.readUint8(),this.AVCLevelIndication=o.readUint8(),this.lengthSizeMinusOne=o.readUint8()&3,this.nb_SPS_nalus=o.readUint8()&31,f=this.size-this.hdr_size-6,this.SPS=[],this.SPS.toString=function(){return u(this)},c=0;c<this.nb_SPS_nalus;c++)this.SPS[c]={},this.SPS[c].length=o.readUint16(),this.SPS[c].nalu=o.readUint8Array(this.SPS[c].length),f-=2+this.SPS[c].length;for(this.nb_PPS_nalus=o.readUint8(),f--,this.PPS=[],this.PPS.toString=function(){return u(this)},c=0;c<this.nb_PPS_nalus;c++)this.PPS[c]={},this.PPS[c].length=o.readUint16(),this.PPS[c].nalu=o.readUint8Array(this.PPS[c].length),f-=2+this.PPS[c].length;f>0&&(this.ext=o.readUint8Array(f))}),l.createBoxCtor("btrt","BitRateBox",function(o){this.bufferSizeDB=o.readUint32(),this.maxBitrate=o.readUint32(),this.avgBitrate=o.readUint32()}),l.createFullBoxCtor("ccst","CodingConstraintsBox",function(o){var c=o.readUint8();this.all_ref_pics_intra=(c&128)==128,this.intra_pred_used=(c&64)==64,this.max_ref_per_pic=(c&63)>>2,o.readUint24()}),l.createBoxCtor("cdef","ComponentDefinitionBox",function(o){var c;for(this.channel_count=o.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[],c=0;c<this.channel_count;c++)this.channel_indexes.push(o.readUint16()),this.channel_types.push(o.readUint16()),this.channel_associations.push(o.readUint16())}),l.createBoxCtor("clap","CleanApertureBox",function(o){this.cleanApertureWidthN=o.readUint32(),this.cleanApertureWidthD=o.readUint32(),this.cleanApertureHeightN=o.readUint32(),this.cleanApertureHeightD=o.readUint32(),this.horizOffN=o.readUint32(),this.horizOffD=o.readUint32(),this.vertOffN=o.readUint32(),this.vertOffD=o.readUint32()}),l.createBoxCtor("clli","ContentLightLevelBox",function(o){this.max_content_light_level=o.readUint16(),this.max_pic_average_light_level=o.readUint16()}),l.createFullBoxCtor("cmex","CameraExtrinsicMatrixProperty",function(o){this.flags&1&&(this.pos_x=o.readInt32()),this.flags&2&&(this.pos_y=o.readInt32()),this.flags&4&&(this.pos_z=o.readInt32()),this.flags&8&&(this.version==0?this.flags&16?(this.quat_x=o.readInt32(),this.quat_y=o.readInt32(),this.quat_z=o.readInt32()):(this.quat_x=o.readInt16(),this.quat_y=o.readInt16(),this.quat_z=o.readInt16()):this.version==1),this.flags&32&&(this.id=o.readUint32())}),l.createFullBoxCtor("cmin","CameraIntrinsicMatrixProperty",function(o){this.focal_length_x=o.readInt32(),this.principal_point_x=o.readInt32(),this.principal_point_y=o.readInt32(),this.flags&1&&(this.focal_length_y=o.readInt32(),this.skew_factor=o.readInt32())}),l.createBoxCtor("cmpd","ComponentDefinitionBox",function(o){for(this.component_count=o.readUint32(),this.component_types=[],this.component_type_urls=[],i=0;i<this.component_count;i++){var c=o.readUint16();this.component_types.push(c),c>=32768&&this.component_type_urls.push(o.readCString())}}),l.createFullBoxCtor("co64","ChunkLargeOffsetBox",function(o){var c,f;if(c=o.readUint32(),this.chunk_offsets=[],this.version===0)for(f=0;f<c;f++)this.chunk_offsets.push(o.readUint64())}),l.createFullBoxCtor("CoLL","ContentLightLevelBox",function(o){this.maxCLL=o.readUint16(),this.maxFALL=o.readUint16()}),l.createBoxCtor("colr","ColourInformationBox",function(o){if(this.colour_type=o.readString(4),this.colour_type==="nclx"){this.colour_primaries=o.readUint16(),this.transfer_characteristics=o.readUint16(),this.matrix_coefficients=o.readUint16();var c=o.readUint8();this.full_range_flag=c>>7}else this.colour_type==="rICC"?this.ICC_profile=o.readUint8Array(this.size-4):this.colour_type==="prof"&&(this.ICC_profile=o.readUint8Array(this.size-4))}),l.createFullBoxCtor("cprt","CopyrightBox",function(o){this.parseLanguage(o),this.notice=o.readCString()}),l.createFullBoxCtor("cslg","CompositionToDecodeBox",function(o){this.version===0&&(this.compositionToDTSShift=o.readInt32(),this.leastDecodeToDisplayDelta=o.readInt32(),this.greatestDecodeToDisplayDelta=o.readInt32(),this.compositionStartTime=o.readInt32(),this.compositionEndTime=o.readInt32())}),l.createFullBoxCtor("ctts","CompositionOffsetBox",function(o){var c,f;if(c=o.readUint32(),this.sample_counts=[],this.sample_offsets=[],this.version===0)for(f=0;f<c;f++){this.sample_counts.push(o.readUint32());var m=o.readInt32();m<0&&e.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(m)}else if(this.version==1)for(f=0;f<c;f++)this.sample_counts.push(o.readUint32()),this.sample_offsets.push(o.readInt32())}),l.createBoxCtor("dac3","AC3SpecificBox",function(o){var c=o.readUint8(),f=o.readUint8(),m=o.readUint8();this.fscod=c>>6,this.bsid=c>>1&31,this.bsmod=(c&1)<<2|f>>6&3,this.acmod=f>>3&7,this.lfeon=f>>2&1,this.bit_rate_code=f&3|m>>5&7}),l.createBoxCtor("dec3","EC3SpecificBox",function(o){var c=o.readUint16();this.data_rate=c>>3,this.num_ind_sub=c&7,this.ind_subs=[];for(var f=0;f<this.num_ind_sub+1;f++){var m={};this.ind_subs.push(m);var S=o.readUint8(),T=o.readUint8(),b=o.readUint8();m.fscod=S>>6,m.bsid=S>>1&31,m.bsmod=(S&1)<<4|T>>4&15,m.acmod=T>>1&7,m.lfeon=T&1,m.num_dep_sub=b>>1&15,m.num_dep_sub>0&&(m.chan_loc=(b&1)<<8|o.readUint8())}}),l.createFullBoxCtor("dfLa","FLACSpecificBox",function(o){var c=127,f=128,m=[],S=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];do{var T=o.readUint8(),b=Math.min(T&c,S.length-1);if(b?o.readUint8Array(o.readUint24()):(o.readUint8Array(13),this.samplerate=o.readUint32()>>12,o.readUint8Array(20)),m.push(S[b]),T&f)break}while(!0);this.numMetadataBlocks=m.length+" ("+m.join(", ")+")"}),l.createBoxCtor("dimm","hintimmediateBytesSent",function(o){this.bytessent=o.readUint64()}),l.createBoxCtor("dmax","hintlongestpacket",function(o){this.time=o.readUint32()}),l.createBoxCtor("dmed","hintmediaBytesSent",function(o){this.bytessent=o.readUint64()}),l.createBoxCtor("dOps","OpusSpecificBox",function(o){if(this.Version=o.readUint8(),this.OutputChannelCount=o.readUint8(),this.PreSkip=o.readUint16(),this.InputSampleRate=o.readUint32(),this.OutputGain=o.readInt16(),this.ChannelMappingFamily=o.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=o.readUint8(),this.CoupledCount=o.readUint8(),this.ChannelMapping=[];for(var c=0;c<this.OutputChannelCount;c++)this.ChannelMapping[c]=o.readUint8()}}),l.createFullBoxCtor("dref","DataReferenceBox",function(o){var c,f;this.entries=[];for(var m=o.readUint32(),S=0;S<m;S++)if(c=l.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),c.code===l.OK)f=c.box,this.entries.push(f);else return}),l.createBoxCtor("drep","hintrepeatedBytesSent",function(o){this.bytessent=o.readUint64()}),l.createFullBoxCtor("elng","ExtendedLanguageBox",function(o){this.extended_language=o.readString(this.size-this.hdr_size)}),l.createFullBoxCtor("elst","EditListBox",function(o){this.entries=[];for(var c=o.readUint32(),f=0;f<c;f++){var m={};this.entries.push(m),this.version===1?(m.segment_duration=o.readUint64(),m.media_time=o.readInt64()):(m.segment_duration=o.readUint32(),m.media_time=o.readInt32()),m.media_rate_integer=o.readInt16(),m.media_rate_fraction=o.readInt16()}}),l.createFullBoxCtor("emsg","EventMessageBox",function(o){this.version==1?(this.timescale=o.readUint32(),this.presentation_time=o.readUint64(),this.event_duration=o.readUint32(),this.id=o.readUint32(),this.scheme_id_uri=o.readCString(),this.value=o.readCString()):(this.scheme_id_uri=o.readCString(),this.value=o.readCString(),this.timescale=o.readUint32(),this.presentation_time_delta=o.readUint32(),this.event_duration=o.readUint32(),this.id=o.readUint32());var c=this.size-this.hdr_size-(4*4+(this.scheme_id_uri.length+1)+(this.value.length+1));this.version==1&&(c-=4),this.message_data=o.readUint8Array(c)}),l.createEntityToGroupCtor=function(o,c){l[o+"Box"]=function(f){l.FullBox.call(this,o,f)},l[o+"Box"].prototype=new l.FullBox,l[o+"Box"].prototype.parse=function(f){if(this.parseFullHeader(f),c)c.call(this,f);else for(this.group_id=f.readUint32(),this.num_entities_in_group=f.readUint32(),this.entity_ids=[],i=0;i<this.num_entities_in_group;i++){var m=f.readUint32();this.entity_ids.push(m)}}},l.createEntityToGroupCtor("aebr"),l.createEntityToGroupCtor("afbr"),l.createEntityToGroupCtor("albc"),l.createEntityToGroupCtor("altr"),l.createEntityToGroupCtor("brst"),l.createEntityToGroupCtor("dobr"),l.createEntityToGroupCtor("eqiv"),l.createEntityToGroupCtor("favc"),l.createEntityToGroupCtor("fobr"),l.createEntityToGroupCtor("iaug"),l.createEntityToGroupCtor("pano"),l.createEntityToGroupCtor("slid"),l.createEntityToGroupCtor("ster"),l.createEntityToGroupCtor("tsyn"),l.createEntityToGroupCtor("wbbr"),l.createEntityToGroupCtor("prgr"),l.createEntityToGroupCtor("pymd",function(o){this.group_id=o.readUint32(),this.num_entities_in_group=o.readUint32(),this.entity_ids=[];for(var c=0;c<this.num_entities_in_group;c++){var f=o.readUint32();this.entity_ids.push(f)}for(this.tile_size_x=o.readUint16(),this.tile_size_y=o.readUint16(),this.layer_binning=[],this.tiles_in_layer_column_minus1=[],this.tiles_in_layer_row_minus1=[],c=0;c<this.num_entities_in_group;c++)this.layer_binning[c]=o.readUint16(),this.tiles_in_layer_row_minus1[c]=o.readUint16(),this.tiles_in_layer_column_minus1[c]=o.readUint16()}),l.createFullBoxCtor("esds","ElementaryStreamDescriptorBox",function(o){var c=o.readUint8Array(this.size-this.hdr_size);if(typeof h<"u"){var f=new h;this.esd=f.parseOneDescriptor(new s(c.buffer,0,s.BIG_ENDIAN))}}),l.createBoxCtor("fiel","FieldHandlingBox",function(o){this.fieldCount=o.readUint8(),this.fieldOrdering=o.readUint8()}),l.createBoxCtor("frma","OriginalFormatBox",function(o){this.data_format=o.readString(4)}),l.createBoxCtor("ftyp","FileTypeBox",function(o){var c=this.size-this.hdr_size;this.major_brand=o.readString(4),this.minor_version=o.readUint32(),c-=8,this.compatible_brands=[];for(var f=0;c>=4;)this.compatible_brands[f]=o.readString(4),c-=4,f++}),l.createFullBoxCtor("hdlr","HandlerBox",function(o){this.version===0&&(o.readUint32(),this.handler=o.readString(4),o.readUint32Array(3),this.name=o.readString(this.size-this.hdr_size-20),this.name[this.name.length-1]==="\0"&&(this.name=this.name.slice(0,-1)))}),l.createBoxCtor("hvcC","HEVCConfigurationBox",function(o){var c,f,m,S;this.configurationVersion=o.readUint8(),S=o.readUint8(),this.general_profile_space=S>>6,this.general_tier_flag=(S&32)>>5,this.general_profile_idc=S&31,this.general_profile_compatibility=o.readUint32(),this.general_constraint_indicator=o.readUint8Array(6),this.general_level_idc=o.readUint8(),this.min_spatial_segmentation_idc=o.readUint16()&4095,this.parallelismType=o.readUint8()&3,this.chroma_format_idc=o.readUint8()&3,this.bit_depth_luma_minus8=o.readUint8()&7,this.bit_depth_chroma_minus8=o.readUint8()&7,this.avgFrameRate=o.readUint16(),S=o.readUint8(),this.constantFrameRate=S>>6,this.numTemporalLayers=(S&13)>>3,this.temporalIdNested=(S&4)>>2,this.lengthSizeMinusOne=S&3,this.nalu_arrays=[],this.nalu_arrays.toString=function(){var L="<table class='inner-table'>";L+="<thead><tr><th>completeness</th><th>nalu_type</th><th>nalu_data</th></tr></thead>",L+="<tbody>";for(var w=0;w<this.length;w++){var R=this[w];L+="<tr>",L+="<td rowspan='"+R.length+"'>"+R.completeness+"</td>",L+="<td rowspan='"+R.length+"'>"+R.nalu_type+"</td>";for(var M=0;M<R.length;M++){var k=R[M];M!==0&&(L+="<tr>"),L+="<td>",L+=k.data.reduce(function(z,O){return z+O.toString(16).padStart(2,"0")},"0x"),L+="</td></tr>"}}return L+="</tbody></table>",L};var T=o.readUint8();for(c=0;c<T;c++){var b=[];this.nalu_arrays.push(b),S=o.readUint8(),b.completeness=(S&128)>>7,b.nalu_type=S&63;var A=o.readUint16();for(f=0;f<A;f++){var I={};b.push(I),m=o.readUint16(),I.data=o.readUint8Array(m)}}}),l.createFullBoxCtor("iinf","ItemInfoBox",function(o){var c;this.version===0?this.entry_count=o.readUint16():this.entry_count=o.readUint32(),this.item_infos=[];for(var f=0;f<this.entry_count;f++)if(c=l.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),c.code===l.OK)c.box.type!=="infe"&&e.error("BoxParser","Expected 'infe' box, got "+c.box.type),this.item_infos[f]=c.box;else return}),l.createFullBoxCtor("iloc","ItemLocationBox",function(o){var c;c=o.readUint8(),this.offset_size=c>>4&15,this.length_size=c&15,c=o.readUint8(),this.base_offset_size=c>>4&15,this.version===1||this.version===2?this.index_size=c&15:this.index_size=0,this.items=[];var f=0;if(this.version<2)f=o.readUint16();else if(this.version===2)f=o.readUint32();else throw"version of iloc box not supported";for(var m=0;m<f;m++){var S={};if(this.items.push(S),this.version<2)S.item_ID=o.readUint16();else if(this.version===2)S.item_ID=o.readUint32();else throw"version of iloc box not supported";switch(this.version===1||this.version===2?S.construction_method=o.readUint16()&15:S.construction_method=0,S.data_reference_index=o.readUint16(),this.base_offset_size){case 0:S.base_offset=0;break;case 4:S.base_offset=o.readUint32();break;case 8:S.base_offset=o.readUint64();break;default:throw"Error reading base offset size"}var T=o.readUint16();S.extents=[];for(var b=0;b<T;b++){var A={};if(S.extents.push(A),this.version===1||this.version===2)switch(this.index_size){case 0:A.extent_index=0;break;case 4:A.extent_index=o.readUint32();break;case 8:A.extent_index=o.readUint64();break;default:throw"Error reading extent index"}switch(this.offset_size){case 0:A.extent_offset=0;break;case 4:A.extent_offset=o.readUint32();break;case 8:A.extent_offset=o.readUint64();break;default:throw"Error reading extent index"}switch(this.length_size){case 0:A.extent_length=0;break;case 4:A.extent_length=o.readUint32();break;case 8:A.extent_length=o.readUint64();break;default:throw"Error reading extent index"}}}}),l.createBoxCtor("imir","ImageMirror",function(o){var c=o.readUint8();this.reserved=c>>7,this.axis=c&1}),l.createFullBoxCtor("infe","ItemInfoEntry",function(o){if((this.version===0||this.version===1)&&(this.item_ID=o.readUint16(),this.item_protection_index=o.readUint16(),this.item_name=o.readCString(),this.content_type=o.readCString(),this.content_encoding=o.readCString()),this.version===1){this.extension_type=o.readString(4),e.warn("BoxParser","Cannot parse extension type"),o.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=o.readUint16():this.version===3&&(this.item_ID=o.readUint32()),this.item_protection_index=o.readUint16(),this.item_type=o.readString(4),this.item_name=o.readCString(),this.item_type==="mime"?(this.content_type=o.readCString(),this.content_encoding=o.readCString()):this.item_type==="uri "&&(this.item_uri_type=o.readCString()))}),l.createFullBoxCtor("ipma","ItemPropertyAssociationBox",function(o){var c,f;for(entry_count=o.readUint32(),this.associations=[],c=0;c<entry_count;c++){var m={};this.associations.push(m),this.version<1?m.id=o.readUint16():m.id=o.readUint32();var S=o.readUint8();for(m.props=[],f=0;f<S;f++){var T=o.readUint8(),b={};m.props.push(b),b.essential=(T&128)>>7===1,this.flags&1?b.property_index=(T&127)<<8|o.readUint8():b.property_index=T&127}}}),l.createFullBoxCtor("iref","ItemReferenceBox",function(o){var c,f;for(this.references=[];o.getPosition()<this.start+this.size;)if(c=l.parseOneBox(o,!0,this.size-(o.getPosition()-this.start)),c.code===l.OK)this.version===0?f=new l.SingleItemTypeReferenceBox(c.type,c.size,c.hdr_size,c.start):f=new l.SingleItemTypeReferenceBoxLarge(c.type,c.size,c.hdr_size,c.start),f.write===l.Box.prototype.write&&f.type!=="mdat"&&(e.warn("BoxParser",f.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),f.parseDataAndRewind(o)),f.parse(o),this.references.push(f);else return}),l.createBoxCtor("irot","ImageRotation",function(o){this.angle=o.readUint8()&3}),l.createFullBoxCtor("ispe","ImageSpatialExtentsProperty",function(o){this.image_width=o.readUint32(),this.image_height=o.readUint32()}),l.createFullBoxCtor("kind","KindBox",function(o){this.schemeURI=o.readCString(),this.value=o.readCString()}),l.createFullBoxCtor("leva","LevelAssignmentBox",function(o){var c=o.readUint8();this.levels=[];for(var f=0;f<c;f++){var m={};this.levels[f]=m,m.track_ID=o.readUint32();var S=o.readUint8();switch(m.padding_flag=S>>7,m.assignment_type=S&127,m.assignment_type){case 0:m.grouping_type=o.readString(4);break;case 1:m.grouping_type=o.readString(4),m.grouping_type_parameter=o.readUint32();break;case 2:break;case 3:break;case 4:m.sub_track_id=o.readUint32();break;default:e.warn("BoxParser","Unknown leva assignement type")}}}),l.createBoxCtor("lhvC","LHEVCConfigurationBox",function(o){var c,f,m;this.configurationVersion=o.readUint8(),this.min_spatial_segmentation_idc=o.readUint16()&4095,this.parallelismType=o.readUint8()&3,m=o.readUint8(),this.numTemporalLayers=(m&13)>>3,this.temporalIdNested=(m&4)>>2,this.lengthSizeMinusOne=m&3,this.nalu_arrays=[],this.nalu_arrays.toString=function(){var L="<table class='inner-table'>";L+="<thead><tr><th>completeness</th><th>nalu_type</th><th>nalu_data</th></tr></thead>",L+="<tbody>";for(var w=0;w<this.length;w++){var R=this[w];L+="<tr>",L+="<td rowspan='"+R.length+"'>"+R.completeness+"</td>",L+="<td rowspan='"+R.length+"'>"+R.nalu_type+"</td>";for(var M=0;M<R.length;M++){var k=R[M];M!==0&&(L+="<tr>"),L+="<td>",L+=k.data.reduce(function(z,O){return z+O.toString(16).padStart(2,"0")},"0x"),L+="</td></tr>"}}return L+="</tbody></table>",L};var S=o.readUint8();for(c=0;c<S;c++){var T=[];this.nalu_arrays.push(T),m=o.readUint8(),T.completeness=(m&128)>>7,T.nalu_type=m&63;var b=o.readUint16();for(f=0;f<b;f++){var A={};T.push(A);var I=o.readUint16();A.data=o.readUint8Array(I)}}}),l.createBoxCtor("lsel","LayerSelectorProperty",function(o){this.layer_id=o.readUint16()}),l.createBoxCtor("maxr","hintmaxrate",function(o){this.period=o.readUint32(),this.bytes=o.readUint32()});function d(o,c){this.x=o,this.y=c}d.prototype.toString=function(){return"("+this.x+","+this.y+")"},l.createBoxCtor("mdcv","MasteringDisplayColourVolumeBox",function(o){this.display_primaries=[],this.display_primaries[0]=new d(o.readUint16(),o.readUint16()),this.display_primaries[1]=new d(o.readUint16(),o.readUint16()),this.display_primaries[2]=new d(o.readUint16(),o.readUint16()),this.white_point=new d(o.readUint16(),o.readUint16()),this.max_display_mastering_luminance=o.readUint32(),this.min_display_mastering_luminance=o.readUint32()}),l.createFullBoxCtor("mdhd","MediaHeaderBox",function(o){this.version==1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.timescale=o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.timescale=o.readUint32(),this.duration=o.readUint32()),this.parseLanguage(o),o.readUint16()}),l.createFullBoxCtor("mehd","MovieExtendsHeaderBox",function(o){this.flags&1&&(e.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),this.version==1?this.fragment_duration=o.readUint64():this.fragment_duration=o.readUint32()}),l.createFullBoxCtor("meta","MetaBox",function(o){this.boxes=[],l.ContainerBox.prototype.parse.call(this,o)}),l.createFullBoxCtor("mfhd","MovieFragmentHeaderBox",function(o){this.sequence_number=o.readUint32()}),l.createFullBoxCtor("mfro","MovieFragmentRandomAccessOffsetBox",function(o){this._size=o.readUint32()}),l.createFullBoxCtor("mskC","MaskConfigurationProperty",function(o){this.bits_per_pixel=o.readUint8()}),l.createFullBoxCtor("mvhd","MovieHeaderBox",function(o){this.version==1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.timescale=o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.timescale=o.readUint32(),this.duration=o.readUint32()),this.rate=o.readUint32(),this.volume=o.readUint16()>>8,o.readUint16(),o.readUint32Array(2),this.matrix=o.readUint32Array(9),o.readUint32Array(6),this.next_track_id=o.readUint32()}),l.createBoxCtor("npck","hintPacketsSent",function(o){this.packetssent=o.readUint32()}),l.createBoxCtor("nump","hintPacketsSent",function(o){this.packetssent=o.readUint64()}),l.createFullBoxCtor("padb","PaddingBitsBox",function(o){var c=o.readUint32();this.padbits=[];for(var f=0;f<Math.floor((c+1)/2);f++)this.padbits=o.readUint8()}),l.createBoxCtor("pasp","PixelAspectRatioBox",function(o){this.hSpacing=o.readUint32(),this.vSpacing=o.readUint32()}),l.createBoxCtor("payl","CuePayloadBox",function(o){this.text=o.readString(this.size-this.hdr_size)}),l.createBoxCtor("payt","hintpayloadID",function(o){this.payloadID=o.readUint32();var c=o.readUint8();this.rtpmap_string=o.readString(c)}),l.createFullBoxCtor("pdin","ProgressiveDownloadInfoBox",function(o){var c=(this.size-this.hdr_size)/8;this.rate=[],this.initial_delay=[];for(var f=0;f<c;f++)this.rate[f]=o.readUint32(),this.initial_delay[f]=o.readUint32()}),l.createFullBoxCtor("pitm","PrimaryItemBox",function(o){this.version===0?this.item_id=o.readUint16():this.item_id=o.readUint32()}),l.createFullBoxCtor("pixi","PixelInformationProperty",function(o){var c;for(this.num_channels=o.readUint8(),this.bits_per_channels=[],c=0;c<this.num_channels;c++)this.bits_per_channels[c]=o.readUint8()}),l.createBoxCtor("pmax","hintlargestpacket",function(o){this.bytes=o.readUint32()}),l.createFullBoxCtor("prdi","ProgressiveDerivedImageItemInformationProperty",function(o){if(this.step_count=o.readUint16(),this.item_count=[],this.flags&2)for(var c=0;c<this.step_count;c++)this.item_count[c]=o.readUint16()}),l.createFullBoxCtor("prft","ProducerReferenceTimeBox",function(o){this.ref_track_id=o.readUint32(),this.ntp_timestamp=o.readUint64(),this.version===0?this.media_time=o.readUint32():this.media_time=o.readUint64()}),l.createFullBoxCtor("pssh","ProtectionSystemSpecificHeaderBox",function(o){if(this.system_id=l.parseHex16(o),this.version>0){var c=o.readUint32();this.kid=[];for(var f=0;f<c;f++)this.kid[f]=l.parseHex16(o)}var m=o.readUint32();m>0&&(this.data=o.readUint8Array(m))}),l.createFullBoxCtor("clef","TrackCleanApertureDimensionsBox",function(o){this.width=o.readUint32(),this.height=o.readUint32()}),l.createFullBoxCtor("enof","TrackEncodedPixelsDimensionsBox",function(o){this.width=o.readUint32(),this.height=o.readUint32()}),l.createFullBoxCtor("prof","TrackProductionApertureDimensionsBox",function(o){this.width=o.readUint32(),this.height=o.readUint32()}),l.createContainerBoxCtor("tapt","TrackApertureModeDimensionsBox",null,["clef","prof","enof"]),l.createBoxCtor("rtp ","rtpmoviehintinformation",function(o){this.descriptionformat=o.readString(4),this.sdptext=o.readString(this.size-this.hdr_size-4)}),l.createFullBoxCtor("saio","SampleAuxiliaryInformationOffsetsBox",function(o){this.flags&1&&(this.aux_info_type=o.readString(4),this.aux_info_type_parameter=o.readUint32());var c=o.readUint32();this.offset=[];for(var f=0;f<c;f++)this.version===0?this.offset[f]=o.readUint32():this.offset[f]=o.readUint64()}),l.createFullBoxCtor("saiz","SampleAuxiliaryInformationSizesBox",function(o){if(this.flags&1&&(this.aux_info_type=o.readString(4),this.aux_info_type_parameter=o.readUint32()),this.default_sample_info_size=o.readUint8(),this.sample_count=o.readUint32(),this.sample_info_size=[],this.default_sample_info_size===0)for(var c=0;c<this.sample_count;c++)this.sample_info_size[c]=o.readUint8()}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_METADATA,"mett",function(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_METADATA,"metx",function(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.namespace=o.readCString(),this.schema_location=o.readCString(),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE,"sbtt",function(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE,"stpp",function(o){this.parseHeader(o),this.namespace=o.readCString(),this.schema_location=o.readCString(),this.auxiliary_mime_types=o.readCString(),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE,"stxt",function(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE,"tx3g",function(o){this.parseHeader(o),this.displayFlags=o.readUint32(),this.horizontal_justification=o.readInt8(),this.vertical_justification=o.readInt8(),this.bg_color_rgba=o.readUint8Array(4),this.box_record=o.readInt16Array(4),this.style_record=o.readUint8Array(12),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_METADATA,"wvtt",function(o){this.parseHeader(o),this.parseFooter(o)}),l.createSampleGroupCtor("alst",function(o){var c,f=o.readUint16();for(this.first_output_sample=o.readUint16(),this.sample_offset=[],c=0;c<f;c++)this.sample_offset[c]=o.readUint32();var m=this.description_length-4-4*f;for(this.num_output_samples=[],this.num_total_samples=[],c=0;c<m/4;c++)this.num_output_samples[c]=o.readUint16(),this.num_total_samples[c]=o.readUint16()}),l.createSampleGroupCtor("avll",function(o){this.layerNumber=o.readUint8(),this.accurateStatisticsFlag=o.readUint8(),this.avgBitRate=o.readUint16(),this.avgFrameRate=o.readUint16()}),l.createSampleGroupCtor("avss",function(o){this.subSequenceIdentifier=o.readUint16(),this.layerNumber=o.readUint8();var c=o.readUint8();this.durationFlag=c>>7,this.avgRateFlag=c>>6&1,this.durationFlag&&(this.duration=o.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=o.readUint8(),this.avgBitRate=o.readUint16(),this.avgFrameRate=o.readUint16()),this.dependency=[];for(var f=o.readUint8(),m=0;m<f;m++){var S={};this.dependency.push(S),S.subSeqDirectionFlag=o.readUint8(),S.layerNumber=o.readUint8(),S.subSequenceIdentifier=o.readUint16()}}),l.createSampleGroupCtor("dtrt",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("mvif",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("prol",function(o){this.roll_distance=o.readInt16()}),l.createSampleGroupCtor("rap ",function(o){var c=o.readUint8();this.num_leading_samples_known=c>>7,this.num_leading_samples=c&127}),l.createSampleGroupCtor("rash",function(o){if(this.operation_point_count=o.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)e.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=o.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=o.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(var c=0;c<this.operation_point_count;c++)this.available_bitrate[c]=o.readUint32(),this.target_rate_share[c]=o.readUint16()}this.maximum_bitrate=o.readUint32(),this.minimum_bitrate=o.readUint32(),this.discard_priority=o.readUint8()}}),l.createSampleGroupCtor("roll",function(o){this.roll_distance=o.readInt16()}),l.SampleGroupEntry.prototype.parse=function(o){e.warn("BoxParser","Unknown Sample Group type: "+this.grouping_type),this.data=o.readUint8Array(this.description_length)},l.createSampleGroupCtor("scif",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("scnm",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("seig",function(o){this.reserved=o.readUint8();var c=o.readUint8();this.crypt_byte_block=c>>4,this.skip_byte_block=c&15,this.isProtected=o.readUint8(),this.Per_Sample_IV_Size=o.readUint8(),this.KID=l.parseHex16(o),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=o.readUint8(),this.constant_IV=o.readUint8Array(this.constant_IV_size))}),l.createSampleGroupCtor("stsa",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("sync",function(o){var c=o.readUint8();this.NAL_unit_type=c&63}),l.createSampleGroupCtor("tele",function(o){var c=o.readUint8();this.level_independently_decodable=c>>7}),l.createSampleGroupCtor("tsas",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("tscl",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("vipr",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createFullBoxCtor("sbgp","SampleToGroupBox",function(o){this.grouping_type=o.readString(4),this.version===1?this.grouping_type_parameter=o.readUint32():this.grouping_type_parameter=0,this.entries=[];for(var c=o.readUint32(),f=0;f<c;f++){var m={};this.entries.push(m),m.sample_count=o.readInt32(),m.group_description_index=o.readInt32()}});function p(o,c){this.bad_pixel_row=o,this.bad_pixel_column=c}p.prototype.toString=function(){return"[row: "+this.bad_pixel_row+", column: "+this.bad_pixel_column+"]"},l.createFullBoxCtor("sbpm","SensorBadPixelsMapBox",function(o){var c;for(this.component_count=o.readUint16(),this.component_index=[],c=0;c<this.component_count;c++)this.component_index.push(o.readUint16());var f=o.readUint8();for(this.correction_applied=(f&128)==128,this.num_bad_rows=o.readUint32(),this.num_bad_cols=o.readUint32(),this.num_bad_pixels=o.readUint32(),this.bad_rows=[],this.bad_columns=[],this.bad_pixels=[],c=0;c<this.num_bad_rows;c++)this.bad_rows.push(o.readUint32());for(c=0;c<this.num_bad_cols;c++)this.bad_columns.push(o.readUint32());for(c=0;c<this.num_bad_pixels;c++){var m=o.readUint32(),S=o.readUint32();this.bad_pixels.push(new p(m,S))}}),l.createFullBoxCtor("schm","SchemeTypeBox",function(o){this.scheme_type=o.readString(4),this.scheme_version=o.readUint32(),this.flags&1&&(this.scheme_uri=o.readString(this.size-this.hdr_size-8))}),l.createBoxCtor("sdp ","rtptracksdphintinformation",function(o){this.sdptext=o.readString(this.size-this.hdr_size)}),l.createFullBoxCtor("sdtp","SampleDependencyTypeBox",function(o){var c,f=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(var m=0;m<f;m++)c=o.readUint8(),this.is_leading[m]=c>>6,this.sample_depends_on[m]=c>>4&3,this.sample_is_depended_on[m]=c>>2&3,this.sample_has_redundancy[m]=c&3}),l.createFullBoxCtor("senc","SampleEncryptionBox"),l.createFullBoxCtor("sgpd","SampleGroupDescriptionBox",function(o){this.grouping_type=o.readString(4),e.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),this.version===1?this.default_length=o.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=o.readUint32()),this.entries=[];for(var c=o.readUint32(),f=0;f<c;f++){var m;l[this.grouping_type+"SampleGroupEntry"]?m=new l[this.grouping_type+"SampleGroupEntry"](this.grouping_type):m=new l.SampleGroupEntry(this.grouping_type),this.entries.push(m),this.version===1?this.default_length===0?m.description_length=o.readUint32():m.description_length=this.default_length:m.description_length=this.default_length,m.write===l.SampleGroupEntry.prototype.write&&(e.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),m.data=o.readUint8Array(m.description_length),o.position-=m.description_length),m.parse(o)}}),l.createFullBoxCtor("sidx","CompressedSegmentIndexBox",function(o){this.reference_ID=o.readUint32(),this.timescale=o.readUint32(),this.version===0?(this.earliest_presentation_time=o.readUint32(),this.first_offset=o.readUint32()):(this.earliest_presentation_time=o.readUint64(),this.first_offset=o.readUint64()),o.readUint16(),this.references=[];for(var c=o.readUint16(),f=0;f<c;f++){var m={};this.references.push(m);var S=o.readUint32();m.reference_type=S>>31&1,m.referenced_size=S&2147483647,m.subsegment_duration=o.readUint32(),S=o.readUint32(),m.starts_with_SAP=S>>31&1,m.SAP_type=S>>28&7,m.SAP_delta_time=S&268435455}}),l.SingleItemTypeReferenceBox=function(o,c,f,m){l.Box.call(this,o,c),this.hdr_size=f,this.start=m},l.SingleItemTypeReferenceBox.prototype=new l.Box,l.SingleItemTypeReferenceBox.prototype.parse=function(o){this.from_item_ID=o.readUint16();var c=o.readUint16();this.references=[];for(var f=0;f<c;f++)this.references[f]={},this.references[f].to_item_ID=o.readUint16()},l.SingleItemTypeReferenceBoxLarge=function(o,c,f,m){l.Box.call(this,o,c),this.hdr_size=f,this.start=m},l.SingleItemTypeReferenceBoxLarge.prototype=new l.Box,l.SingleItemTypeReferenceBoxLarge.prototype.parse=function(o){this.from_item_ID=o.readUint32();var c=o.readUint16();this.references=[];for(var f=0;f<c;f++)this.references[f]={},this.references[f].to_item_ID=o.readUint32()},l.createFullBoxCtor("SmDm","SMPTE2086MasteringDisplayMetadataBox",function(o){this.primaryRChromaticity_x=o.readUint16(),this.primaryRChromaticity_y=o.readUint16(),this.primaryGChromaticity_x=o.readUint16(),this.primaryGChromaticity_y=o.readUint16(),this.primaryBChromaticity_x=o.readUint16(),this.primaryBChromaticity_y=o.readUint16(),this.whitePointChromaticity_x=o.readUint16(),this.whitePointChromaticity_y=o.readUint16(),this.luminanceMax=o.readUint32(),this.luminanceMin=o.readUint32()}),l.createFullBoxCtor("smhd","SoundMediaHeaderBox",function(o){this.balance=o.readUint16(),o.readUint16()}),l.createFullBoxCtor("ssix","CompressedSubsegmentIndexBox",function(o){this.subsegments=[];for(var c=o.readUint32(),f=0;f<c;f++){var m={};this.subsegments.push(m),m.ranges=[];for(var S=o.readUint32(),T=0;T<S;T++){var b={};m.ranges.push(b),b.level=o.readUint8(),b.range_size=o.readUint24()}}}),l.createFullBoxCtor("stco","ChunkOffsetBox",function(o){var c;if(c=o.readUint32(),this.chunk_offsets=[],this.version===0)for(var f=0;f<c;f++)this.chunk_offsets.push(o.readUint32())}),l.createFullBoxCtor("stdp","DegradationPriorityBox",function(o){var c=(this.size-this.hdr_size)/2;this.priority=[];for(var f=0;f<c;f++)this.priority[f]=o.readUint16()}),l.createFullBoxCtor("sthd","SubtitleMediaHeaderBox"),l.createFullBoxCtor("stri","SubTrackInformationBox",function(o){this.switch_group=o.readUint16(),this.alternate_group=o.readUint16(),this.sub_track_id=o.readUint32();var c=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(var f=0;f<c;f++)this.attribute_list[f]=o.readUint32()}),l.createFullBoxCtor("stsc","SampleToChunkBox",function(o){var c,f;if(c=o.readUint32(),this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],this.version===0)for(f=0;f<c;f++)this.first_chunk.push(o.readUint32()),this.samples_per_chunk.push(o.readUint32()),this.sample_description_index.push(o.readUint32())}),l.createFullBoxCtor("stsd","SampleDescriptionBox",function(o){var c,f,m,S;for(this.entries=[],m=o.readUint32(),c=1;c<=m;c++)if(f=l.parseOneBox(o,!0,this.size-(o.getPosition()-this.start)),f.code===l.OK)l[f.type+"SampleEntry"]?(S=new l[f.type+"SampleEntry"](f.size),S.hdr_size=f.hdr_size,S.start=f.start):(e.warn("BoxParser","Unknown sample entry type: "+f.type),S=new l.SampleEntry(f.type,f.size,f.hdr_size,f.start)),S.write===l.SampleEntry.prototype.write&&(e.info("BoxParser","SampleEntry "+S.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),S.parseDataAndRewind(o)),S.parse(o),this.entries.push(S);else return}),l.createFullBoxCtor("stsg","SubTrackSampleGroupBox",function(o){this.grouping_type=o.readUint32();var c=o.readUint16();this.group_description_index=[];for(var f=0;f<c;f++)this.group_description_index[f]=o.readUint32()}),l.createFullBoxCtor("stsh","ShadowSyncSampleBox",function(o){var c,f;if(c=o.readUint32(),this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],this.version===0)for(f=0;f<c;f++)this.shadowed_sample_numbers.push(o.readUint32()),this.sync_sample_numbers.push(o.readUint32())}),l.createFullBoxCtor("stss","SyncSampleBox",function(o){var c,f;if(f=o.readUint32(),this.version===0)for(this.sample_numbers=[],c=0;c<f;c++)this.sample_numbers.push(o.readUint32())}),l.createFullBoxCtor("stsz","SampleSizeBox",function(o){var c;if(this.sample_sizes=[],this.version===0)for(this.sample_size=o.readUint32(),this.sample_count=o.readUint32(),c=0;c<this.sample_count;c++)this.sample_size===0?this.sample_sizes.push(o.readUint32()):this.sample_sizes[c]=this.sample_size}),l.createFullBoxCtor("stts","TimeToSampleBox",function(o){var c,f,m;if(c=o.readUint32(),this.sample_counts=[],this.sample_deltas=[],this.version===0)for(f=0;f<c;f++)this.sample_counts.push(o.readUint32()),m=o.readInt32(),m<0&&(e.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),m=1),this.sample_deltas.push(m)}),l.createFullBoxCtor("stvi","StereoVideoBox",function(o){var c=o.readUint32();this.single_view_allowed=c&3,this.stereo_scheme=o.readUint32();var f=o.readUint32();this.stereo_indication_type=o.readString(f);var m,S;for(this.boxes=[];o.getPosition()<this.start+this.size;)if(m=l.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),m.code===l.OK)S=m.box,this.boxes.push(S),this[S.type]=S;else return}),l.createBoxCtor("styp","SegmentTypeBox",function(o){l.ftypBox.prototype.parse.call(this,o)}),l.createFullBoxCtor("stz2","CompactSampleSizeBox",function(o){var c,f;if(this.sample_sizes=[],this.version===0)if(this.reserved=o.readUint24(),this.field_size=o.readUint8(),f=o.readUint32(),this.field_size===4)for(c=0;c<f;c+=2){var m=o.readUint8();this.sample_sizes[c]=m>>4&15,this.sample_sizes[c+1]=m&15}else if(this.field_size===8)for(c=0;c<f;c++)this.sample_sizes[c]=o.readUint8();else if(this.field_size===16)for(c=0;c<f;c++)this.sample_sizes[c]=o.readUint16();else e.error("BoxParser","Error in length field in stz2 box")}),l.createFullBoxCtor("subs","SubSampleInformationBox",function(o){var c,f,m,S;for(m=o.readUint32(),this.entries=[],c=0;c<m;c++){var T={};if(this.entries[c]=T,T.sample_delta=o.readUint32(),T.subsamples=[],S=o.readUint16(),S>0)for(f=0;f<S;f++){var b={};T.subsamples.push(b),this.version==1?b.size=o.readUint32():b.size=o.readUint16(),b.priority=o.readUint8(),b.discardable=o.readUint8(),b.codec_specific_parameters=o.readUint32()}}}),l.createFullBoxCtor("tenc","TrackEncryptionBox",function(o){if(o.readUint8(),this.version===0)o.readUint8();else{var c=o.readUint8();this.default_crypt_byte_block=c>>4&15,this.default_skip_byte_block=c&15}this.default_isProtected=o.readUint8(),this.default_Per_Sample_IV_Size=o.readUint8(),this.default_KID=l.parseHex16(o),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=o.readUint8(),this.default_constant_IV=o.readUint8Array(this.default_constant_IV_size))}),l.createFullBoxCtor("tfdt","TrackFragmentBaseMediaDecodeTimeBox",function(o){this.version==1?this.baseMediaDecodeTime=o.readUint64():this.baseMediaDecodeTime=o.readUint32()}),l.createFullBoxCtor("tfhd","TrackFragmentHeaderBox",function(o){var c=0;this.track_id=o.readUint32(),this.size-this.hdr_size>c&&this.flags&l.TFHD_FLAG_BASE_DATA_OFFSET?(this.base_data_offset=o.readUint64(),c+=8):this.base_data_offset=0,this.size-this.hdr_size>c&&this.flags&l.TFHD_FLAG_SAMPLE_DESC?(this.default_sample_description_index=o.readUint32(),c+=4):this.default_sample_description_index=0,this.size-this.hdr_size>c&&this.flags&l.TFHD_FLAG_SAMPLE_DUR?(this.default_sample_duration=o.readUint32(),c+=4):this.default_sample_duration=0,this.size-this.hdr_size>c&&this.flags&l.TFHD_FLAG_SAMPLE_SIZE?(this.default_sample_size=o.readUint32(),c+=4):this.default_sample_size=0,this.size-this.hdr_size>c&&this.flags&l.TFHD_FLAG_SAMPLE_FLAGS?(this.default_sample_flags=o.readUint32(),c+=4):this.default_sample_flags=0}),l.createFullBoxCtor("tfra","TrackFragmentRandomAccessBox",function(o){this.track_ID=o.readUint32(),o.readUint24();var c=o.readUint8();this.length_size_of_traf_num=c>>4&3,this.length_size_of_trun_num=c>>2&3,this.length_size_of_sample_num=c&3,this.entries=[];for(var f=o.readUint32(),m=0;m<f;m++)this.version===1?(this.time=o.readUint64(),this.moof_offset=o.readUint64()):(this.time=o.readUint32(),this.moof_offset=o.readUint32()),this.traf_number=o["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=o["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=o["readUint"+8*(this.length_size_of_sample_num+1)]()}),l.createFullBoxCtor("tkhd","TrackHeaderBox",function(o){this.version==1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.track_id=o.readUint32(),o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.track_id=o.readUint32(),o.readUint32(),this.duration=o.readUint32()),o.readUint32Array(2),this.layer=o.readInt16(),this.alternate_group=o.readInt16(),this.volume=o.readInt16()>>8,o.readUint16(),this.matrix=o.readInt32Array(9),this.width=o.readUint32(),this.height=o.readUint32()}),l.createBoxCtor("tmax","hintmaxrelativetime",function(o){this.time=o.readUint32()}),l.createBoxCtor("tmin","hintminrelativetime",function(o){this.time=o.readUint32()}),l.createBoxCtor("totl","hintBytesSent",function(o){this.bytessent=o.readUint32()}),l.createBoxCtor("tpay","hintBytesSent",function(o){this.bytessent=o.readUint32()}),l.createBoxCtor("tpyl","hintBytesSent",function(o){this.bytessent=o.readUint64()}),l.TrackGroupTypeBox.prototype.parse=function(o){this.parseFullHeader(o),this.track_group_id=o.readUint32()},l.createTrackGroupCtor("msrc"),l.TrackReferenceTypeBox=function(o,c,f,m){l.Box.call(this,o,c),this.hdr_size=f,this.start=m},l.TrackReferenceTypeBox.prototype=new l.Box,l.TrackReferenceTypeBox.prototype.parse=function(o){this.track_ids=o.readUint32Array((this.size-this.hdr_size)/4)},l.trefBox.prototype.parse=function(o){for(var c,f;o.getPosition()<this.start+this.size;)if(c=l.parseOneBox(o,!0,this.size-(o.getPosition()-this.start)),c.code===l.OK)f=new l.TrackReferenceTypeBox(c.type,c.size,c.hdr_size,c.start),f.write===l.Box.prototype.write&&f.type!=="mdat"&&(e.info("BoxParser","TrackReference "+f.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),f.parseDataAndRewind(o)),f.parse(o),this.boxes.push(f);else return},l.createFullBoxCtor("trep","TrackExtensionPropertiesBox",function(o){for(this.track_ID=o.readUint32(),this.boxes=[];o.getPosition()<this.start+this.size;)if(ret=l.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),ret.code===l.OK)box=ret.box,this.boxes.push(box);else return}),l.createFullBoxCtor("trex","TrackExtendsBox",function(o){this.track_id=o.readUint32(),this.default_sample_description_index=o.readUint32(),this.default_sample_duration=o.readUint32(),this.default_sample_size=o.readUint32(),this.default_sample_flags=o.readUint32()}),l.createBoxCtor("trpy","hintBytesSent",function(o){this.bytessent=o.readUint64()}),l.createFullBoxCtor("trun","TrackRunBox",function(o){var c=0;if(this.sample_count=o.readUint32(),c+=4,this.size-this.hdr_size>c&&this.flags&l.TRUN_FLAGS_DATA_OFFSET?(this.data_offset=o.readInt32(),c+=4):this.data_offset=0,this.size-this.hdr_size>c&&this.flags&l.TRUN_FLAGS_FIRST_FLAG?(this.first_sample_flags=o.readUint32(),c+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>c)for(var f=0;f<this.sample_count;f++)this.flags&l.TRUN_FLAGS_DURATION&&(this.sample_duration[f]=o.readUint32()),this.flags&l.TRUN_FLAGS_SIZE&&(this.sample_size[f]=o.readUint32()),this.flags&l.TRUN_FLAGS_FLAGS&&(this.sample_flags[f]=o.readUint32()),this.flags&l.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?this.sample_composition_time_offset[f]=o.readUint32():this.sample_composition_time_offset[f]=o.readInt32())}),l.createFullBoxCtor("tsel","TrackSelectionBox",function(o){this.switch_group=o.readUint32();var c=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(var f=0;f<c;f++)this.attribute_list[f]=o.readUint32()}),l.createFullBoxCtor("txtC","TextConfigBox",function(o){this.config=o.readCString()}),l.createBoxCtor("tyco","TypeCombinationBox",function(o){var c=(this.size-this.hdr_size)/4;this.compatible_brands=[];for(var f=0;f<c;f++)this.compatible_brands[f]=o.readString(4)}),l.createFullBoxCtor("udes","UserDescriptionProperty",function(o){this.lang=o.readCString(),this.name=o.readCString(),this.description=o.readCString(),this.tags=o.readCString()}),l.createFullBoxCtor("uncC","UncompressedFrameConfigBox",function(o){var c;if(this.profile=o.readString(4),this.version!=1){if(this.version==0){for(this.component_count=o.readUint32(),this.component_index=[],this.component_bit_depth_minus_one=[],this.component_format=[],this.component_align_size=[],c=0;c<this.component_count;c++)this.component_index.push(o.readUint16()),this.component_bit_depth_minus_one.push(o.readUint8()),this.component_format.push(o.readUint8()),this.component_align_size.push(o.readUint8());this.sampling_type=o.readUint8(),this.interleave_type=o.readUint8(),this.block_size=o.readUint8();var f=o.readUint8();this.component_little_endian=f>>7&1,this.block_pad_lsb=f>>6&1,this.block_little_endian=f>>5&1,this.block_reversed=f>>4&1,this.pad_unknown=f>>3&1,this.pixel_size=o.readUint32(),this.row_align_size=o.readUint32(),this.tile_align_size=o.readUint32(),this.num_tile_cols_minus_one=o.readUint32(),this.num_tile_rows_minus_one=o.readUint32()}}}),l.createFullBoxCtor("url ","DataEntryUrlBox",function(o){this.flags!==1&&(this.location=o.readCString())}),l.createFullBoxCtor("urn ","DataEntryUrnBox",function(o){this.name=o.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=o.readCString())}),l.createUUIDBox("a5d40b30e81411ddba2f0800200c9a66","LiveServerManifestBox",!0,!1,function(o){this.LiveServerManifest=o.readString(this.size-this.hdr_size).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}),l.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3","PiffProtectionSystemSpecificHeaderBox",!0,!1,function(o){this.system_id=l.parseHex16(o);var c=o.readUint32();c>0&&(this.data=o.readUint8Array(c))}),l.createUUIDBox("a2394f525a9b4f14a2446c427c648df4","PiffSampleEncryptionBox",!0,!1),l.createUUIDBox("8974dbce7be74c5184f97148f9882554","PiffTrackEncryptionBox",!0,!1,function(o){this.default_AlgorithmID=o.readUint24(),this.default_IV_size=o.readUint8(),this.default_KID=l.parseHex16(o)}),l.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f","TfrfBox",!0,!1,function(o){this.fragment_count=o.readUint8(),this.entries=[];for(var c=0;c<this.fragment_count;c++){var f={},m=0,S=0;this.version===1?(m=o.readUint64(),S=o.readUint64()):(m=o.readUint32(),S=o.readUint32()),f.absolute_time=m,f.absolute_duration=S,this.entries.push(f)}}),l.createUUIDBox("6d1d9b0542d544e680e2141daff757b2","TfxdBox",!0,!1,function(o){this.version===1?(this.absolute_time=o.readUint64(),this.duration=o.readUint64()):(this.absolute_time=o.readUint32(),this.duration=o.readUint32())}),l.createFullBoxCtor("vmhd","VideoMediaHeaderBox",function(o){this.graphicsmode=o.readUint16(),this.opcolor=o.readUint16Array(3)}),l.createFullBoxCtor("vpcC","VPCodecConfigurationRecord",function(o){var c;this.version===1?(this.profile=o.readUint8(),this.level=o.readUint8(),c=o.readUint8(),this.bitDepth=c>>4,this.chromaSubsampling=c>>1&7,this.videoFullRangeFlag=c&1,this.colourPrimaries=o.readUint8(),this.transferCharacteristics=o.readUint8(),this.matrixCoefficients=o.readUint8(),this.codecIntializationDataSize=o.readUint16(),this.codecIntializationData=o.readUint8Array(this.codecIntializationDataSize)):(this.profile=o.readUint8(),this.level=o.readUint8(),c=o.readUint8(),this.bitDepth=c>>4&15,this.colorSpace=c&15,c=o.readUint8(),this.chromaSubsampling=c>>4&15,this.transferFunction=c>>1&7,this.videoFullRangeFlag=c&1,this.codecIntializationDataSize=o.readUint16(),this.codecIntializationData=o.readUint8Array(this.codecIntializationDataSize))}),l.createBoxCtor("vttC","WebVTTConfigurationBox",function(o){this.text=o.readString(this.size-this.hdr_size)}),l.createFullBoxCtor("vvcC","VvcConfigurationBox",function(o){var c,f,m={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(k){this.held_bits=k.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(k){this.held_bits=k.readUint16(),this.num_held_bits=16},extract_bits:function(k){var z=this.held_bits>>this.num_held_bits-k&(1<<k)-1;return this.num_held_bits-=k,z}};if(m.stream_read_1_bytes(o),m.extract_bits(5),this.lengthSizeMinusOne=m.extract_bits(2),this.ptl_present_flag=m.extract_bits(1),this.ptl_present_flag){m.stream_read_2_bytes(o),this.ols_idx=m.extract_bits(9),this.num_sublayers=m.extract_bits(3),this.constant_frame_rate=m.extract_bits(2),this.chroma_format_idc=m.extract_bits(2),m.stream_read_1_bytes(o),this.bit_depth_minus8=m.extract_bits(3),m.extract_bits(5);{if(m.stream_read_2_bytes(o),m.extract_bits(2),this.num_bytes_constraint_info=m.extract_bits(6),this.general_profile_idc=m.extract_bits(7),this.general_tier_flag=m.extract_bits(1),this.general_level_idc=o.readUint8(),m.stream_read_1_bytes(o),this.ptl_frame_only_constraint_flag=m.extract_bits(1),this.ptl_multilayer_enabled_flag=m.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(c=0;c<this.num_bytes_constraint_info-1;c++){var S=m.extract_bits(6);m.stream_read_1_bytes(o);var T=m.extract_bits(2);this.general_constraint_info[c]=S<<2|T}this.general_constraint_info[this.num_bytes_constraint_info-1]=m.extract_bits(6)}else m.extract_bits(6);if(this.num_sublayers>1){for(m.stream_read_1_bytes(o),this.ptl_sublayer_present_mask=0,f=this.num_sublayers-2;f>=0;--f){var b=m.extract_bits(1);this.ptl_sublayer_present_mask|=b<<f}for(f=this.num_sublayers;f<=8&&this.num_sublayers>1;++f)m.extract_bits(1);for(this.sublayer_level_idc=[],f=this.num_sublayers-2;f>=0;--f)this.ptl_sublayer_present_mask&1<<f&&(this.sublayer_level_idc[f]=o.readUint8())}if(this.ptl_num_sub_profiles=o.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(c=0;c<this.ptl_num_sub_profiles;c++)this.general_sub_profile_idc.push(o.readUint32())}this.max_picture_width=o.readUint16(),this.max_picture_height=o.readUint16(),this.avg_frame_rate=o.readUint16()}var A=12,I=13;this.nalu_arrays=[];var L=o.readUint8();for(c=0;c<L;c++){var w=[];this.nalu_arrays.push(w),m.stream_read_1_bytes(o),w.completeness=m.extract_bits(1),m.extract_bits(2),w.nalu_type=m.extract_bits(5);var R=1;for(w.nalu_type!=I&&w.nalu_type!=A&&(R=o.readUint16()),f=0;f<R;f++){var M=o.readUint16();w.push({data:o.readUint8Array(M),length:M})}}}),l.createFullBoxCtor("vvnC","VvcNALUConfigBox",function(o){var c=strm.readUint8();this.lengthSizeMinusOne=c&3}),l.SampleEntry.prototype.isVideo=function(){return!1},l.SampleEntry.prototype.isAudio=function(){return!1},l.SampleEntry.prototype.isSubtitle=function(){return!1},l.SampleEntry.prototype.isMetadata=function(){return!1},l.SampleEntry.prototype.isHint=function(){return!1},l.SampleEntry.prototype.getCodec=function(){return this.type.replace(".","")},l.SampleEntry.prototype.getWidth=function(){return""},l.SampleEntry.prototype.getHeight=function(){return""},l.SampleEntry.prototype.getChannelCount=function(){return""},l.SampleEntry.prototype.getSampleRate=function(){return""},l.SampleEntry.prototype.getSampleSize=function(){return""},l.VisualSampleEntry.prototype.isVideo=function(){return!0},l.VisualSampleEntry.prototype.getWidth=function(){return this.width},l.VisualSampleEntry.prototype.getHeight=function(){return this.height},l.AudioSampleEntry.prototype.isAudio=function(){return!0},l.AudioSampleEntry.prototype.getChannelCount=function(){return this.channel_count},l.AudioSampleEntry.prototype.getSampleRate=function(){return this.samplerate},l.AudioSampleEntry.prototype.getSampleSize=function(){return this.samplesize},l.SubtitleSampleEntry.prototype.isSubtitle=function(){return!0},l.MetadataSampleEntry.prototype.isMetadata=function(){return!0},l.decimalToHex=function(o,c){var f=Number(o).toString(16);for(c=typeof c>"u"||c===null?c=2:c;f.length<c;)f="0"+f;return f},l.avc1SampleEntry.prototype.getCodec=l.avc2SampleEntry.prototype.getCodec=l.avc3SampleEntry.prototype.getCodec=l.avc4SampleEntry.prototype.getCodec=function(){var o=l.SampleEntry.prototype.getCodec.call(this);return this.avcC?o+"."+l.decimalToHex(this.avcC.AVCProfileIndication)+l.decimalToHex(this.avcC.profile_compatibility)+l.decimalToHex(this.avcC.AVCLevelIndication):o},l.hev1SampleEntry.prototype.getCodec=l.hvc1SampleEntry.prototype.getCodec=function(){var o,c=l.SampleEntry.prototype.getCodec.call(this);if(this.hvcC){switch(c+=".",this.hvcC.general_profile_space){case 0:c+="";break;case 1:c+="A";break;case 2:c+="B";break;case 3:c+="C";break}c+=this.hvcC.general_profile_idc,c+=".";var f=this.hvcC.general_profile_compatibility,m=0;for(o=0;o<32&&(m|=f&1,o!=31);o++)m<<=1,f>>=1;c+=l.decimalToHex(m,0),c+=".",this.hvcC.general_tier_flag===0?c+="L":c+="H",c+=this.hvcC.general_level_idc;var S=!1,T="";for(o=5;o>=0;o--)(this.hvcC.general_constraint_indicator[o]||S)&&(T="."+l.decimalToHex(this.hvcC.general_constraint_indicator[o],0)+T,S=!0);c+=T}return c},l.vvc1SampleEntry.prototype.getCodec=l.vvi1SampleEntry.prototype.getCodec=function(){var o,c=l.SampleEntry.prototype.getCodec.call(this);if(this.vvcC){c+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?c+=".H":c+=".L",c+=this.vvcC.general_level_idc;var f="";if(this.vvcC.general_constraint_info){var m=[],S=0;S|=this.vvcC.ptl_frame_only_constraint<<7,S|=this.vvcC.ptl_multilayer_enabled<<6;var T;for(o=0;o<this.vvcC.general_constraint_info.length;++o)S|=this.vvcC.general_constraint_info[o]>>2&63,m.push(S),S&&(T=o),S=this.vvcC.general_constraint_info[o]>>2&3;if(T===void 0)f=".CA";else{f=".C";var b="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",A=0,I=0;for(o=0;o<=T;++o)for(A=A<<8|m[o],I+=8;I>=5;){var L=A>>I-5&31;f+=b[L],I-=5,A&=(1<<I)-1}I&&(A<<=5-I,f+=b[A&31])}}c+=f}return c},l.mp4aSampleEntry.prototype.getCodec=function(){var o=l.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var c=this.esds.esd.getOTI(),f=this.esds.esd.getAudioConfig();return o+"."+l.decimalToHex(c)+(f?"."+f:"")}else return o},l.stxtSampleEntry.prototype.getCodec=function(){var o=l.SampleEntry.prototype.getCodec.call(this);return this.mime_format?o+"."+this.mime_format:o},l.vp08SampleEntry.prototype.getCodec=l.vp09SampleEntry.prototype.getCodec=function(){var o=l.SampleEntry.prototype.getCodec.call(this),c=this.vpcC.level;c==0&&(c="00");var f=this.vpcC.bitDepth;return f==8&&(f="08"),o+".0"+this.vpcC.profile+"."+c+"."+f},l.av01SampleEntry.prototype.getCodec=function(){var o=l.SampleEntry.prototype.getCodec.call(this),c=this.av1C.seq_level_idx_0;c<10&&(c="0"+c);var f;return this.av1C.seq_profile===2&&this.av1C.high_bitdepth===1?f=this.av1C.twelve_bit===1?"12":"10":this.av1C.seq_profile<=2&&(f=this.av1C.high_bitdepth===1?"10":"08"),o+"."+this.av1C.seq_profile+"."+c+(this.av1C.seq_tier_0?"H":"M")+"."+f},l.Box.prototype.writeHeader=function(o,c){this.size+=8,this.size>n&&(this.size+=8),this.type==="uuid"&&(this.size+=16),e.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+o.getPosition()+(c||"")),this.size>n?o.writeUint32(1):(this.sizePosition=o.getPosition(),o.writeUint32(this.size)),o.writeString(this.type,null,4),this.type==="uuid"&&o.writeUint8Array(this.uuid),this.size>n&&o.writeUint64(this.size)},l.FullBox.prototype.writeHeader=function(o){this.size+=4,l.Box.prototype.writeHeader.call(this,o," v="+this.version+" f="+this.flags),o.writeUint8(this.version),o.writeUint24(this.flags)},l.Box.prototype.write=function(o){this.type==="mdat"?this.data&&(this.size=this.data.length,this.writeHeader(o),o.writeUint8Array(this.data)):(this.size=this.data?this.data.length:0,this.writeHeader(o),this.data&&o.writeUint8Array(this.data))},l.ContainerBox.prototype.write=function(o){this.size=0,this.writeHeader(o);for(var c=0;c<this.boxes.length;c++)this.boxes[c]&&(this.boxes[c].write(o),this.size+=this.boxes[c].size);e.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},l.TrackReferenceTypeBox.prototype.write=function(o){this.size=this.track_ids.length*4,this.writeHeader(o),o.writeUint32Array(this.track_ids)},l.avcCBox.prototype.write=function(o){var c;for(this.size=7,c=0;c<this.SPS.length;c++)this.size+=2+this.SPS[c].length;for(c=0;c<this.PPS.length;c++)this.size+=2+this.PPS[c].length;for(this.ext&&(this.size+=this.ext.length),this.writeHeader(o),o.writeUint8(this.configurationVersion),o.writeUint8(this.AVCProfileIndication),o.writeUint8(this.profile_compatibility),o.writeUint8(this.AVCLevelIndication),o.writeUint8(this.lengthSizeMinusOne+252),o.writeUint8(this.SPS.length+224),c=0;c<this.SPS.length;c++)o.writeUint16(this.SPS[c].length),o.writeUint8Array(this.SPS[c].nalu);for(o.writeUint8(this.PPS.length),c=0;c<this.PPS.length;c++)o.writeUint16(this.PPS[c].length),o.writeUint8Array(this.PPS[c].nalu);this.ext&&o.writeUint8Array(this.ext)},l.co64Box.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(o),o.writeUint32(this.chunk_offsets.length),c=0;c<this.chunk_offsets.length;c++)o.writeUint64(this.chunk_offsets[c])},l.cslgBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(o),o.writeInt32(this.compositionToDTSShift),o.writeInt32(this.leastDecodeToDisplayDelta),o.writeInt32(this.greatestDecodeToDisplayDelta),o.writeInt32(this.compositionStartTime),o.writeInt32(this.compositionEndTime)},l.cttsBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(o),o.writeUint32(this.sample_counts.length),c=0;c<this.sample_counts.length;c++)o.writeUint32(this.sample_counts[c]),this.version===1?o.writeInt32(this.sample_offsets[c]):o.writeUint32(this.sample_offsets[c])},l.drefBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4,this.writeHeader(o),o.writeUint32(this.entries.length);for(var c=0;c<this.entries.length;c++)this.entries[c].write(o),this.size+=this.entries[c].size;e.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},l.elngBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(o),o.writeString(this.extended_language)},l.elstBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4+12*this.entries.length,this.writeHeader(o),o.writeUint32(this.entries.length);for(var c=0;c<this.entries.length;c++){var f=this.entries[c];o.writeUint32(f.segment_duration),o.writeInt32(f.media_time),o.writeInt16(f.media_rate_integer),o.writeInt16(f.media_rate_fraction)}},l.emsgBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4*4+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(o),o.writeCString(this.scheme_id_uri),o.writeCString(this.value),o.writeUint32(this.timescale),o.writeUint32(this.presentation_time_delta),o.writeUint32(this.event_duration),o.writeUint32(this.id),o.writeUint8Array(this.message_data)},l.ftypBox.prototype.write=function(o){this.size=8+4*this.compatible_brands.length,this.writeHeader(o),o.writeString(this.major_brand,null,4),o.writeUint32(this.minor_version);for(var c=0;c<this.compatible_brands.length;c++)o.writeString(this.compatible_brands[c],null,4)},l.hdlrBox.prototype.write=function(o){this.size=5*4+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(o),o.writeUint32(0),o.writeString(this.handler,null,4),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeCString(this.name)},l.hvcCBox.prototype.write=function(o){var c,f;for(this.size=23,c=0;c<this.nalu_arrays.length;c++)for(this.size+=3,f=0;f<this.nalu_arrays[c].length;f++)this.size+=2+this.nalu_arrays[c][f].data.length;for(this.writeHeader(o),o.writeUint8(this.configurationVersion),o.writeUint8((this.general_profile_space<<6)+(this.general_tier_flag<<5)+this.general_profile_idc),o.writeUint32(this.general_profile_compatibility),o.writeUint8Array(this.general_constraint_indicator),o.writeUint8(this.general_level_idc),o.writeUint16(this.min_spatial_segmentation_idc+(15<<24)),o.writeUint8(this.parallelismType+252),o.writeUint8(this.chroma_format_idc+252),o.writeUint8(this.bit_depth_luma_minus8+248),o.writeUint8(this.bit_depth_chroma_minus8+248),o.writeUint16(this.avgFrameRate),o.writeUint8((this.constantFrameRate<<6)+(this.numTemporalLayers<<3)+(this.temporalIdNested<<2)+this.lengthSizeMinusOne),o.writeUint8(this.nalu_arrays.length),c=0;c<this.nalu_arrays.length;c++)for(o.writeUint8((this.nalu_arrays[c].completeness<<7)+this.nalu_arrays[c].nalu_type),o.writeUint16(this.nalu_arrays[c].length),f=0;f<this.nalu_arrays[c].length;f++)o.writeUint16(this.nalu_arrays[c][f].data.length),o.writeUint8Array(this.nalu_arrays[c][f].data)},l.kindBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value.length+1),this.writeHeader(o),o.writeCString(this.schemeURI),o.writeCString(this.value)},l.mdhdBox.prototype.write=function(o){this.size=4*4+2*2,this.flags=0,this.version=0,this.writeHeader(o),o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.timescale),o.writeUint32(this.duration),o.writeUint16(this.language),o.writeUint16(0)},l.mehdBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4,this.writeHeader(o),o.writeUint32(this.fragment_duration)},l.mfhdBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4,this.writeHeader(o),o.writeUint32(this.sequence_number)},l.mvhdBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=23*4+2*2,this.writeHeader(o),o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.timescale),o.writeUint32(this.duration),o.writeUint32(this.rate),o.writeUint16(this.volume<<8),o.writeUint16(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32Array(this.matrix),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(this.next_track_id)},l.SampleEntry.prototype.writeHeader=function(o){this.size=8,l.Box.prototype.writeHeader.call(this,o),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint16(this.data_reference_index)},l.SampleEntry.prototype.writeFooter=function(o){for(var c=0;c<this.boxes.length;c++)this.boxes[c].write(o),this.size+=this.boxes[c].size;e.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},l.SampleEntry.prototype.write=function(o){this.writeHeader(o),o.writeUint8Array(this.data),this.size+=this.data.length,e.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},l.VisualSampleEntry.prototype.write=function(o){this.writeHeader(o),this.size+=2*7+6*4+32,o.writeUint16(0),o.writeUint16(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint16(this.width),o.writeUint16(this.height),o.writeUint32(this.horizresolution),o.writeUint32(this.vertresolution),o.writeUint32(0),o.writeUint16(this.frame_count),o.writeUint8(Math.min(31,this.compressorname.length)),o.writeString(this.compressorname,null,31),o.writeUint16(this.depth),o.writeInt16(-1),this.writeFooter(o)},l.AudioSampleEntry.prototype.write=function(o){this.writeHeader(o),this.size+=2*4+3*4,o.writeUint32(0),o.writeUint32(0),o.writeUint16(this.channel_count),o.writeUint16(this.samplesize),o.writeUint16(0),o.writeUint16(0),o.writeUint32(this.samplerate<<16),this.writeFooter(o)},l.stppSampleEntry.prototype.write=function(o){this.writeHeader(o),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,o.writeCString(this.namespace),o.writeCString(this.schema_location),o.writeCString(this.auxiliary_mime_types),this.writeFooter(o)},l.SampleGroupEntry.prototype.write=function(o){o.writeUint8Array(this.data)},l.sbgpBox.prototype.write=function(o){this.version=1,this.flags=0,this.size=12+8*this.entries.length,this.writeHeader(o),o.writeString(this.grouping_type,null,4),o.writeUint32(this.grouping_type_parameter),o.writeUint32(this.entries.length);for(var c=0;c<this.entries.length;c++){var f=this.entries[c];o.writeInt32(f.sample_count),o.writeInt32(f.group_description_index)}},l.sgpdBox.prototype.write=function(o){var c,f;for(this.flags=0,this.size=12,c=0;c<this.entries.length;c++)f=this.entries[c],this.version===1&&(this.default_length===0&&(this.size+=4),this.size+=f.data.length);for(this.writeHeader(o),o.writeString(this.grouping_type,null,4),this.version===1&&o.writeUint32(this.default_length),this.version>=2&&o.writeUint32(this.default_sample_description_index),o.writeUint32(this.entries.length),c=0;c<this.entries.length;c++)f=this.entries[c],this.version===1&&this.default_length===0&&o.writeUint32(f.description_length),f.write(o)},l.sidxBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4*4+2+2+12*this.references.length,this.writeHeader(o),o.writeUint32(this.reference_ID),o.writeUint32(this.timescale),o.writeUint32(this.earliest_presentation_time),o.writeUint32(this.first_offset),o.writeUint16(0),o.writeUint16(this.references.length);for(var c=0;c<this.references.length;c++){var f=this.references[c];o.writeUint32(f.reference_type<<31|f.referenced_size),o.writeUint32(f.subsegment_duration),o.writeUint32(f.starts_with_SAP<<31|f.SAP_type<<28|f.SAP_delta_time)}},l.smhdBox.prototype.write=function(o){this.version=0,this.flags=1,this.size=4,this.writeHeader(o),o.writeUint16(this.balance),o.writeUint16(0)},l.stcoBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(o),o.writeUint32(this.chunk_offsets.length),o.writeUint32Array(this.chunk_offsets)},l.stscBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(o),o.writeUint32(this.first_chunk.length),c=0;c<this.first_chunk.length;c++)o.writeUint32(this.first_chunk[c]),o.writeUint32(this.samples_per_chunk[c]),o.writeUint32(this.sample_description_index[c])},l.stsdBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=0,this.writeHeader(o),o.writeUint32(this.entries.length),this.size+=4,c=0;c<this.entries.length;c++)this.entries[c].write(o),this.size+=this.entries[c].size;e.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},l.stshBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(o),o.writeUint32(this.shadowed_sample_numbers.length),c=0;c<this.shadowed_sample_numbers.length;c++)o.writeUint32(this.shadowed_sample_numbers[c]),o.writeUint32(this.sync_sample_numbers[c])},l.stssBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(o),o.writeUint32(this.sample_numbers.length),o.writeUint32Array(this.sample_numbers)},l.stszBox.prototype.write=function(o){var c,f=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0)for(c=0;c+1<this.sample_sizes.length;)if(this.sample_sizes[c+1]!==this.sample_sizes[0]){f=!1;break}else c++;else f=!1;this.size=8,f||(this.size+=4*this.sample_sizes.length),this.writeHeader(o),f?o.writeUint32(this.sample_sizes[0]):o.writeUint32(0),o.writeUint32(this.sample_sizes.length),f||o.writeUint32Array(this.sample_sizes)},l.sttsBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(o),o.writeUint32(this.sample_counts.length),c=0;c<this.sample_counts.length;c++)o.writeUint32(this.sample_counts[c]),o.writeUint32(this.sample_deltas[c])},l.tfdtBox.prototype.write=function(o){var c=Math.pow(2,32)-1;this.version=this.baseMediaDecodeTime>c?1:0,this.flags=0,this.size=4,this.version===1&&(this.size+=4),this.writeHeader(o),this.version===1?o.writeUint64(this.baseMediaDecodeTime):o.writeUint32(this.baseMediaDecodeTime)},l.tfhdBox.prototype.write=function(o){this.version=0,this.size=4,this.flags&l.TFHD_FLAG_BASE_DATA_OFFSET&&(this.size+=8),this.flags&l.TFHD_FLAG_SAMPLE_DESC&&(this.size+=4),this.flags&l.TFHD_FLAG_SAMPLE_DUR&&(this.size+=4),this.flags&l.TFHD_FLAG_SAMPLE_SIZE&&(this.size+=4),this.flags&l.TFHD_FLAG_SAMPLE_FLAGS&&(this.size+=4),this.writeHeader(o),o.writeUint32(this.track_id),this.flags&l.TFHD_FLAG_BASE_DATA_OFFSET&&o.writeUint64(this.base_data_offset),this.flags&l.TFHD_FLAG_SAMPLE_DESC&&o.writeUint32(this.default_sample_description_index),this.flags&l.TFHD_FLAG_SAMPLE_DUR&&o.writeUint32(this.default_sample_duration),this.flags&l.TFHD_FLAG_SAMPLE_SIZE&&o.writeUint32(this.default_sample_size),this.flags&l.TFHD_FLAG_SAMPLE_FLAGS&&o.writeUint32(this.default_sample_flags)},l.tkhdBox.prototype.write=function(o){this.version=0,this.size=4*18+2*4,this.writeHeader(o),o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.track_id),o.writeUint32(0),o.writeUint32(this.duration),o.writeUint32(0),o.writeUint32(0),o.writeInt16(this.layer),o.writeInt16(this.alternate_group),o.writeInt16(this.volume<<8),o.writeUint16(0),o.writeInt32Array(this.matrix),o.writeUint32(this.width),o.writeUint32(this.height)},l.trexBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(o),o.writeUint32(this.track_id),o.writeUint32(this.default_sample_description_index),o.writeUint32(this.default_sample_duration),o.writeUint32(this.default_sample_size),o.writeUint32(this.default_sample_flags)},l.trunBox.prototype.write=function(o){this.version=0,this.size=4,this.flags&l.TRUN_FLAGS_DATA_OFFSET&&(this.size+=4),this.flags&l.TRUN_FLAGS_FIRST_FLAG&&(this.size+=4),this.flags&l.TRUN_FLAGS_DURATION&&(this.size+=4*this.sample_duration.length),this.flags&l.TRUN_FLAGS_SIZE&&(this.size+=4*this.sample_size.length),this.flags&l.TRUN_FLAGS_FLAGS&&(this.size+=4*this.sample_flags.length),this.flags&l.TRUN_FLAGS_CTS_OFFSET&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(o),o.writeUint32(this.sample_count),this.flags&l.TRUN_FLAGS_DATA_OFFSET&&(this.data_offset_position=o.getPosition(),o.writeInt32(this.data_offset)),this.flags&l.TRUN_FLAGS_FIRST_FLAG&&o.writeUint32(this.first_sample_flags);for(var c=0;c<this.sample_count;c++)this.flags&l.TRUN_FLAGS_DURATION&&o.writeUint32(this.sample_duration[c]),this.flags&l.TRUN_FLAGS_SIZE&&o.writeUint32(this.sample_size[c]),this.flags&l.TRUN_FLAGS_FLAGS&&o.writeUint32(this.sample_flags[c]),this.flags&l.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?o.writeUint32(this.sample_composition_time_offset[c]):o.writeInt32(this.sample_composition_time_offset[c]))},l["url Box"].prototype.write=function(o){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(o),this.location&&o.writeCString(this.location)},l["urn Box"].prototype.write=function(o){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(o),o.writeCString(this.name),this.location&&o.writeCString(this.location)},l.vmhdBox.prototype.write=function(o){this.version=0,this.flags=1,this.size=8,this.writeHeader(o),o.writeUint16(this.graphicsmode),o.writeUint16Array(this.opcolor)},l.cttsBox.prototype.unpack=function(o){var c,f,m;for(m=0,c=0;c<this.sample_counts.length;c++)for(f=0;f<this.sample_counts[c];f++)o[m].pts=o[m].dts+this.sample_offsets[c],m++},l.sttsBox.prototype.unpack=function(o){var c,f,m;for(m=0,c=0;c<this.sample_counts.length;c++)for(f=0;f<this.sample_counts[c];f++)m===0?o[m].dts=0:o[m].dts=o[m-1].dts+this.sample_deltas[c],m++},l.stcoBox.prototype.unpack=function(o){var c;for(c=0;c<this.chunk_offsets.length;c++)o[c].offset=this.chunk_offsets[c]},l.stscBox.prototype.unpack=function(o){var c,f,m,S,T;for(S=0,T=0,c=0;c<this.first_chunk.length;c++)for(f=0;f<(c+1<this.first_chunk.length?this.first_chunk[c+1]:1/0);f++)for(T++,m=0;m<this.samples_per_chunk[c];m++){if(o[S])o[S].description_index=this.sample_description_index[c],o[S].chunk_index=T;else return;S++}},l.stszBox.prototype.unpack=function(o){var c;for(c=0;c<this.sample_sizes.length;c++)o[c].size=this.sample_sizes[c]},l.DIFF_BOXES_PROP_NAMES=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],l.DIFF_PRIMITIVE_ARRAY_PROP_NAMES=["compatible_brands","matrix","opcolor","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"],l.boxEqualFields=function(o,c){if(o&&!c)return!1;var f;for(f in o)if(!(l.DIFF_BOXES_PROP_NAMES.indexOf(f)>-1)){if(o[f]instanceof l.Box||c[f]instanceof l.Box)continue;if(typeof o[f]>"u"||typeof c[f]>"u")continue;if(typeof o[f]=="function"||typeof c[f]=="function")continue;if(o.subBoxNames&&o.subBoxNames.indexOf(f.slice(0,4))>-1||c.subBoxNames&&c.subBoxNames.indexOf(f.slice(0,4))>-1)continue;if(f==="data"||f==="start"||f==="size"||f==="creation_time"||f==="modification_time")continue;if(l.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(f)>-1)continue;if(o[f]!==c[f])return!1}return!0},l.boxEqual=function(o,c){if(!l.boxEqualFields(o,c))return!1;for(var f=0;f<l.DIFF_BOXES_PROP_NAMES.length;f++){var m=l.DIFF_BOXES_PROP_NAMES[f];if(o[m]&&c[m]&&!l.boxEqual(o[m],c[m]))return!1}return!0};var g=function(){};g.prototype.parseSample=function(o){var c,f,m=new t(o.buffer);for(c=[];!m.isEos();)f=l.parseOneBox(m,!1),f.code===l.OK&&f.box.type==="vttc"&&c.push(f.box);return c},g.prototype.getText=function(o,c,f){function m(L,w,R){return R=R||"0",L=L+"",L.length>=w?L:new Array(w-L.length+1).join(R)+L}function S(L){var w=Math.floor(L/3600),R=Math.floor((L-w*3600)/60),M=Math.floor(L-w*3600-R*60),k=Math.floor((L-w*3600-R*60-M)*1e3);return""+m(w,2)+":"+m(R,2)+":"+m(M,2)+"."+m(k,3)}for(var T=this.parseSample(f),b="",A=0;A<T.length;A++){var I=T[A];b+=S(o)+" --> "+S(c)+`\r
|
|
145
|
+
`,b+=I.payl.text}return b};var y=function(){};y.prototype.parseSample=function(o){var c={},f;c.resources=[];var m=new t(o.data.buffer);if(!o.subsamples||o.subsamples.length===0)c.documentString=m.readString(o.data.length);else if(c.documentString=m.readString(o.subsamples[0].size),o.subsamples.length>1)for(f=1;f<o.subsamples.length;f++)c.resources[f]=m.readUint8Array(o.subsamples[f].size);return typeof DOMParser<"u"&&(c.document=new DOMParser().parseFromString(c.documentString,"application/xml")),c};var x=function(){};x.prototype.parseSample=function(o){var c,f=new t(o.data.buffer);return c=f.readString(o.data.length),c},x.prototype.parseConfig=function(o){var c,f=new t(o.buffer);return f.readUint32(),c=f.readCString(),c},r.VTTin4Parser=g,r.XMLSubtitlein4Parser=y,r.Textin4Parser=x;var v=function(o){this.stream=o||new a,this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.onMoovStart=null,this.moovStartSent=!1,this.onReady=null,this.readySent=!1,this.onSegment=null,this.onSamples=null,this.onError=null,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.items=[],this.entity_groups=[],this.onSidx=null,this.sidxSent=!1};v.prototype.setSegmentOptions=function(o,c,f){var m=this.getTrackById(o);if(m){var S={};this.fragmentedTracks.push(S),S.id=o,S.user=c,S.trak=m,m.nextSample=0,S.segmentStream=null,S.nb_samples=1e3,S.rapAlignement=!0,f&&(f.nbSamples&&(S.nb_samples=f.nbSamples),f.rapAlignement&&(S.rapAlignement=f.rapAlignement))}},v.prototype.unsetSegmentOptions=function(o){for(var c=-1,f=0;f<this.fragmentedTracks.length;f++){var m=this.fragmentedTracks[f];m.id==o&&(c=f)}c>-1&&this.fragmentedTracks.splice(c,1)},v.prototype.setExtractionOptions=function(o,c,f){var m=this.getTrackById(o);if(m){var S={};this.extractedTracks.push(S),S.id=o,S.user=c,S.trak=m,m.nextSample=0,S.nb_samples=1e3,S.samples=[],f&&f.nbSamples&&(S.nb_samples=f.nbSamples)}},v.prototype.unsetExtractionOptions=function(o){for(var c=-1,f=0;f<this.extractedTracks.length;f++){var m=this.extractedTracks[f];m.id==o&&(c=f)}c>-1&&this.extractedTracks.splice(c,1)},v.prototype.parse=function(){var o,c,f=!1;if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else if(this.saveParsePosition&&this.saveParsePosition(),o=l.parseOneBox(this.stream,f),o.code===l.ERR_NOT_ENOUGH_DATA)if(this.processIncompleteBox){if(this.processIncompleteBox(o))continue;return}else return;else{var m;switch(c=o.box,m=c.type!=="uuid"?c.type:c.uuid,this.boxes.push(c),m){case"mdat":this.mdats.push(c);break;case"moof":this.moofs.push(c);break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[m]!==void 0&&e.warn("ISOFile","Duplicate Box of type: "+m+", overriding previous occurrence"),this[m]=c;break}this.updateUsedBytes&&this.updateUsedBytes(c,o)}},v.prototype.checkBuffer=function(o){if(o==null)throw"Buffer must be defined and non empty";if(o.fileStart===void 0)throw"Buffer must have a fileStart property";return o.byteLength===0?(e.warn("ISOFile","Ignoring empty buffer (fileStart: "+o.fileStart+")"),this.stream.logBufferLevel(),!1):(e.info("ISOFile","Processing buffer (fileStart: "+o.fileStart+")"),o.usedBytes=0,this.stream.insertBuffer(o),this.stream.logBufferLevel(),this.stream.initialized()?!0:(e.warn("ISOFile","Not ready to start parsing"),!1))},v.prototype.appendBuffer=function(o,c){var f;if(this.checkBuffer(o))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(c),this.nextSeekPosition?(f=this.nextSeekPosition,this.nextSeekPosition=void 0):f=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(f=this.stream.getEndFilePositionAfter(f))):this.nextParsePosition?f=this.nextParsePosition:f=0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(e.info("ISOFile","Done processing buffer (fileStart: "+o.fileStart+") - next buffer to fetch should have a fileStart position of "+f),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),e.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),f},v.prototype.getInfo=function(){var o,c,f={},m,S,T,b,A=new Date("1904-01-01T00:00:00Z").getTime();if(this.moov)for(f.hasMoov=!0,f.duration=this.moov.mvhd.duration,f.timescale=this.moov.mvhd.timescale,f.isFragmented=this.moov.mvex!=null,f.isFragmented&&this.moov.mvex.mehd&&(f.fragment_duration=this.moov.mvex.mehd.fragment_duration),f.isProgressive=this.isProgressive,f.hasIOD=this.moov.iods!=null,f.brands=[],f.brands.push(this.ftyp.major_brand),f.brands=f.brands.concat(this.ftyp.compatible_brands),f.created=new Date(A+this.moov.mvhd.creation_time*1e3),f.modified=new Date(A+this.moov.mvhd.modification_time*1e3),f.tracks=[],f.audioTracks=[],f.videoTracks=[],f.subtitleTracks=[],f.metadataTracks=[],f.hintTracks=[],f.otherTracks=[],o=0;o<this.moov.traks.length;o++){if(m=this.moov.traks[o],b=m.mdia.minf.stbl.stsd.entries[0],S={},f.tracks.push(S),S.id=m.tkhd.track_id,S.name=m.mdia.hdlr.name,S.references=[],m.tref)for(c=0;c<m.tref.boxes.length;c++)T={},S.references.push(T),T.type=m.tref.boxes[c].type,T.track_ids=m.tref.boxes[c].track_ids;m.edts&&(S.edits=m.edts.elst.entries),S.created=new Date(A+m.tkhd.creation_time*1e3),S.modified=new Date(A+m.tkhd.modification_time*1e3),S.movie_duration=m.tkhd.duration,S.movie_timescale=f.timescale,S.layer=m.tkhd.layer,S.alternate_group=m.tkhd.alternate_group,S.volume=m.tkhd.volume,S.matrix=m.tkhd.matrix,S.track_width=m.tkhd.width/65536,S.track_height=m.tkhd.height/65536,S.timescale=m.mdia.mdhd.timescale,S.cts_shift=m.mdia.minf.stbl.cslg,S.duration=m.mdia.mdhd.duration,S.samples_duration=m.samples_duration,S.codec=b.getCodec(),S.kind=m.udta&&m.udta.kinds.length?m.udta.kinds[0]:{schemeURI:"",value:""},S.language=m.mdia.elng?m.mdia.elng.extended_language:m.mdia.mdhd.languageString,S.nb_samples=m.samples.length,S.size=m.samples_size,S.bitrate=S.size*8*S.timescale/S.samples_duration,b.isAudio()?(S.type="audio",f.audioTracks.push(S),S.audio={},S.audio.sample_rate=b.getSampleRate(),S.audio.channel_count=b.getChannelCount(),S.audio.sample_size=b.getSampleSize()):b.isVideo()?(S.type="video",f.videoTracks.push(S),S.video={},S.video.width=b.getWidth(),S.video.height=b.getHeight()):b.isSubtitle()?(S.type="subtitles",f.subtitleTracks.push(S)):b.isHint()?(S.type="metadata",f.hintTracks.push(S)):b.isMetadata()?(S.type="metadata",f.metadataTracks.push(S)):(S.type="metadata",f.otherTracks.push(S))}else f.hasMoov=!1;if(f.mime="",f.hasMoov&&f.tracks){for(f.videoTracks&&f.videoTracks.length>0?f.mime+='video/mp4; codecs="':f.audioTracks&&f.audioTracks.length>0?f.mime+='audio/mp4; codecs="':f.mime+='application/mp4; codecs="',o=0;o<f.tracks.length;o++)o!==0&&(f.mime+=","),f.mime+=f.tracks[o].codec;f.mime+='"; profiles="',f.mime+=this.ftyp.compatible_brands.join(),f.mime+='"'}return f},v.prototype.setNextSeekPositionFromSample=function(o){o&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(o.offset+o.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=o.offset+o.alreadyRead)},v.prototype.processSamples=function(o){var c,f;if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==null)for(c=0;c<this.fragmentedTracks.length;c++){var m=this.fragmentedTracks[c];for(f=m.trak;f.nextSample<f.samples.length&&this.sampleProcessingStarted;){e.debug("ISOFile","Creating media fragment on track #"+m.id+" for sample "+f.nextSample);var S=this.createFragment(m.id,f.nextSample,m.segmentStream);if(S)m.segmentStream=S,f.nextSample++;else break;if((f.nextSample%m.nb_samples===0||o||f.nextSample>=f.samples.length)&&(e.info("ISOFile","Sending fragmented data on track #"+m.id+" for samples ["+Math.max(0,f.nextSample-m.nb_samples)+","+(f.nextSample-1)+"]"),e.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(m.id,m.user,m.segmentStream.buffer,f.nextSample,o||f.nextSample>=f.samples.length),m.segmentStream=null,m!==this.fragmentedTracks[c]))break}}if(this.onSamples!==null)for(c=0;c<this.extractedTracks.length;c++){var T=this.extractedTracks[c];for(f=T.trak;f.nextSample<f.samples.length&&this.sampleProcessingStarted;){e.debug("ISOFile","Exporting on track #"+T.id+" sample #"+f.nextSample);var b=this.getSample(f,f.nextSample);if(b)f.nextSample++,T.samples.push(b);else{this.setNextSeekPositionFromSample(f.samples[f.nextSample]);break}if((f.nextSample%T.nb_samples===0||f.nextSample>=f.samples.length)&&(e.debug("ISOFile","Sending samples on track #"+T.id+" for sample "+f.nextSample),this.onSamples&&this.onSamples(T.id,T.user,T.samples),T.samples=[],T!==this.extractedTracks[c]))break}}}},v.prototype.getBox=function(o){var c=this.getBoxes(o,!0);return c.length?c[0]:null},v.prototype.getBoxes=function(o,c){var f=[];return v._sweep.call(this,o,f,c),f},v._sweep=function(o,c,f){this.type&&this.type==o&&c.push(this);for(var m in this.boxes){if(c.length&&f)return;v._sweep.call(this.boxes[m],o,c,f)}},v.prototype.getTrackSamplesInfo=function(o){var c=this.getTrackById(o);if(c)return c.samples},v.prototype.getTrackSample=function(o,c){var f=this.getTrackById(o),m=this.getSample(f,c);return m},v.prototype.releaseUsedSamples=function(o,c){var f=0,m=this.getTrackById(o);m.lastValidSample||(m.lastValidSample=0);for(var S=m.lastValidSample;S<c;S++)f+=this.releaseSample(m,S);e.info("ISOFile","Track #"+o+" released samples up to "+c+" (released size: "+f+", remaining: "+this.samplesDataSize+")"),m.lastValidSample=c},v.prototype.start=function(){this.sampleProcessingStarted=!0,this.processSamples(!1)},v.prototype.stop=function(){this.sampleProcessingStarted=!1},v.prototype.flush=function(){e.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)},v.prototype.seekTrack=function(o,c,f){var m,S,T=1/0,b=0,A=0,I;if(f.samples.length===0)return e.info("ISOFile","No sample in track, cannot seek! Using time "+e.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(m=0;m<f.samples.length;m++){if(S=f.samples[m],m===0)A=0,I=S.timescale;else if(S.cts>o*S.timescale){A=m-1;break}c&&S.is_sync&&(b=m)}for(c&&(A=b),o=f.samples[A].cts,f.nextSample=A;f.samples[A].alreadyRead===f.samples[A].size&&f.samples[A+1];)A++;return T=f.samples[A].offset+f.samples[A].alreadyRead,e.info("ISOFile","Seeking to "+(c?"RAP":"")+" sample #"+f.nextSample+" on track "+f.tkhd.track_id+", time "+e.getDurationString(o,I)+" and offset: "+T),{offset:T,time:o/I}},v.prototype.getTrackDuration=function(o){var c;return o.samples?(c=o.samples[o.samples.length-1],(c.cts+c.duration)/c.timescale):1/0},v.prototype.seek=function(o,c){var f=this.moov,m,S,T,b={offset:1/0,time:1/0};if(this.moov){for(T=0;T<f.traks.length;T++)m=f.traks[T],!(o>this.getTrackDuration(m))&&(S=this.seekTrack(o,c,m),S.offset<b.offset&&(b.offset=S.offset),S.time<b.time&&(b.time=S.time));return e.info("ISOFile","Seeking at time "+e.getDurationString(b.time,1)+" needs a buffer with a fileStart position of "+b.offset),b.offset===1/0?b={offset:this.nextParsePosition,time:0}:b.offset=this.stream.getEndFilePositionAfter(b.offset),e.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+b.offset),b}else throw"Cannot seek: moov not received!"},v.prototype.equal=function(o){for(var c=0;c<this.boxes.length&&c<o.boxes.length;){var f=this.boxes[c],m=o.boxes[c];if(!l.boxEqual(f,m))return!1;c++}return!0},r.ISOFile=v,v.prototype.lastBoxStartPosition=0,v.prototype.parsingMdat=null,v.prototype.nextParsePosition=0,v.prototype.discardMdatData=!1,v.prototype.processIncompleteBox=function(o){var c,f,m;return o.type==="mdat"?(c=new l[o.type+"Box"](o.size),this.parsingMdat=c,this.boxes.push(c),this.mdats.push(c),c.start=o.start,c.hdr_size=o.hdr_size,this.stream.addUsedBytes(c.hdr_size),this.lastBoxStartPosition=c.start+c.size,m=this.stream.seek(c.start+c.size,!1,this.discardMdatData),m?(this.parsingMdat=null,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=c.start+c.size,!1)):(o.type==="moov"&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),f=this.stream.mergeNextBuffer?this.stream.mergeNextBuffer():!1,f?(this.nextParsePosition=this.stream.getEndPosition(),!0):(o.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+o.size:this.nextParsePosition=this.stream.getEndPosition(),!1))},v.prototype.hasIncompleteMdat=function(){return this.parsingMdat!==null},v.prototype.processIncompleteMdat=function(){var o,c;return o=this.parsingMdat,c=this.stream.seek(o.start+o.size,!1,this.discardMdatData),c?(e.debug("ISOFile","Found 'mdat' end in buffered data"),this.parsingMdat=null,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)},v.prototype.restoreParsePosition=function(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)},v.prototype.saveParsePosition=function(){this.lastBoxStartPosition=this.stream.getPosition()},v.prototype.updateUsedBytes=function(o,c){this.stream.addUsedBytes&&(o.type==="mdat"?(this.stream.addUsedBytes(o.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(o.size-o.hdr_size)):this.stream.addUsedBytes(o.size))},v.prototype.add=l.Box.prototype.add,v.prototype.addBox=l.Box.prototype.addBox,v.prototype.init=function(o){var c=o||{};this.add("ftyp").set("major_brand",c.brands&&c.brands[0]||"iso4").set("minor_version",0).set("compatible_brands",c.brands||["iso4"]);var f=this.add("moov");return f.add("mvhd").set("timescale",c.timescale||600).set("rate",c.rate||65536).set("creation_time",0).set("modification_time",0).set("duration",c.duration||0).set("volume",c.width?0:256).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("next_track_id",1),f.add("mvex"),this},v.prototype.addTrack=function(o){this.moov||this.init(o);var c=o||{};c.width=c.width||320,c.height=c.height||320,c.id=c.id||this.moov.mvhd.next_track_id,c.type=c.type||"avc1";var f=this.moov.add("trak");this.moov.mvhd.next_track_id=c.id+1,f.add("tkhd").set("flags",l.TKHD_FLAG_ENABLED|l.TKHD_FLAG_IN_MOVIE|l.TKHD_FLAG_IN_PREVIEW).set("creation_time",0).set("modification_time",0).set("track_id",c.id).set("duration",c.duration||0).set("layer",c.layer||0).set("alternate_group",0).set("volume",1).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("width",c.width<<16).set("height",c.height<<16);var m=f.add("mdia");m.add("mdhd").set("creation_time",0).set("modification_time",0).set("timescale",c.timescale||1).set("duration",c.media_duration||0).set("language",c.language||"und"),m.add("hdlr").set("handler",c.hdlr||"vide").set("name",c.name||"Track created with MP4Box.js"),m.add("elng").set("extended_language",c.language||"fr-FR");var S=m.add("minf");if(l[c.type+"SampleEntry"]!==void 0){var T=new l[c.type+"SampleEntry"];T.data_reference_index=1;var b="";for(var A in l.sampleEntryCodes)for(var I=l.sampleEntryCodes[A],L=0;L<I.length;L++)if(I.indexOf(c.type)>-1){b=A;break}switch(b){case"Visual":if(S.add("vmhd").set("graphicsmode",0).set("opcolor",[0,0,0]),T.set("width",c.width).set("height",c.height).set("horizresolution",72<<16).set("vertresolution",72<<16).set("frame_count",1).set("compressorname",c.type+" Compressor").set("depth",24),c.avcDecoderConfigRecord){var w=new l.avcCBox;w.parse(new t(c.avcDecoderConfigRecord)),T.addBox(w)}else if(c.hevcDecoderConfigRecord){var R=new l.hvcCBox;R.parse(new t(c.hevcDecoderConfigRecord)),T.addBox(R)}break;case"Audio":S.add("smhd").set("balance",c.balance||0),T.set("channel_count",c.channel_count||2).set("samplesize",c.samplesize||16).set("samplerate",c.samplerate||65536);break;case"Hint":S.add("hmhd");break;case"Subtitle":switch(S.add("sthd"),c.type){case"stpp":T.set("namespace",c.namespace||"nonamespace").set("schema_location",c.schema_location||"").set("auxiliary_mime_types",c.auxiliary_mime_types||"");break}break;case"Metadata":S.add("nmhd");break;case"System":S.add("nmhd");break;default:S.add("nmhd");break}c.description&&T.addBox(c.description),c.description_boxes&&c.description_boxes.forEach(function(k){T.addBox(k)}),S.add("dinf").add("dref").addEntry(new l["url Box"]().set("flags",1));var M=S.add("stbl");return M.add("stsd").addEntry(T),M.add("stts").set("sample_counts",[]).set("sample_deltas",[]),M.add("stsc").set("first_chunk",[]).set("samples_per_chunk",[]).set("sample_description_index",[]),M.add("stco").set("chunk_offsets",[]),M.add("stsz").set("sample_sizes",[]),this.moov.mvex.add("trex").set("track_id",c.id).set("default_sample_description_index",c.default_sample_description_index||1).set("default_sample_duration",c.default_sample_duration||0).set("default_sample_size",c.default_sample_size||0).set("default_sample_flags",c.default_sample_flags||0),this.buildTrakSampleLists(f),c.id}},l.Box.prototype.computeSize=function(o){var c=o||new s;c.endianness=s.BIG_ENDIAN,this.write(c)},v.prototype.addSample=function(o,c,f){var m=f||{},S={},T=this.getTrackById(o);if(T!==null){S.number=T.samples.length,S.track_id=T.tkhd.track_id,S.timescale=T.mdia.mdhd.timescale,S.description_index=m.sample_description_index?m.sample_description_index-1:0,S.description=T.mdia.minf.stbl.stsd.entries[S.description_index],S.data=c,S.size=c.byteLength,S.alreadyRead=S.size,S.duration=m.duration||1,S.cts=m.cts||0,S.dts=m.dts||0,S.is_sync=m.is_sync||!1,S.is_leading=m.is_leading||0,S.depends_on=m.depends_on||0,S.is_depended_on=m.is_depended_on||0,S.has_redundancy=m.has_redundancy||0,S.degradation_priority=m.degradation_priority||0,S.offset=0,S.subsamples=m.subsamples,T.samples.push(S),T.samples_size+=S.size,T.samples_duration+=S.duration,T.first_dts===void 0&&(T.first_dts=m.dts),this.processSamples();var b=this.createSingleSampleMoof(S);return this.addBox(b),b.computeSize(),b.trafs[0].truns[0].data_offset=b.size+8,this.add("mdat").data=new Uint8Array(c),S}},v.prototype.createSingleSampleMoof=function(o){var c=0;o.is_sync?c=1<<25:c=65536;var f=new l.moofBox;f.add("mfhd").set("sequence_number",this.nextMoofNumber),this.nextMoofNumber++;var m=f.add("traf"),S=this.getTrackById(o.track_id);return m.add("tfhd").set("track_id",o.track_id).set("flags",l.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),m.add("tfdt").set("baseMediaDecodeTime",o.dts-(S.first_dts||0)),m.add("trun").set("flags",l.TRUN_FLAGS_DATA_OFFSET|l.TRUN_FLAGS_DURATION|l.TRUN_FLAGS_SIZE|l.TRUN_FLAGS_FLAGS|l.TRUN_FLAGS_CTS_OFFSET).set("data_offset",0).set("first_sample_flags",0).set("sample_count",1).set("sample_duration",[o.duration]).set("sample_size",[o.size]).set("sample_flags",[c]).set("sample_composition_time_offset",[o.cts-o.dts]),f},v.prototype.lastMoofIndex=0,v.prototype.samplesDataSize=0,v.prototype.resetTables=function(){var o,c,f,m,S,T,b,A;for(this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0,o=0;o<this.moov.traks.length;o++){c=this.moov.traks[o],c.tkhd.duration=0,c.mdia.mdhd.duration=0,f=c.mdia.minf.stbl.stco||c.mdia.minf.stbl.co64,f.chunk_offsets=[],m=c.mdia.minf.stbl.stsc,m.first_chunk=[],m.samples_per_chunk=[],m.sample_description_index=[],S=c.mdia.minf.stbl.stsz||c.mdia.minf.stbl.stz2,S.sample_sizes=[],T=c.mdia.minf.stbl.stts,T.sample_counts=[],T.sample_deltas=[],b=c.mdia.minf.stbl.ctts,b&&(b.sample_counts=[],b.sample_offsets=[]),A=c.mdia.minf.stbl.stss;var I=c.mdia.minf.stbl.boxes.indexOf(A);I!=-1&&(c.mdia.minf.stbl.boxes[I]=null)}},v.initSampleGroups=function(o,c,f,m,S){var T,b,A,I;function L(w,R,M){this.grouping_type=w,this.grouping_type_parameter=R,this.sbgp=M,this.last_sample_in_run=-1,this.entry_index=-1}for(c&&(c.sample_groups_info=[]),o.sample_groups_info||(o.sample_groups_info=[]),b=0;b<f.length;b++){for(I=f[b].grouping_type+"/"+f[b].grouping_type_parameter,A=new L(f[b].grouping_type,f[b].grouping_type_parameter,f[b]),c&&(c.sample_groups_info[I]=A),o.sample_groups_info[I]||(o.sample_groups_info[I]=A),T=0;T<m.length;T++)m[T].grouping_type===f[b].grouping_type&&(A.description=m[T],A.description.used=!0);if(S)for(T=0;T<S.length;T++)S[T].grouping_type===f[b].grouping_type&&(A.fragment_description=S[T],A.fragment_description.used=!0,A.is_fragment=!0)}if(c){if(S)for(b=0;b<S.length;b++)!S[b].used&&S[b].version>=2&&(I=S[b].grouping_type+"/0",A=new L(S[b].grouping_type,0),A.is_fragment=!0,c.sample_groups_info[I]||(c.sample_groups_info[I]=A))}else for(b=0;b<m.length;b++)!m[b].used&&m[b].version>=2&&(I=m[b].grouping_type+"/0",A=new L(m[b].grouping_type,0),o.sample_groups_info[I]||(o.sample_groups_info[I]=A))},v.setSampleGroupProperties=function(o,c,f,m){var S,T;c.sample_groups=[];for(S in m)if(c.sample_groups[S]={},c.sample_groups[S].grouping_type=m[S].grouping_type,c.sample_groups[S].grouping_type_parameter=m[S].grouping_type_parameter,f>=m[S].last_sample_in_run&&(m[S].last_sample_in_run<0&&(m[S].last_sample_in_run=0),m[S].entry_index++,m[S].entry_index<=m[S].sbgp.entries.length-1&&(m[S].last_sample_in_run+=m[S].sbgp.entries[m[S].entry_index].sample_count)),m[S].entry_index<=m[S].sbgp.entries.length-1?c.sample_groups[S].group_description_index=m[S].sbgp.entries[m[S].entry_index].group_description_index:c.sample_groups[S].group_description_index=-1,c.sample_groups[S].group_description_index!==0){var b;m[S].fragment_description?b=m[S].fragment_description:b=m[S].description,c.sample_groups[S].group_description_index>0?(c.sample_groups[S].group_description_index>65535?T=(c.sample_groups[S].group_description_index>>16)-1:T=c.sample_groups[S].group_description_index-1,b&&T>=0&&(c.sample_groups[S].description=b.entries[T])):b&&b.version>=2&&b.default_group_description_index>0&&(c.sample_groups[S].description=b.entries[b.default_group_description_index-1])}},v.process_sdtp=function(o,c,f){c&&(o?(c.is_leading=o.is_leading[f],c.depends_on=o.sample_depends_on[f],c.is_depended_on=o.sample_is_depended_on[f],c.has_redundancy=o.sample_has_redundancy[f]):(c.is_leading=0,c.depends_on=0,c.is_depended_on=0,c.has_redundancy=0))},v.prototype.buildSampleLists=function(){var o,c;for(o=0;o<this.moov.traks.length;o++)c=this.moov.traks[o],this.buildTrakSampleLists(c)},v.prototype.buildTrakSampleLists=function(o){var c,f,m,S,T,b,A,I,L,w,R,M,k,z,O,U,j,H,V,J,$,G,ie,ce;if(o.samples=[],o.samples_duration=0,o.samples_size=0,f=o.mdia.minf.stbl.stco||o.mdia.minf.stbl.co64,m=o.mdia.minf.stbl.stsc,S=o.mdia.minf.stbl.stsz||o.mdia.minf.stbl.stz2,T=o.mdia.minf.stbl.stts,b=o.mdia.minf.stbl.ctts,A=o.mdia.minf.stbl.stss,I=o.mdia.minf.stbl.stsd,L=o.mdia.minf.stbl.subs,M=o.mdia.minf.stbl.stdp,w=o.mdia.minf.stbl.sbgps,R=o.mdia.minf.stbl.sgpds,H=-1,V=-1,J=-1,$=-1,G=0,ie=0,ce=0,v.initSampleGroups(o,null,w,R),!(typeof S>"u")){for(c=0;c<S.sample_sizes.length;c++){var K={};K.number=c,K.track_id=o.tkhd.track_id,K.timescale=o.mdia.mdhd.timescale,K.alreadyRead=0,o.samples[c]=K,K.size=S.sample_sizes[c],o.samples_size+=K.size,c===0?(z=1,k=0,K.chunk_index=z,K.chunk_run_index=k,j=m.samples_per_chunk[k],U=0,k+1<m.first_chunk.length?O=m.first_chunk[k+1]-1:O=1/0):c<j?(K.chunk_index=z,K.chunk_run_index=k):(z++,K.chunk_index=z,U=0,z<=O||(k++,k+1<m.first_chunk.length?O=m.first_chunk[k+1]-1:O=1/0),K.chunk_run_index=k,j+=m.samples_per_chunk[k]),K.description_index=m.sample_description_index[K.chunk_run_index]-1,K.description=I.entries[K.description_index],K.offset=f.chunk_offsets[K.chunk_index-1]+U,U+=K.size,c>H&&(V++,H<0&&(H=0),H+=T.sample_counts[V]),c>0?(o.samples[c-1].duration=T.sample_deltas[V],o.samples_duration+=o.samples[c-1].duration,K.dts=o.samples[c-1].dts+o.samples[c-1].duration):K.dts=0,b?(c>=J&&($++,J<0&&(J=0),J+=b.sample_counts[$]),K.cts=o.samples[c].dts+b.sample_offsets[$]):K.cts=K.dts,A?(c==A.sample_numbers[G]-1?(K.is_sync=!0,G++):(K.is_sync=!1,K.degradation_priority=0),L&&L.entries[ie].sample_delta+ce==c+1&&(K.subsamples=L.entries[ie].subsamples,ce+=L.entries[ie].sample_delta,ie++)):K.is_sync=!0,v.process_sdtp(o.mdia.minf.stbl.sdtp,K,K.number),M?K.degradation_priority=M.priority[c]:K.degradation_priority=0,L&&L.entries[ie].sample_delta+ce==c&&(K.subsamples=L.entries[ie].subsamples,ce+=L.entries[ie].sample_delta),(w.length>0||R.length>0)&&v.setSampleGroupProperties(o,K,c,o.sample_groups_info)}c>0&&(o.samples[c-1].duration=Math.max(o.mdia.mdhd.duration-o.samples[c-1].dts,0),o.samples_duration+=o.samples[c-1].duration)}},v.prototype.updateSampleLists=function(){var o,c,f,m,S,T,b,A,I,L,w,R,M,k,z;if(this.moov!==void 0){for(;this.lastMoofIndex<this.moofs.length;)if(I=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,I.type=="moof")for(L=I,o=0;o<L.trafs.length;o++){for(w=L.trafs[o],R=this.getTrackById(w.tfhd.track_id),M=this.getTrexById(w.tfhd.track_id),w.tfhd.flags&l.TFHD_FLAG_SAMPLE_DESC?m=w.tfhd.default_sample_description_index:m=M?M.default_sample_description_index:1,w.tfhd.flags&l.TFHD_FLAG_SAMPLE_DUR?S=w.tfhd.default_sample_duration:S=M?M.default_sample_duration:0,w.tfhd.flags&l.TFHD_FLAG_SAMPLE_SIZE?T=w.tfhd.default_sample_size:T=M?M.default_sample_size:0,w.tfhd.flags&l.TFHD_FLAG_SAMPLE_FLAGS?b=w.tfhd.default_sample_flags:b=M?M.default_sample_flags:0,w.sample_number=0,w.sbgps.length>0&&v.initSampleGroups(R,w,w.sbgps,R.mdia.minf.stbl.sgpds,w.sgpds),c=0;c<w.truns.length;c++){var O=w.truns[c];for(f=0;f<O.sample_count;f++){k={},k.moof_number=this.lastMoofIndex,k.number_in_traf=w.sample_number,w.sample_number++,k.number=R.samples.length,w.first_sample_index=R.samples.length,R.samples.push(k),k.track_id=R.tkhd.track_id,k.timescale=R.mdia.mdhd.timescale,k.description_index=m-1,k.description=R.mdia.minf.stbl.stsd.entries[k.description_index],k.size=T,O.flags&l.TRUN_FLAGS_SIZE&&(k.size=O.sample_size[f]),R.samples_size+=k.size,k.duration=S,O.flags&l.TRUN_FLAGS_DURATION&&(k.duration=O.sample_duration[f]),R.samples_duration+=k.duration,R.first_traf_merged||f>0?k.dts=R.samples[R.samples.length-2].dts+R.samples[R.samples.length-2].duration:(w.tfdt?k.dts=w.tfdt.baseMediaDecodeTime:k.dts=0,R.first_traf_merged=!0),k.cts=k.dts,O.flags&l.TRUN_FLAGS_CTS_OFFSET&&(k.cts=k.dts+O.sample_composition_time_offset[f]),z=b,O.flags&l.TRUN_FLAGS_FLAGS?z=O.sample_flags[f]:f===0&&O.flags&l.TRUN_FLAGS_FIRST_FLAG&&(z=O.first_sample_flags),k.is_sync=!(z>>16&1),k.is_leading=z>>26&3,k.depends_on=z>>24&3,k.is_depended_on=z>>22&3,k.has_redundancy=z>>20&3,k.degradation_priority=z&65535;var U=!!(w.tfhd.flags&l.TFHD_FLAG_BASE_DATA_OFFSET),j=!!(w.tfhd.flags&l.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),H=!!(O.flags&l.TRUN_FLAGS_DATA_OFFSET),V=0;U?V=w.tfhd.base_data_offset:j||c===0?V=L.start:V=A,c===0&&f===0?H?k.offset=V+O.data_offset:k.offset=V:k.offset=A,A=k.offset+k.size,(w.sbgps.length>0||w.sgpds.length>0||R.mdia.minf.stbl.sbgps.length>0||R.mdia.minf.stbl.sgpds.length>0)&&v.setSampleGroupProperties(R,k,k.number_in_traf,w.sample_groups_info)}}if(w.subs){R.has_fragment_subsamples=!0;var J=w.first_sample_index;for(c=0;c<w.subs.entries.length;c++)J+=w.subs.entries[c].sample_delta,k=R.samples[J-1],k.subsamples=w.subs.entries[c].subsamples}}}},v.prototype.getSample=function(o,c){var f,m=o.samples[c];if(!this.moov)return null;if(!m.data)m.data=new Uint8Array(m.size),m.alreadyRead=0,this.samplesDataSize+=m.size,e.debug("ISOFile","Allocating sample #"+c+" on track #"+o.tkhd.track_id+" of size "+m.size+" (total: "+this.samplesDataSize+")");else if(m.alreadyRead==m.size)return m;for(;;){var S=this.stream.findPosition(!0,m.offset+m.alreadyRead,!1);if(S>-1){f=this.stream.buffers[S];var T=f.byteLength-(m.offset+m.alreadyRead-f.fileStart);if(m.size-m.alreadyRead<=T)return e.debug("ISOFile","Getting sample #"+c+" data (alreadyRead: "+m.alreadyRead+" offset: "+(m.offset+m.alreadyRead-f.fileStart)+" read size: "+(m.size-m.alreadyRead)+" full size: "+m.size+")"),s.memcpy(m.data.buffer,m.alreadyRead,f,m.offset+m.alreadyRead-f.fileStart,m.size-m.alreadyRead),f.usedBytes+=m.size-m.alreadyRead,this.stream.logBufferLevel(),m.alreadyRead=m.size,m;if(T===0)return null;e.debug("ISOFile","Getting sample #"+c+" partial data (alreadyRead: "+m.alreadyRead+" offset: "+(m.offset+m.alreadyRead-f.fileStart)+" read size: "+T+" full size: "+m.size+")"),s.memcpy(m.data.buffer,m.alreadyRead,f,m.offset+m.alreadyRead-f.fileStart,T),m.alreadyRead+=T,f.usedBytes+=T,this.stream.logBufferLevel()}else return null}},v.prototype.releaseSample=function(o,c){var f=o.samples[c];return f.data?(this.samplesDataSize-=f.size,f.data=null,f.alreadyRead=0,f.size):0},v.prototype.getAllocatedSampleDataSize=function(){return this.samplesDataSize},v.prototype.getCodecs=function(){var o,c="";for(o=0;o<this.moov.traks.length;o++){var f=this.moov.traks[o];o>0&&(c+=","),c+=f.mdia.minf.stbl.stsd.entries[0].getCodec()}return c},v.prototype.getTrexById=function(o){var c;if(!this.moov||!this.moov.mvex)return null;for(c=0;c<this.moov.mvex.trexs.length;c++){var f=this.moov.mvex.trexs[c];if(f.track_id==o)return f}return null},v.prototype.getTrackById=function(o){if(this.moov===void 0)return null;for(var c=0;c<this.moov.traks.length;c++){var f=this.moov.traks[c];if(f.tkhd.track_id==o)return f}return null},v.prototype.itemsDataSize=0,v.prototype.flattenItemInfo=function(){var o=this.items,c=this.entity_groups,f,m,S,T=this.meta;if(T!=null&&T.hdlr!==void 0&&T.iinf!==void 0){for(f=0;f<T.iinf.item_infos.length;f++)S={},S.id=T.iinf.item_infos[f].item_ID,o[S.id]=S,S.ref_to=[],S.name=T.iinf.item_infos[f].item_name,T.iinf.item_infos[f].protection_index>0&&(S.protection=T.ipro.protections[T.iinf.item_infos[f].protection_index-1]),T.iinf.item_infos[f].item_type?S.type=T.iinf.item_infos[f].item_type:S.type="mime",S.content_type=T.iinf.item_infos[f].content_type,S.content_encoding=T.iinf.item_infos[f].content_encoding,S.item_uri_type=T.iinf.item_infos[f].item_uri_type;if(T.grpl)for(f=0;f<T.grpl.boxes.length;f++)entity_group={},entity_group.id=T.grpl.boxes[f].group_id,entity_group.entity_ids=T.grpl.boxes[f].entity_ids,entity_group.type=T.grpl.boxes[f].type,c[entity_group.id]=entity_group;if(T.iloc)for(f=0;f<T.iloc.items.length;f++){var b=T.iloc.items[f];switch(S=o[b.item_ID],b.data_reference_index!==0&&(e.warn("Item storage with reference to other files: not supported"),S.source=T.dinf.boxes[b.data_reference_index-1]),b.construction_method){case 0:break;case 1:break;case 2:e.warn("Item storage with construction_method : not supported");break}for(S.extents=[],S.size=0,m=0;m<b.extents.length;m++)S.extents[m]={},S.extents[m].offset=b.extents[m].extent_offset+b.base_offset,b.construction_method==1&&(S.extents[m].offset+=T.idat.start+T.idat.hdr_size),S.extents[m].length=b.extents[m].extent_length,S.extents[m].alreadyRead=0,S.size+=S.extents[m].length}if(T.pitm&&(o[T.pitm.item_id].primary=!0),T.iref)for(f=0;f<T.iref.references.length;f++){var A=T.iref.references[f];for(m=0;m<A.references.length;m++)o[A.from_item_ID].ref_to.push({type:A.type,id:A.references[m]})}if(T.iprp)for(var I=0;I<T.iprp.ipmas.length;I++){var L=T.iprp.ipmas[I];for(f=0;f<L.associations.length;f++){var w=L.associations[f];if(S=o[w.id],S||(S=c[w.id]),S)for(S.properties===void 0&&(S.properties={},S.properties.boxes=[]),m=0;m<w.props.length;m++){var R=w.props[m];if(R.property_index>0&&R.property_index-1<T.iprp.ipco.boxes.length){var M=T.iprp.ipco.boxes[R.property_index-1];S.properties[M.type]=M,S.properties.boxes.push(M)}}}}}},v.prototype.getItem=function(o){var c,f;if(!this.meta)return null;if(f=this.items[o],!f.data&&f.size)f.data=new Uint8Array(f.size),f.alreadyRead=0,this.itemsDataSize+=f.size,e.debug("ISOFile","Allocating item #"+o+" of size "+f.size+" (total: "+this.itemsDataSize+")");else if(f.alreadyRead===f.size)return f;for(var m=0;m<f.extents.length;m++){var S=f.extents[m];if(S.alreadyRead!==S.length){var T=this.stream.findPosition(!0,S.offset+S.alreadyRead,!1);if(T>-1){c=this.stream.buffers[T];var b=c.byteLength-(S.offset+S.alreadyRead-c.fileStart);if(S.length-S.alreadyRead<=b)e.debug("ISOFile","Getting item #"+o+" extent #"+m+" data (alreadyRead: "+S.alreadyRead+" offset: "+(S.offset+S.alreadyRead-c.fileStart)+" read size: "+(S.length-S.alreadyRead)+" full extent size: "+S.length+" full item size: "+f.size+")"),s.memcpy(f.data.buffer,f.alreadyRead,c,S.offset+S.alreadyRead-c.fileStart,S.length-S.alreadyRead),c.usedBytes+=S.length-S.alreadyRead,this.stream.logBufferLevel(),f.alreadyRead+=S.length-S.alreadyRead,S.alreadyRead=S.length;else return e.debug("ISOFile","Getting item #"+o+" extent #"+m+" partial data (alreadyRead: "+S.alreadyRead+" offset: "+(S.offset+S.alreadyRead-c.fileStart)+" read size: "+b+" full extent size: "+S.length+" full item size: "+f.size+")"),s.memcpy(f.data.buffer,f.alreadyRead,c,S.offset+S.alreadyRead-c.fileStart,b),S.alreadyRead+=b,f.alreadyRead+=b,c.usedBytes+=b,this.stream.logBufferLevel(),null}else return null}}return f.alreadyRead===f.size?f:null},v.prototype.releaseItem=function(o){var c=this.items[o];if(c.data){this.itemsDataSize-=c.size,c.data=null,c.alreadyRead=0;for(var f=0;f<c.extents.length;f++){var m=c.extents[f];m.alreadyRead=0}return c.size}else return 0},v.prototype.processItems=function(o){for(var c in this.items){var f=this.items[c];this.getItem(f.id),o&&!f.sent&&(o(f),f.sent=!0,f.data=null)}},v.prototype.hasItem=function(o){for(var c in this.items){var f=this.items[c];if(f.name===o)return f.id}return-1},v.prototype.getMetaHandler=function(){return this.meta?this.meta.hdlr.handler:null},v.prototype.getPrimaryItem=function(){return!this.meta||!this.meta.pitm?null:this.getItem(this.meta.pitm.item_id)},v.prototype.itemToFragmentedTrackFile=function(o){var c=o||{},f=null;if(c.itemId?f=this.getItem(c.itemId):f=this.getPrimaryItem(),f==null)return null;var m=new v;m.discardMdatData=!1;var S={type:f.type,description_boxes:f.properties.boxes};f.properties.ispe&&(S.width=f.properties.ispe.image_width,S.height=f.properties.ispe.image_height);var T=m.addTrack(S);return T?(m.addSample(T,f.data),m):null},v.prototype.write=function(o){for(var c=0;c<this.boxes.length;c++)this.boxes[c].write(o)},v.prototype.createFragment=function(o,c,f){var m=this.getTrackById(o),S=this.getSample(m,c);if(S==null)return this.setNextSeekPositionFromSample(m.samples[c]),null;var T=f||new s;T.endianness=s.BIG_ENDIAN;var b=this.createSingleSampleMoof(S);b.write(T),b.trafs[0].truns[0].data_offset=b.size+8,e.debug("MP4Box","Adjusting data_offset with new value "+b.trafs[0].truns[0].data_offset),T.adjustUint32(b.trafs[0].truns[0].data_offset_position,b.trafs[0].truns[0].data_offset);var A=new l.mdatBox;return A.data=S.data,A.write(T),T},v.writeInitializationSegment=function(o,c,f,m){var S;e.debug("ISOFile","Generating initialization segment");var T=new s;T.endianness=s.BIG_ENDIAN,o.write(T);var b=c.add("mvex");for(f&&b.add("mehd").set("fragment_duration",f),S=0;S<c.traks.length;S++)b.add("trex").set("track_id",c.traks[S].tkhd.track_id).set("default_sample_description_index",1).set("default_sample_duration",m).set("default_sample_size",0).set("default_sample_flags",65536);return c.write(T),T.buffer},v.prototype.save=function(o){var c=new s;c.endianness=s.BIG_ENDIAN,this.write(c),c.save(o)},v.prototype.getBuffer=function(){var o=new s;return o.endianness=s.BIG_ENDIAN,this.write(o),o.buffer},v.prototype.initializeSegmentation=function(){var o,c,f,m;for(this.onSegment===null&&e.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.nextMoofNumber=0,this.resetTables()),c=[],o=0;o<this.fragmentedTracks.length;o++){var S=new l.moovBox;S.mvhd=this.moov.mvhd,S.boxes.push(S.mvhd),f=this.getTrackById(this.fragmentedTracks[o].id),S.boxes.push(f),S.traks.push(f),m={},m.id=f.tkhd.track_id,m.user=this.fragmentedTracks[o].user,m.buffer=v.writeInitializationSegment(this.ftyp,S,this.moov.mvex&&this.moov.mvex.mehd?this.moov.mvex.mehd.fragment_duration:void 0,this.moov.traks[o].samples.length>0?this.moov.traks[o].samples[0].duration:0),c.push(m)}return c},l.Box.prototype.printHeader=function(o){this.size+=8,this.size>n&&(this.size+=8),this.type==="uuid"&&(this.size+=16),o.log(o.indent+"size:"+this.size),o.log(o.indent+"type:"+this.type)},l.FullBox.prototype.printHeader=function(o){this.size+=4,l.Box.prototype.printHeader.call(this,o),o.log(o.indent+"version:"+this.version),o.log(o.indent+"flags:"+this.flags)},l.Box.prototype.print=function(o){this.printHeader(o)},l.ContainerBox.prototype.print=function(o){this.printHeader(o);for(var c=0;c<this.boxes.length;c++)if(this.boxes[c]){var f=o.indent;o.indent+=" ",this.boxes[c].print(o),o.indent=f}},v.prototype.print=function(o){o.indent="";for(var c=0;c<this.boxes.length;c++)this.boxes[c]&&this.boxes[c].print(o)},l.mvhdBox.prototype.print=function(o){l.FullBox.prototype.printHeader.call(this,o),o.log(o.indent+"creation_time: "+this.creation_time),o.log(o.indent+"modification_time: "+this.modification_time),o.log(o.indent+"timescale: "+this.timescale),o.log(o.indent+"duration: "+this.duration),o.log(o.indent+"rate: "+this.rate),o.log(o.indent+"volume: "+(this.volume>>8)),o.log(o.indent+"matrix: "+this.matrix.join(", ")),o.log(o.indent+"next_track_id: "+this.next_track_id)},l.tkhdBox.prototype.print=function(o){l.FullBox.prototype.printHeader.call(this,o),o.log(o.indent+"creation_time: "+this.creation_time),o.log(o.indent+"modification_time: "+this.modification_time),o.log(o.indent+"track_id: "+this.track_id),o.log(o.indent+"duration: "+this.duration),o.log(o.indent+"volume: "+(this.volume>>8)),o.log(o.indent+"matrix: "+this.matrix.join(", ")),o.log(o.indent+"layer: "+this.layer),o.log(o.indent+"alternate_group: "+this.alternate_group),o.log(o.indent+"width: "+this.width),o.log(o.indent+"height: "+this.height)};var _={};_.createFile=function(o,c){var f=o!==void 0?o:!0,m=new v(c);return m.discardMdatData=!f,m},r.createFile=_.createFile})(or);class Zh{constructor(e,t,s,n=0){this.segment=e,this.sourceFps=t,this.targetFps=s,this.sum=n,this.framesRequested=0}async getNextFrame(){var t;const e=this.sourceFps/this.targetFps;if(this.sum+=e,this.framesRequested+=1,this.sum<1&&this.lastFrame)return this.lastFrame;for(;this.sum>=2;){const s=await this.segment.getNextFrame();if(!s)return;s.close(),this.sum-=1}if(this.sum>=1||!this.lastFrame){this.sum-=1;const s=await this.segment.getNextFrame();return s?((t=this.lastFrame)==null||t.close(),this.lastFrame=s,s):void 0}throw new Error("Unreachable code")}getLastFrame(){return this.lastFrame}getSum(){return this.sum}getSegment(){return this.segment}getTime(e){return(this.framesRequested-e)/this.targetFps}}class Fu{constructor(e,t,s=0){this.file=e,this.setStatus=t,this.offset=s}write(e){const t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e),t.fileStart=this.offset,this.offset+=t.byteLength,this.setStatus("fetch",(this.offset/1024**2).toFixed(1)+" MiB"),this.file.appendBuffer(t)}close(){this.setStatus("fetch","Done"),this.file.flush()}}const wS=30;class Jh{constructor(e,t,s,n,a=0){this.done=!1,this.currentFramePastSegmentEndTime=!1,this.abortController=new AbortController,this.responseFinished=!1,this.framesProcessed=0,this.framesDue=0,this.frameBuffer=[],this.encodedChunkQueue=[],this.readMore=async()=>{},this.uri=e,this.file=t,this.file.onSamples=this.onSamples.bind(this),this.edit=s[n],this.startTime=a;const h=Math.floor(this.startTime*this.edit.fps);this.framesProcessed+=h,this.decoder=new VideoDecoder({output:this.onFrame.bind(this),error(l){console.error(l)}})}async start(e){if(this.edit.mediaTime===-1){this.done=!0,this.responseFinished=!0,this.decoder.close();const d=this.edit.segmentDuration/this.file.getInfo().videoTracks[0].movie_timescale,p=Math.ceil(d*this.edit.fps),g=this.file.getInfo().videoTracks[0].track_height,y=this.file.getInfo().videoTracks[0].track_width,x=g*y*4,v=new ArrayBuffer(x),_=new Uint8Array(v);_.fill(0),this.frameBuffer=Array.from({length:p},()=>new VideoFrame(_,{timestamp:0,duration:1/this.edit.fps,codedHeight:g,codedWidth:y,format:"BGRA"}));return}this.decoder.configure(e);const t=this.file.getInfo().videoTracks[0],s=this.file.getTrackById(t.id),n=this.edit.mediaTime,a=this.startTime*t.timescale,l=(n+a)/t.timescale,u=this.file.seekTrack(l,!0,s);this.readMore=await this.startStreamingAtOffset(this.file,this.uri,u.offset)}async startStreamingAtOffset(e,t,s){return fetch(t,{headers:{Range:`bytes=${s}-`},signal:this.abortController.signal}).then(async n=>{if(!n.body)throw new Error("Response body is null");const a=n.body.getReader(),h=new Fu(e,()=>{},s);return async()=>a.read().then(({done:l,value:u})=>{if(l){this.responseFinished=!0,this.abortController.abort(),h.close();return}h.write(u)})})}onSamples(e,t,s){for(const n of s){const a=new EncodedVideoChunk({type:n.is_sync?"key":"delta",timestamp:1e6*n.cts/n.timescale,duration:1e6*n.duration/n.timescale,data:n.data});this.framesDue++,this.encodedChunkQueue.push(a);const h=this.file.getInfo().videoTracks[0],l=this.file.getTrackById(h.id);this.file.releaseSample(l,n.number)}}async decodeChunks(){for(;this.encodedChunkQueue.length>0&&this.decoder.decodeQueueSize<wS;){const e=this.encodedChunkQueue.shift();e&&this.decoder.decode(e)}if(this.done){this.currentFramePastSegmentEndTime=!0;return}if(this.responseFinished&&this.encodedChunkQueue.length===0){await this.flushDecoderWithRetry(),this.currentFramePastSegmentEndTime=!0;return}}async flushDecoderWithRetry(e=3,t=2e3){for(let s=0;s<e;s++){if(this.decoder.decodeQueueSize===0)return;try{await Promise.race([this.decoder.flush(),new Promise((n,a)=>setTimeout(()=>a(new Error("Flush timeout")),t))])}catch(n){if(s===e)throw n}}}async onFrame(e){this.framesDue--;const t=this.edit.mediaTime/this.file.getInfo().videoTracks[0].timescale,s=this.startTime+t,n=e.timestamp/1e6;if(n<s){e.close();return}const a=this.edit.segmentDuration/this.file.getInfo().videoTracks[0].movie_timescale,h=t+a;if(n>h){e.close(),this.done=!0,await this.decoder.flush();return}this.frameBuffer.push(e)}async populateBuffer(){for(;this.frameBuffer.length===0&&!this.currentFramePastSegmentEndTime;)this.responseFinished||await this.readMore(),await this.decodeChunks(),await new Promise(e=>setTimeout(e,0));if(this.frameBuffer.length===0&&this.framesDue>0){let e=200;for(;this.frameBuffer.length===0;)if(await new Promise(t=>setTimeout(t,10)),e--,this.done||e===0)return}}async getNextFrame(){await this.populateBuffer();const e=this.frameBuffer.shift();return e&&this.framesProcessed++,e}async close(){this.abortController.abort(),this.frameBuffer.forEach(e=>e.close());try{this.decoder.state==="configured"&&(await this.decoder.flush(),this.decoder.close())}catch{}}getFramesProcessed(){return this.framesProcessed}getStartTime(){return this.startTime}}function LS(r,e){const t=r.getTrackById(e.id);for(const s of t.mdia.minf.stbl.stsd.entries){const n=s.avcC||s.hvcC||s.vpcC||s.av1C;if(n){const a=new or.DataStream(void 0,0,or.DataStream.BIG_ENDIAN);return n.write(a),new Uint8Array(a.buffer,8)}}throw new Error("avcC, hvcC, vpcC, or av1C box not found")}function RS(r){return{mediaTime:r.media_time,segmentDuration:r.segment_duration,mediaRateInteger:r.media_rate_integer,mediaRateFraction:r.media_rate_fraction}}async function CS(r){return new Promise((e,t)=>{const s=or.createFile();let n=!1;const a=new AbortController;return s.onReady=h=>{var x;n=!0,a.abort();const l=h.videoTracks[0],u={codec:l.codec.startsWith("vp08")?"vp8":l.codec,codedHeight:l.video.height,codedWidth:l.video.width,description:LS(s,l)},d={mediaTime:0,segmentDuration:l.duration,mediaRateInteger:1,mediaRateFraction:0},p=(x=l.edits)==null?void 0:x.map(v=>RS(v)),y=(p!=null&&p.length?p:[d]).map(v=>{const _=l.duration/l.timescale,o=v.segmentDuration/l.movie_timescale,c=l.nb_samples*(o/_),f=v.mediaRateInteger+v.mediaRateFraction/65535,m=c/o*f;return{...v,fps:m}});s.setExtractionOptions(l.id),s.start(),e({file:s,edits:y,config:u})},fetch(r,{signal:a.signal}).then(async h=>{if(!h.body)throw new Error("Response body is null");const l=h.body.getReader(),u=new Fu(s,()=>{});for(;!n;)await l.read().then(({done:d,value:p})=>{if(d){s.flush(),a.abort(),t("Could not find moov");return}u.write(p)})})})}class PS{constructor(e,t,s){this.edits=[],this.nextSegment=0,this.uri=e,this.targetFps=t,this.startTime=s}async start(){const{file:e,edits:t,config:s}=await CS(this.uri);this.file=e,this.edits=t,this.decoderConfig=s}async getNextFrame(){var t;if(!this.sampler){let s=this.startTime;for(;this.nextSegment<this.edits.length;){const a=this.getSecondDurationOfSegment(this.edits[this.nextSegment]);if(s<a)break;s-=a,this.nextSegment++}if(this.nextSegment>=this.edits.length)throw new Error(`Timestamp ${this.startTime} is outside of the video, max timestamp is ${this.getDuration()}`);const n=new Jh(this.uri,this.file,this.edits,this.nextSegment,s);await n.start(this.decoderConfig),this.sampler=new Zh(n,this.edits[this.nextSegment].fps,this.targetFps,0),this.nextSegment++}let e=await this.sampler.getNextFrame();for(;!e&&this.nextSegment<this.edits.length;){this.sampler.getSegment().close(),(t=this.sampler.getLastFrame())==null||t.close();const s=new Jh(this.uri,this.file,this.edits,this.nextSegment,0);await s.start(this.decoderConfig),this.sampler=new Zh(s,this.edits[this.nextSegment].fps,this.targetFps,this.sampler.getSum()),this.nextSegment++,e=await this.sampler.getNextFrame()}if(!e&&(e=this.sampler.getLastFrame(),await this.sampler.getSegment().close(),!e))throw new Error("There are no frames in the video.");return e}getSecondDurationOfSegment(e){const t=e.mediaRateInteger+e.mediaRateFraction/65535;return e.segmentDuration/this.file.getInfo().videoTracks[0].movie_timescale/t}getDuration(){return this.edits.reduce((e,t)=>e+this.getSecondDurationOfSegment(t),0)}getTimeSubtractingFrames(e){const t=this.edits.slice(0,this.nextSegment-1).reduce((a,h)=>a+this.getSecondDurationOfSegment(h),0);if(!this.sampler)throw new Error("No current segment");const s=this.sampler.getSegment().getStartTime(),n=this.sampler.getTime(e);return t+s+n}getTime(){return this.getTimeSubtractingFrames(0)}getLastTime(){return this.getTimeSubtractingFrames(1)}getLastFrame(){var e;return(e=this.sampler)==null?void 0:e.getLastFrame()}close(){var e,t,s;(e=this.sampler)==null||e.getSegment().close(),(s=(t=this.sampler)==null?void 0:t.getLastFrame())==null||s.close(),this.file.flush()}}const ns=new Map;async function DS(r,e){const t=e+"-"+r,s=ns.get(t);s&&(s.close(),ns.delete(t))}async function kS(r,e,t,s){const n=e+"-"+r;let a=ns.get(n);const h=1/s,l=a==null?void 0:a.getDuration();l&&t>l&&(t=l);const u=a&&Math.abs(t-a.getLastTime())<h/2;if(a&&u){const d=a.getLastFrame();if(!d)throw new Error("No last frame");return d}return a&&t+h<a.getTime()&&(a.close(),ns.delete(n),a=void 0),a&&t>a.getTime()+h*1.5&&(a.close(),ns.delete(n),a=void 0),a||(a=new PS(e,s,t),await a.start(),ns.set(n,a)),a.getNextFrame()}var Yi=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},hi;let vt=hi=class extends qe{constructor(e){super(e),this.detectedFileType="unknown",this.fileTypeWasDetected=!1,this.lastFrame=null}desiredSize(){const e=super.desiredSize();if(e.x===null&&e.y===null){const t=this.video();return{x:t.videoWidth,y:t.videoHeight}}return e}mediaElement(){return this.video()}seekedMedia(){return this.seekedVideo()}fastSeekedMedia(){return this.fastSeekedVideo()}video(){const e=this.src(),t=`${this.key}/${e||"pending"}`;let s=hi.pool[t];if(s){if(e&&e!=="undefined"&&s.src!==e){try{if(new URL(e,window.location.origin).pathname.endsWith(".m3u8")){const l=new Qt;l.loadSource(e),l.attachMedia(s)}else s.src=e}catch{s.src=e}delete hi.pool[t];const a=`${this.key}/${e}`;hi.pool[a]=s}}else{if(s=document.createElement("video"),s.crossOrigin="anonymous",e&&e!=="undefined")try{if(new URL(e,window.location.origin).pathname.endsWith(".m3u8")){const h=new Qt;h.loadSource(e),h.attachMedia(s)}else s.src=e}catch{s.src=e}hi.pool[t]=s}return(!e||e==="undefined")&&ye.collectPromise(new Promise(a=>{const h=()=>{const l=this.src();l&&l!=="undefined"?a():setTimeout(h,10)};h()})),this.waitForCanPlayNecessary(s)&&ye.collectPromise(new Promise(a=>{this.waitForCanPlay(s,a)})),s}seekedVideo(){const e=this.video(),t=this.clampTime(this.time());return e.playbackRate=this.playbackRate(),e.paused||e.pause(),this.lastTime===t||this.setCurrentTime(t),e}fastSeekedVideo(){const e=this.video(),t=this.clampTime(this.time());if(e.playbackRate=this.playbackRate(),this.lastTime===t)return e;const s=this.playing()&&t<e.duration&&e.playbackRate>0;return s?e.paused&&ye.collectPromise(e.play()):e.paused||e.pause(),Math.abs(e.currentTime-t)>1?this.setCurrentTime(t):s||(e.currentTime=t),e}async webcodecSeekedVideo(){const e=this.video(),t=this.clampTime(this.time());if(e.playbackRate=this.playbackRate(),this.lastFrame&&this.lastTime===t)return this.lastFrame;const s=this.view().fps()/this.playbackRate();return kS(this.key,e.src,t,s)}async ffmpegSeekedVideo(){const e=this.video(),t=this.clampTime(this.time()),s=this.getDuration();if(e.playbackRate=this.playbackRate(),this.lastFrame&&this.lastTime===t)return this.lastFrame;const n=this.view().fps()/this.playbackRate();if(!hi.imageCommunication)throw new Error("ServerSeekedVideo can only be used with HMR.");const a=await hi.imageCommunication.getFrame(this.key,e.src,t,s,n);return this.lastFrame=a,this.lastTime=t,a}async seekFunction(){const e=this.view().playbackState();return e===tt.Playing||e===tt.Presenting?this.fastSeekedVideo():e===tt.Paused?this.seekedVideo():this.decoder()==="slow"?this.seekedVideo():this.decoder()==="ffmpeg"?this.ffmpegSeekedVideo():this.decoder()==="web"?this.webcodecSeekedVideo():(this.fileTypeWasDetected||this.detectFileType(),this.detectedFileType==="webm"?this.ffmpegSeekedVideo():this.detectedFileType==="hls"?this.seekedVideo():this.webcodecSeekedVideo())}async draw(e){this.autoPlayBasedOnTwick(),this.drawShape(e);const t=this.alpha();if(t>0){const s=await this.seekFunction(),n=pe.fromSizeCentered(this.computedSize());e.save(),e.clip(this.getPath()),t<1&&(e.globalAlpha*=t),e.imageSmoothingEnabled=this.smoothing(),Zc(e,s,n),e.restore()}this.clip()&&e.clip(this.getPath()),await this.drawChildren(e)}applyFlex(){super.applyFlex();try{const e=this.video();e&&e.videoWidth>0&&e.videoHeight>0&&(this.element.style.aspectRatio=(this.ratio()??e.videoWidth/e.videoHeight).toString())}catch{}}remove(){return super.remove(),DS(this.key,this.src()),this}handleUnknownFileType(e){console.warn(`WARNING: Could not detect file type of video (${e}), will default to using mp4 decoder. If your video file is not an mp4 file, this will lead to an error - to fix this, reencode your video as an mp4 file (better performance) or specify a different decoder: https://docs.re.video/common-issues/slow-rendering#use-mp4-decoder`),this.detectedFileType="unknown",this.fileTypeWasDetected=!0}detectFileType(){return ye.collectPromise((async()=>{var a;const e=this.src(),t=(a=e.split("?")[0].split(".").pop())==null?void 0:a.toLowerCase();if(t==="mp4"||t==="webm"||t==="mov"){this.detectedFileType=t,this.fileTypeWasDetected=!0;return}if(t==="m3u8"){this.detectedFileType="hls",this.fileTypeWasDetected=!0;return}if(!e.startsWith("http://")&&!e.startsWith("https://")){this.handleUnknownFileType(e);return}const n=(await fetch(e,{method:"HEAD"})).headers.get("Content-Type");if(!n){this.handleUnknownFileType(e);return}if(n.includes("video/mp4")){this.detectedFileType="mp4",this.fileTypeWasDetected=!0;return}if(n.includes("video/webm")){this.detectedFileType="webm",this.fileTypeWasDetected=!0;return}if(n.includes("video/quicktime")){this.detectedFileType="mov",this.fileTypeWasDetected=!0;return}if(n.includes("application/vnd.apple.mpegurl")||n.includes("application/x-mpegURL")){this.detectedFileType="hls",this.fileTypeWasDetected=!0;return}this.handleUnknownFileType(e)})())}};vt.pool={};vt.imageCommunication=null;Yi([W(1),N()],vt.prototype,"alpha",void 0);Yi([W(!0),N()],vt.prototype,"smoothing",void 0);Yi([W(null),N()],vt.prototype,"decoder",void 0);Yi([te()],vt.prototype,"video",null);Yi([te()],vt.prototype,"seekedVideo",null);Yi([te()],vt.prototype,"fastSeekedVideo",null);vt=hi=Yi([ut("Video")],vt);class MS extends e0{constructor(e){super(e),this.view=null,this.registeredNodes=new Map,this.nodeCounters=new Map,this.assetHash=Date.now().toString(),this.recreateView()}getView(){return this.view}next(){var e;return(e=this.getView())==null||e.playbackState(this.playback.state).globalTime(this.playback.time),super.next()}async draw(e){e.save(),this.renderLifecycle.dispatch([Mt.BeforeRender,e]),e.save(),this.renderLifecycle.dispatch([Mt.BeginRender,e]),this.getView().playbackState(this.playback.state).globalTime(this.playback.time).fps(this.playback.fps),await this.getView().render(e),this.renderLifecycle.dispatch([Mt.FinishRender,e]),e.restore(),this.renderLifecycle.dispatch([Mt.AfterRender,e]),e.restore()}reset(e){for(const t of this.registeredNodes.keys())try{this.registeredNodes.get(t).dispose()}catch(s){this.logger.error(s)}return this.registeredNodes.clear(),this.registeredNodes=new Map,this.nodeCounters.clear(),this.recreateView(),super.reset(e)}inspectPosition(e,t){const s=this.getNodeByPosition(e,t);return s==null?void 0:s.key}getNodeByPosition(e,t){return this.execute(()=>this.getView().hit(new C(e,t))??null)}validateInspection(e){var t;return((t=this.getNode(e))==null?void 0:t.key)??null}inspectAttributes(e){const t=this.getNode(e);if(!t)return null;const s={stack:t.creationStack,key:t.key};for(const{key:n,meta:a,signal:h}of t)a.inspectable&&(s[n]=h());return s}drawOverlay(e,t,s){const n=this.getNode(e);n&&this.execute(()=>{n.drawOverlay(s,t.multiply(n.localToWorld()))})}transformMousePosition(e,t){return Nt(new C(e,t),this.getView().localToParent().inverse())}registerNode(e,t){var h;const s=((h=e.constructor)==null?void 0:h.name)??"unknown",n=(this.nodeCounters.get(s)??0)+1;this.nodeCounters.set(s,n),t&&this.registeredNodes.has(t)&&(Ue().error({message:`Duplicated node key: "${t}".`,inspect:t,stack:new Error().stack}),t=void 0),t??(t=`${this.name}/${s}[${n}]`),this.registeredNodes.set(t,e);const a=this.registeredNodes;return[t,()=>a.delete(t)]}getNode(e){return typeof e!="string"?null:this.registeredNodes.get(e)??null}*getDetachedNodes(){for(const e of this.registeredNodes.values())!e.parent()&&e!==this.view&&(yield e)}getMediaAssets(){const e=Array.from(this.registeredNodes.values()).filter(n=>n instanceof vt).filter(n=>n.isPlaying()),t=Array.from(this.registeredNodes.values()).filter(n=>n instanceof ti).filter(n=>n.isPlaying()),s=[];return s.push(...e.map(n=>({key:n.key,type:"video",src:n.src(),decoder:n.decoder(),playbackRate:typeof n.playbackRate=="function"?n.playbackRate():n.playbackRate,volume:n.getVolume(),currentTime:n.getCurrentTime(),duration:n.getDuration()}))),s.push(...t.map(n=>({key:n.key,type:"audio",src:n.src(),playbackRate:typeof n.playbackRate=="function"?n.playbackRate():n.playbackRate,volume:n.getVolume(),currentTime:n.getCurrentTime(),duration:n.getDuration()}))),s}stopAllMedia(){const e=Array.from(this.registeredNodes.values()).filter(t=>t instanceof qe).filter(t=>t.isPlaying());for(const t of e)t.dispose()}adjustVolume(e){const t=Array.from(this.registeredNodes.values()).filter(s=>s instanceof qe);for(const s of t)s.setVolume(s.getVolume()*e)}recreateView(){this.execute(()=>{const e=this.getSize();this.view=new ii({position:e.scale(this.resolutionScale/2),scale:this.resolutionScale,assetHash:this.assetHash,size:e})})}}function FS(r,e){return{klass:MS,name:r,config:e,stack:new Error().stack,plugins:["@twick/2d/editor"]}}const Uu="#000000",Ou={x:0,y:0},mi="easeInOut",Ls={VIDEO:"video",AUDIO:"audio",CAPTION:"caption",SCENE:"scene",ELEMENT:"element"},ec={highlight_bg:{rect:{alignItems:"center",gap:2},word:{lineWidth:.35,stroke:"#000000",fontWeight:700,shadowOffset:[-3,3],shadowColor:"#000000",fill:"#ffffff",fontFamily:"Bangers",bgColor:"#444444",bgOffsetWidth:30,bgOffsetHeight:8,fontSize:50}},word_by_word:{rect:{alignItems:"center",justifyContent:"center",gap:8},word:{lineWidth:.35,stroke:"#000000",fontWeight:700,strokeFirst:!0,shadowOffset:[-2,2],shadowColor:"#000000",shadowBlur:5,fontFamily:"Bangers",fill:"#FFFFFF",bgOffsetWidth:20,bgOffsetHeight:10,fontSize:50}},word_by_word_with_bg:{rect:{alignItems:"center",gap:8,padding:[10,20],radius:10},word:{lineWidth:.35,stroke:"#000000",fontWeight:700,strokeFirst:!0,shadowOffset:[-2,2],shadowColor:"#000000",shadowBlur:5,fontFamily:"Bangers",fill:"#FFFFFF",bgOffsetWidth:20,bgOffsetHeight:10,fontSize:50}}},US={text:"#000000",bgColor:"#444444"},OS={family:"Poppins",size:48,weight:400},BS="#FFFFFF00",tc={VIDEO:"video",IMAGE:"image"},Ia={CONTAIN:"contain",COVER:"cover",FILL:"fill"},Xe={SATURATED:"saturated",BRIGHT:"bright",VIBRANT:"vibrant",RETRO:"retro",BLACK_WHITE:"blackWhite",COOL:"cool",WARM:"warm",CINEMATIC:"cinematic",SOFT_GLOW:"softGlow",MOODY:"moody",DREAMY:"dreamy",INVERTED:"inverted",VINTAGE:"vintage",DRAMATIC:"dramatic",FADED:"faded"},ic={PLAYER_UPDATE:"twick:playerUpdate"};function nn(r,e){console.log(`[Visualizer] ${r}`,e||"")}const NS={name:"audio",*create({containerRef:r,element:e,view:t}){const s=Oe();yield*oe(e==null?void 0:e.s),yield r().add(ke(ti,{ref:s,play:!0,...e.props},e.id)),yield*oe(Math.max(0,e.e-e.s)),yield s().play(!1),yield s().remove()}};function $S({t:r,s:e,e:t}){const s=r.split(" "),n=t-e,a=s.join("").length;let h=e;return s.map(l=>{const u=l.length/a*n,d=h,p=d+u;return h=p,{t:l,s:parseFloat(d.toFixed(2)),e:parseFloat(p.toFixed(2))}})}const Bu=r=>{let e=r.replace(/^#/,"");if(e.length===3&&(e=e.split("").map(h=>h+h).join("")),e.length!==6)throw new Error("Invalid hex color");const t=parseInt(e,16),s=t>>16&255,n=t>>8&255,a=t&255;return{r:s,g:n,b:a}},GS={name:"caption",*create({containerRef:r,caption:e}){var a,h,l,u,d,p;const t=$S(e);let s=0;t!=null&&t.length&&(s=t[0].s);let n={refs:[],props:[],idx:0,prevTime:s};for(const g of t){n.props.push(e.props);const y=Oe(),x=e.props;if(r().add(ke($t,{ref:y,...x,text:g.t,opacity:0})),e.capStyle=="highlight_bg"){const v=Oe(),_=Oe(),o=new we({...Bu(x.colors.bgColor),a:(x==null?void 0:x.bgOpacity)??1});r().add(ke(je,{ref:v,fill:o,width:y().width()+(x.bgOffsetWidth??30),height:y().height()+(x.bgOffsetHeight??10),margin:x.bgMargin??[0,-5],radius:x.bgRadius??10,padding:x.bgPadding??[0,15],opacity:0,alignItems:"center",justifyContent:"center",layout:!0,children:ke($t,{ref:_,...x,text:g.t})})),y().remove(),n.refs.push({bgRef:v,textRef:_})}else n.refs.push({textRef:y});n.prevTime=g.e,n.idx=n.idx+1}n.prevTime=s,n.idx=0;for(const g of t)e.capStyle=="highlight_bg"?(yield*(h=(a=n.refs[n.idx])==null?void 0:a.bgRef)==null?void 0:h.call(a).opacity(1,0),yield*oe(Math.max(0,g.e-g.s)),yield*(u=(l=n.refs[n.idx])==null?void 0:l.bgRef)==null?void 0:u.call(l).fill(BS,0)):(yield*(p=(d=n.refs[n.idx])==null?void 0:d.textRef)==null?void 0:p.call(d).opacity(1,0),yield*oe(Math.max(0,g.e-g.s))),n.prevTime=g.e,n.idx=n.idx+1}},zS={name:"elastic",*run({elementRef:r,duration:e,delay:t}){t&&(yield*oe(t)),r().scale(0),yield*r().scale(1,e,dc)}},HS={name:"erase",*run({elementRef:r,duration:e,delay:t,bufferTime:s=.1}){const n=r().text(),a=r().size();r().setText(""),r().size(a),r().textAlign("left"),t&&(yield*oe(t));let h=(e-s)/n.length;yield*oe(h);for(let l=n.length;l>=0;l--)yield*oe(h),r().setText(n.substring(0,l))}},VS={name:"stream-word",*run({elementRef:r,duration:e,delay:t,bufferTime:s=.1}){const n=r().text(),a=r().size(),h=n.split(" ");r().setText(""),r().size(a),t&&(yield*oe(t)),r().textAlign("left");let l=(e-s)/h.length;for(let u=0;u<h.length;u++)yield*oe(l),r().setText(h.slice(0,u+1).join(" "))}},KS={name:"typewriter",*run({elementRef:r,duration:e,delay:t,bufferTime:s=.1}){const n=r().text(),a=r().size();r().setText(""),r().size(a),r().textAlign("left"),t&&(yield*oe(t));let h=(e-s)/n.length;yield*oe(h);for(let l=0;l<n.length;l++)yield*oe(h),r().setText(n.substring(0,l+1))}};class YS{constructor(){this.effects=new Map}register(e){this.effects.set(e.name,e)}get(e){return this.effects.get(e)}list(){return Array.from(this.effects.keys())}}const WS=()=>{Cs.register(KS),Cs.register(VS),Cs.register(HS),Cs.register(zS)},Cs=new YS;WS();const jS={name:"blur",*run({elementRef:r,containerRef:e,interval:t,duration:s,intensity:n=25,animate:a}){const h=e??r;let l=Math.min(t,s);a==="enter"?(h().filters.blur(n),yield*h().filters.blur(0,l)):a==="exit"?(yield*oe(s-l),yield*h().filters.blur(n,l)):a==="both"&&(l=Math.min(t,s/2),h().filters.blur(n),yield*h().filters.blur(0,l),yield*oe(s-l),yield*h().filters.blur(n,l))}};function Ot(r){switch(r){case"easeInSine":return af;case"easeOutSine":return of;case"easeInOutSine":return lf;case"easeInQuad":return hf;case"easeOutQuad":return cf;case"easeInOutQuad":return df;case"easeInCubic":return uf;case"easeOutCubic":return ff;case"easeInOutCubic":return Bs;case"easeInQuart":return pf;case"easeOutQuart":return gf;case"easeInOutQuart":return mf;case"easeInQuint":return yf;case"easeOutQuint":return vf;case"easeInOutQuint":return xf;case"easeInExpo":return Sf;case"easeOutExpo":return hc;case"easeInOutExpo":return _f;case"easeInCirc":return Ef;case"easeOutCirc":return Tf;case"easeInOutCirc":return bf;case"easeInBack":return kf;case"easeOutBack":return Mf;case"easeInOutBack":return Ff;case"easeInElastic":return Nf;case"easeOutElastic":return dc;case"easeInOutElastic":return $f;case"easeInBounce":return Uf;case"easeOutBounce":return Of;case"easeInOutBounce":return Bf;default:return cc}}const qS={name:"breathe",*run({elementRef:r,containerRef:e,mode:t,duration:s,intensity:n=.5}){const a=e??r,h=a().scale();t==="in"&&(yield*a().scale(new C(h.x*n,h.y*n),s,Ot("easeInSine"))),t==="out"&&(a().scale(new C(h.x*n,h.y*n)),yield*a().scale(new C(h.x,h.y),s,Ot("easeOutSine")))}},XS={name:"fade",*run({elementRef:r,containerRef:e,interval:t,duration:s,animate:n}){const a=e??r;let h=Math.min(t,s);n==="enter"?(a().opacity(0),yield*a().opacity(1,h)):n==="exit"?(yield*oe(s-h),yield*a().opacity(0,h)):n==="both"&&(h=Math.min(t,s/2),a().opacity(0),yield*a().opacity(1,h),yield*oe(s-h),yield*a().opacity(0,h))}},QS={name:"photo-rise",*run({elementRef:r,containerRef:e,direction:t,duration:s,intensity:n=200}){if(e){const a=r().position();t==="up"?(r().y(a.y+n),yield*r().y(a.y,s)):t==="down"?(r().y(a.y-n),yield*r().y(a.y,s)):t==="left"?(r().x(a.x+n),yield*r().x(a.x,s)):t==="right"&&(r().x(a.x-n),yield*r().x(a.x,s))}}},ZS={name:"photo-zoom",*run({elementRef:r,containerRef:e,mode:t,duration:s,intensity:n=1.5}){if(e){const a=r().scale();t==="in"&&(yield r().scale(new C(a.x*n,a.y*n)),yield*r().scale(new C(a.x,a.y),s)),t==="out"&&(r().scale(new C(a.x,a.y)),yield*r().scale(new C(a.x*n,a.y*n),s))}}},JS={name:"rise",*run({elementRef:r,containerRef:e,interval:t=.25,duration:s,animate:n,direction:a,intensity:h=200}){const l=e??r,u=l().position();let d=Math.min(t,s);n==="enter"?(l().opacity(0),a==="up"?(l().y(u.y+h),yield*Se(l().opacity(1,d/4),l().y(u.y,d))):a==="down"&&(l().y(u.y-h),yield*Se(l().opacity(1,d/4),l().y(u.y,d)))):n==="exit"?(yield*oe(s-d),a==="up"?yield*Se(Fi(3*d/4,l().opacity(0,d/4)),l().y(u.y-h,d)):a==="down"&&(yield*Se(Fi(3*d/4,l().opacity(0,d/4)),l().y(u.y+h,d)))):n==="both"&&(d=Math.min(t,s/2),l().opacity(0),a==="up"?(l().y(u.y+h),yield*Se(l().opacity(1,d/4),l().y(u.y,d)),yield*oe(s-d),yield*Se(Fi(3*d/4,l().opacity(0,d/4)),l().y(u.y-h,d))):a==="down"&&(l().y(u.y-h),yield*Se(l().opacity(1,d/4),l().y(u.y,d)),yield*oe(s-d),yield*Se(Fi(3*d/4,l().opacity(0,d/4)),l().y(u.y+h,d))))}},e_={name:"succession",*run({elementRef:r,containerRef:e,interval:t,duration:s,animate:n}){const a=e??r,h=a().scale();let l=Math.min(t,s);n==="enter"?(a().opacity(0),a().scale(new C(h.x/2,h.y/2)),yield*Se(a().scale(h,l),a().opacity(1,l/2))):n==="exit"?(yield*oe(s-l),yield*Se(a().scale(new C(h.x/2,h.y/2),l),Fi(l/2,a().opacity(0,l/2)))):n==="both"&&(l=Math.min(t,s/2),a().opacity(0),a().scale(new C(h.x/2,h.y/2)),yield*Se(a().scale(h,l),a().opacity(1,l/2)),yield*oe(s-l),yield*Se(a().scale(new C(h.x/2,h.y/2),l),Fi(l/2,a().opacity(0,l/2))))}};class t_{constructor(){this.animations=new Map}register(e){this.animations.set(e.name,e)}get(e){return this.animations.get(e)}list(){return Array.from(this.animations.keys())}}const i_=()=>{ci.register(XS),ci.register(JS),ci.register(qS),ci.register(e_),ci.register(jS),ci.register(ZS),ci.register(QS)},ci=new t_;i_();const s_={name:"circle",*run({containerRef:r,elementRef:e,initFrameState:t,frameEffect:s}){yield*oe(s.s);const n=s.props,a=[];a.push(r().size({x:n.frameSize[0],y:n.frameSize[1]},n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(r().position(n.framePosition??{x:0,y:0},n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(e().position(n.elementPosition??Ou,n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(r().radius(n.frameSize[0]/2,n.transitionDuration,Ot(n.transitionEasing??mi))),n.objectFit&&a.push(rn({elementRef:e,containerSize:{x:n.frameSize[0],y:n.frameSize[1]},elementSize:t.element.size,objectFit:n.objectFit})),yield*Se(...a)}},n_={name:"rect",*run({containerRef:r,elementRef:e,initFrameState:t,frameEffect:s}){yield*oe(s.s);const n=s.props,a=[];a.push(r().size(n.frameSize,n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(r().position(n.framePosition??{x:0,y:0},n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(e().position(n.elementPosition??Ou,n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(r().radius(n.radius??0,n.transitionDuration,Ot(n.transitionEasing??mi))),n.objectFit&&a.push(rn({elementRef:e,containerSize:{x:n.frameSize[0],y:n.frameSize[1]},elementSize:t.element.size,objectFit:n.objectFit})),yield*Se(...a)}};class r_{constructor(){this.frameEffects=new Map}register(e){this.frameEffects.set(e.name,e)}get(e){return this.frameEffects.get(e)}list(){return Array.from(this.frameEffects.keys())}}const a_=()=>{ao.register(s_),ao.register(n_)},ao=new r_;a_();function*rn({containerSize:r,elementSize:e,elementRef:t,objectFit:s}){const n=r.x/r.y,a=e.x/e.y;switch(s){case Ia.CONTAIN:a>n?(yield t().size({x:r.x,y:r.x/a}),yield t().scale(r.x/e.x,r.x*a/e.y)):(yield t().size({x:r.y*a,y:r.y}),yield t().scale(r.y*a/e.x,r.y/e.y));break;case Ia.COVER:a>n?(yield t().size({x:r.y*a,y:r.y}),yield t().scale(r.y*a/e.x,r.y/e.y)):(yield t().size({x:r.x,y:r.x/a}),yield t().scale(r.x/e.x,r.x*a/e.y));break;case Ia.FILL:yield t().size(r),yield t().scale(r.x/e.x,r.x/e.y);break}}function*o_({elementRef:r,element:e}){if(yield r(),e.textEffect){const t=Cs.get(e.textEffect.name);t&&(yield*t.run({elementRef:r,duration:e.e-e.s,...e.textEffect}))}}function*Ts({elementRef:r,containerRef:e,element:t,view:s}){if(yield r(),t.animation){const n=ci.get(t.animation.name);n&&(yield*n.run({elementRef:r,containerRef:e,view:s,duration:t.e-t.s,...t.animation}))}}function*Nu({containerRef:r,elementRef:e,element:t}){var n;const s=l_({containerRef:r,elementRef:e});for(let a=0;a<((n=t==null?void 0:t.frameEffects)==null?void 0:n.length);a++){const h=t.frameEffects[a],l=a===t.frameEffects.length-1||t.frameEffects[a+1].s!==h.e,u=ao.get(h.name);u&&(yield*u.run({containerRef:r,elementRef:e,initFrameState:s,frameEffect:h}),l&&(yield*h_({containerRef:r,elementRef:e,duration:h.e-h.s,element:t,initProps:s})))}}function l_({containerRef:r,elementRef:e}){return{frame:{size:r().size(),pos:r().position(),radius:r().radius(),scale:r().scale(),rotation:r().rotation()},element:{size:r().size(),pos:e().position(),scale:e().scale()}}}function*h_({containerRef:r,elementRef:e,duration:t,element:s,initProps:n}){yield*oe(t),nn(`restoreFrameState: ${JSON.stringify(n)}`);let a=[];a.push(r().size(n.frame.size)),a.push(r().position(n.frame.pos)),a.push(r().scale(n.frame.scale)),a.push(r().rotation(n.frame.rotation)),a.push(r().radius(n.frame.radius)),a.push(e().size(n.element.size)),a.push(e().position(n.element.pos)),a.push(e().scale(n.element.scale)),a.push(rn({elementRef:e,containerSize:n.frame.size,elementSize:n.element.size,objectFit:s.objectFit??"none"})),yield*Se(...a)}const c_={name:"circle",*create({containerRef:r,element:e,view:t}){const s=Oe();yield*oe(e==null?void 0:e.s),yield r().add(ke(Gi,{ref:s,...e.props},e.id)),yield*Se(Ts({elementRef:s,element:e,view:t}),oe(Math.max(0,e.e-e.s))),yield s().remove()}},d_={name:"icon",*create({containerRef:r,element:e,view:t}){const s=Oe();yield*oe(e==null?void 0:e.s),yield r().add(ke(Ir,{ref:s,...e.props},e.id)),yield*Se(Ts({elementRef:s,element:e,view:t}),oe(Math.max(0,e.e-e.s))),yield s().remove()}},$u=(r,e)=>{switch(e){case Xe.SATURATED:r().filters.saturate(1.4),r().filters.contrast(1.1);break;case Xe.BRIGHT:r().filters.brightness(1.3),r().filters.contrast(1.05);break;case Xe.VIBRANT:r().filters.saturate(1.6),r().filters.brightness(1.15),r().filters.contrast(1.1);break;case Xe.RETRO:r().filters.sepia(.8),r().filters.contrast(1.3),r().filters.brightness(.85),r().filters.saturate(.8);break;case Xe.BLACK_WHITE:r().filters.grayscale(1),r().filters.contrast(1.25),r().filters.brightness(1.05);break;case Xe.COOL:r().filters.hue(15),r().filters.brightness(1.1),r().filters.saturate(1.3),r().filters.contrast(1.05);break;case Xe.WARM:r().filters.hue(-15),r().filters.brightness(1.15),r().filters.saturate(1.3),r().filters.contrast(1.05);break;case Xe.CINEMATIC:r().filters.contrast(1.4),r().filters.brightness(.95),r().filters.saturate(.85),r().filters.sepia(.2);break;case Xe.SOFT_GLOW:r().filters.brightness(1.2),r().filters.contrast(.95),r().filters.blur(1.2),r().filters.saturate(1.1);break;case Xe.MOODY:r().filters.brightness(1.05),r().filters.contrast(1.4),r().filters.saturate(.65),r().filters.sepia(.2);break;case Xe.DREAMY:r().filters.brightness(1.3),r().filters.blur(2),r().filters.saturate(1.4),r().filters.contrast(.95);break;case Xe.INVERTED:r().filters.invert(1),r().filters.hue(180);break;case Xe.VINTAGE:r().filters.sepia(.4),r().filters.saturate(1.4),r().filters.contrast(1.2),r().filters.brightness(1.1);break;case Xe.DRAMATIC:r().filters.contrast(1.5),r().filters.brightness(.9),r().filters.saturate(1.2);break;case Xe.FADED:r().filters.opacity(.9),r().filters.brightness(1.2),r().filters.saturate(.8),r().filters.contrast(.9);break}},Gu={name:"image",*create({containerRef:r,element:e,view:t}){var a;yield*oe(e==null?void 0:e.s);const s=Oe(),n=Oe();yield r().add(ke(je,{ref:s,...e.frame,children:ke(mt,{ref:n,...e.props},`child-${e.id}`)},e.id)),s()&&(yield rn({elementRef:n,containerSize:s().size(),elementSize:n().size(),objectFit:e.objectFit}),(a=e==null?void 0:e.props)!=null&&a.mediaFilter&&$u(n,e.props.mediaFilter),yield*Se(Ts({elementRef:n,containerRef:s,element:e,view:t}),Nu({containerRef:s,elementRef:n,element:e}),oe(Math.max(0,e.e-e.s))),yield n().remove(),yield s().remove())}},u_={name:"rect",*create({containerRef:r,element:e,view:t}){const s=Oe();yield*oe(e==null?void 0:e.s),nn(`RectElement: ${JSON.stringify(e)}`),yield r().add(ke(je,{ref:s,...e.props},e.id)),yield*Se(Ts({elementRef:s,element:e,view:t}),oe(Math.max(0,e.e-e.s))),yield s().remove()}},zu={name:"video",*create({containerRef:r,element:e,view:t}){var a;yield*oe(e==null?void 0:e.s);const s=Oe(),n=Oe();yield r().add(ke(je,{ref:s,...e.frame,children:ke(vt,{ref:n,play:!0,...e.props},`child-${e.id}`)},e.id)),s()&&(yield rn({elementRef:n,containerSize:s().size(),elementSize:n().size(),objectFit:e.objectFit}),(a=e==null?void 0:e.props)!=null&&a.mediaFilter&&$u(n,e.props.mediaFilter),yield*Se(Ts({elementRef:n,containerRef:s,element:e,view:t}),Nu({containerRef:s,elementRef:n,element:e}),oe(Math.max(0,e.e-e.s))),yield n().play(!1),yield n().remove(),yield s().remove())}},f_={name:"scene",*create({containerRef:r,element:e,view:t}){yield*oe(e==null?void 0:e.s);const s=Oe();nn(`SceneElement: ${JSON.stringify(e)}`),yield r().add(ke(je,{ref:s,fill:e.backgroundColor??Uu,size:"100%"})),e.type===tc.IMAGE?yield*Gu.create({containerRef:r,element:e,view:t}):e.type===tc.VIDEO&&(yield*zu.create({containerRef:r,element:e,view:t})),yield s().remove()}},p_={name:"text",*create({containerRef:r,element:e,view:t}){const s=Oe();yield*oe(e==null?void 0:e.s),yield r().add(ke($t,{ref:s,text:e.t,...e.props},e.id)),yield*Se(Ts({elementRef:s,element:e,view:t}),o_({elementRef:s,element:e}),oe(Math.max(0,e.e-e.s))),yield s().remove()}};class g_{constructor(){this.elements=new Map}register(e){this.elements.set(e.name,e)}get(e){return this.elements.get(e)}list(){return Array.from(this.elements.keys())}}const m_=()=>{ht.register(zu),ht.register(GS),ht.register(f_),ht.register(Gu),ht.register(p_),ht.register(NS),ht.register(c_),ht.register(d_),ht.register(u_)},ht=new g_;m_();function*y_({view:r,track:e}){var n;const t=Oe();let s=0;r.add(ke(Q,{size:"100%",ref:t,layout:!0}));for(const a of e.elements||[])yield*oe((a==null?void 0:a.s)-s),yield*(n=ht.get("video"))==null?void 0:n.create({containerRef:t,element:a,view:r}),s=a.e;yield t().remove()}function*v_({view:r,track:e}){let t=0;for(const s of e.elements){const n=Oe();yield*oe((s==null?void 0:s.s)-t),t=s==null?void 0:s.e,nn(`Adding audio element ${s.id}`),r.add(ke(ti,{ref:n,...s.props},s.id)),yield*oe(Math.max(0,s.e-s.s)),yield n().playing(!1),yield n().remove()}}function*x_({view:r,track:e}){var l;let t=0;const s=Oe();r.add(ke(Q,{size:"100%",ref:s}));const n=e==null?void 0:e.props,a=(n==null?void 0:n.applyToAll)??!1,h=(ec[(n==null?void 0:n.capStyle)??""]||{}).word||{};for(const u of e.elements){const d=u.props,p=(ec[(d==null?void 0:d.capStyle)??(n==null?void 0:n.capStyle)??""]||{}).rect||{},g={...p,justifyContent:p.justifyContent,alignItems:p.alignItems},y=a?n==null?void 0:n.colors:(d==null?void 0:d.colors)??(n==null?void 0:n.colors)??US,x={...h,...(n==null?void 0:n.captionProps)||{},colors:y,font:a?n==null?void 0:n.font:(d==null?void 0:d.font)??(n==null?void 0:n.font)??OS,fill:y.text,bgColor:y.bgColor,bgOpacity:(n==null?void 0:n.bgOpacity)??1};yield*oe((u==null?void 0:u.s)-t);const v=Oe();if(s().add(ke(je,{ref:v,...g,x:a?n==null?void 0:n.x:(d==null?void 0:d.x)??(n==null?void 0:n.x),y:a?n==null?void 0:n.y:(d==null?void 0:d.y)??(n==null?void 0:n.y),layout:!0},u.id)),(n==null?void 0:n.capStyle)==="word_by_word_with_bg"){const _=new we({...Bu(x.bgColor),a:(x==null?void 0:x.bgOpacity)??1});v().fill(_)}yield*(l=ht.get("caption"))==null?void 0:l.create({containerRef:v,caption:{...u,t:u.t??"",capStyle:(d==null?void 0:d.capStyle)??(n==null?void 0:n.capStyle),props:x},view:r}),t=u.e,yield v().remove()}}function*S_({view:r,track:e}){var s;const t=Oe();r.add(ke(Q,{size:"100%",ref:t,layout:!0}));for(const n of e.elements||[])yield*(s=ht.get("scene"))==null?void 0:s.create({containerRef:t,element:n,view:r});yield t().remove()}function*__({view:r,track:e}){var n;const t=Oe();r.add(ke(Q,{size:"100%",ref:t}));const s=[];try{for(const a of e.elements)s.push((n=ht.get(a.type))==null?void 0:n.create({containerRef:t,element:a,view:r}))}catch(a){nn("Error creating element track",a)}yield*Se(...s),yield t().remove()}const sc=(r,e)=>{if(typeof window<"u"){const t=new CustomEvent(r,e);return window.dispatchEvent(t)}},E_=FS("scene",function*(r){const e=zn().variables.get("input",null)(),t=zn().variables.get("playerId",null)();if(e)if(console.log("Scene updated",{playerId:t,input:e}),yield r.add(ke(je,{fill:e.backgroundColor??Uu,size:"100%"})),e.tracks){const s=[];for(const n of e.tracks)switch(n.type){case Ls.VIDEO:s.push(y_({view:r,track:n}));break;case Ls.AUDIO:s.push(v_({view:r,track:n}));break;case Ls.CAPTION:s.push(x_({view:r,track:n}));break;case Ls.SCENE:s.push(S_({view:r,track:n}));break;case Ls.ELEMENT:s.push(__({view:r,track:n}));break}yield*Se(...s),sc(ic.PLAYER_UPDATE,{detail:{status:"ready",playerId:t,message:"All elements created"}})}else sc(ic.PLAYER_UPDATE,{detail:{status:"ready",playerId:t,message:"No elements to create"}})}),G_=Bg({scenes:[E_]});export{G_ as default};
|