@design.estate/wcctools 6.0.0 → 6.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/changelog.md +13 -0
- package/dist_shell/bundle.js +3 -3
- package/dist_shell/bundle.js.map +1 -1
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/cli.js +8 -2
- package/dist_ts/plugins.d.ts +7 -2
- package/dist_ts/plugins.js +9 -3
- package/dist_ts/standards/baselines.d.ts +27 -0
- package/dist_ts/standards/baselines.js +83 -0
- package/dist_ts/standards/checker.d.ts +21 -0
- package/dist_ts/standards/checker.js +88 -0
- package/dist_ts/standards/classes.gitrepo.d.ts +13 -0
- package/dist_ts/standards/classes.gitrepo.js +43 -0
- package/dist_ts/standards/classes.sourceedits.d.ts +15 -0
- package/dist_ts/standards/classes.sourceedits.js +54 -0
- package/dist_ts/standards/classes.standardfixer.d.ts +40 -0
- package/dist_ts/standards/classes.standardfixer.js +210 -0
- package/dist_ts/standards/classes.standardproject.d.ts +80 -0
- package/dist_ts/standards/classes.standardproject.js +195 -0
- package/dist_ts/standards/classes.standardtree.d.ts +56 -0
- package/dist_ts/standards/classes.standardtree.js +207 -0
- package/dist_ts/standards/cli.d.ts +7 -0
- package/dist_ts/standards/cli.js +89 -0
- package/dist_ts/standards/config.d.ts +33 -0
- package/dist_ts/standards/config.js +139 -0
- package/dist_ts/standards/errors.d.ts +9 -0
- package/dist_ts/standards/errors.js +17 -0
- package/dist_ts/standards/helpers.ast.d.ts +56 -0
- package/dist_ts/standards/helpers.ast.js +172 -0
- package/dist_ts/standards/helpers.paths.d.ts +36 -0
- package/dist_ts/standards/helpers.paths.js +86 -0
- package/dist_ts/standards/index.d.ts +14 -0
- package/dist_ts/standards/index.js +15 -0
- package/dist_ts/standards/output.d.ts +7 -0
- package/dist_ts/standards/output.js +57 -0
- package/dist_ts/standards/ratchet.d.ts +15 -0
- package/dist_ts/standards/ratchet.js +45 -0
- package/dist_ts/standards/rule.d.ts +50 -0
- package/dist_ts/standards/rule.js +9 -0
- package/dist_ts/standards/rules/barrel.element-index.d.ts +7 -0
- package/dist_ts/standards/rules/barrel.element-index.js +108 -0
- package/dist_ts/standards/rules/barrel.no-demo-export.d.ts +3 -0
- package/dist_ts/standards/rules/barrel.no-demo-export.js +29 -0
- package/dist_ts/standards/rules/demo.fixture-not-exported.d.ts +3 -0
- package/dist_ts/standards/rules/demo.fixture-not-exported.js +29 -0
- package/dist_ts/standards/rules/demo.groups.d.ts +6 -0
- package/dist_ts/standards/rules/demo.groups.js +72 -0
- package/dist_ts/standards/rules/demo.required.d.ts +3 -0
- package/dist_ts/standards/rules/demo.required.js +48 -0
- package/dist_ts/standards/rules/demo.separate-file.d.ts +3 -0
- package/dist_ts/standards/rules/demo.separate-file.js +38 -0
- package/dist_ts/standards/rules/demo.shape.d.ts +3 -0
- package/dist_ts/standards/rules/demo.shape.js +38 -0
- package/dist_ts/standards/rules/docs.component-index.d.ts +8 -0
- package/dist_ts/standards/rules/docs.component-index.js +84 -0
- package/dist_ts/standards/rules/element.exported.d.ts +3 -0
- package/dist_ts/standards/rules/element.exported.js +33 -0
- package/dist_ts/standards/rules/element.literal-tag.d.ts +3 -0
- package/dist_ts/standards/rules/element.literal-tag.js +30 -0
- package/dist_ts/standards/rules/element.reachable.d.ts +3 -0
- package/dist_ts/standards/rules/element.reachable.js +48 -0
- package/dist_ts/standards/rules/element.tag-map.d.ts +3 -0
- package/dist_ts/standards/rules/element.tag-map.js +83 -0
- package/dist_ts/standards/rules/i18n.literals.d.ts +3 -0
- package/dist_ts/standards/rules/i18n.literals.js +52 -0
- package/dist_ts/standards/rules/index.d.ts +12 -0
- package/dist_ts/standards/rules/index.js +83 -0
- package/dist_ts/standards/rules/layout.element-folder.d.ts +3 -0
- package/dist_ts/standards/rules/layout.element-folder.js +47 -0
- package/dist_ts/standards/rules/layout.entry-file-name.d.ts +3 -0
- package/dist_ts/standards/rules/layout.entry-file-name.js +71 -0
- package/dist_ts/standards/rules/layout.entry.d.ts +3 -0
- package/dist_ts/standards/rules/layout.entry.js +38 -0
- package/dist_ts/standards/rules/layout.group-folder.d.ts +3 -0
- package/dist_ts/standards/rules/layout.group-folder.js +22 -0
- package/dist_ts/standards/rules/layout.shared-00.d.ts +3 -0
- package/dist_ts/standards/rules/layout.shared-00.js +36 -0
- package/dist_ts/standards/rules/naming.class-matches-tag.d.ts +3 -0
- package/dist_ts/standards/rules/naming.class-matches-tag.js +26 -0
- package/dist_ts/standards/rules/naming.lowercase-files.d.ts +3 -0
- package/dist_ts/standards/rules/naming.lowercase-files.js +26 -0
- package/dist_ts/standards/rules/naming.tag-prefix.d.ts +3 -0
- package/dist_ts/standards/rules/naming.tag-prefix.js +23 -0
- package/dist_ts/standards/rules/props.accessor.d.ts +3 -0
- package/dist_ts/standards/rules/props.accessor.js +35 -0
- package/dist_ts/standards/rules/props.object-no-attribute.d.ts +3 -0
- package/dist_ts/standards/rules/props.object-no-attribute.js +42 -0
- package/dist_ts/standards/rules/props.reflect-primitive.d.ts +5 -0
- package/dist_ts/standards/rules/props.reflect-primitive.js +41 -0
- package/dist_ts/standards/rules/props.typed.d.ts +6 -0
- package/dist_ts/standards/rules/props.typed.js +64 -0
- package/dist_ts/standards/rules/shared.d.ts +38 -0
- package/dist_ts/standards/rules/shared.js +103 -0
- package/dist_ts/standards/rules/style.bdtheme.d.ts +5 -0
- package/dist_ts/standards/rules/style.bdtheme.js +28 -0
- package/dist_ts_interfaces/index.d.ts +1 -0
- package/dist_ts_interfaces/index.js +2 -1
- package/dist_ts_interfaces/standard.d.ts +93 -0
- package/dist_ts_interfaces/standard.js +6 -0
- package/dist_ts_web/00_commitinfo_data.js +1 -1
- package/package.json +4 -2
- package/readme.md +34 -1
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/cli.ts +8 -1
- package/ts/plugins.ts +10 -2
- package/ts/standards/baselines.ts +100 -0
- package/ts/standards/checker.ts +114 -0
- package/ts/standards/classes.gitrepo.ts +48 -0
- package/ts/standards/classes.sourceedits.ts +58 -0
- package/ts/standards/classes.standardfixer.ts +234 -0
- package/ts/standards/classes.standardproject.ts +250 -0
- package/ts/standards/classes.standardtree.ts +220 -0
- package/ts/standards/cli.ts +86 -0
- package/ts/standards/config.ts +160 -0
- package/ts/standards/errors.ts +18 -0
- package/ts/standards/helpers.ast.ts +208 -0
- package/ts/standards/helpers.paths.ts +119 -0
- package/ts/standards/index.ts +22 -0
- package/ts/standards/output.ts +65 -0
- package/ts/standards/ratchet.ts +63 -0
- package/ts/standards/rule.ts +58 -0
- package/ts/standards/rules/barrel.element-index.ts +112 -0
- package/ts/standards/rules/barrel.no-demo-export.ts +30 -0
- package/ts/standards/rules/demo.fixture-not-exported.ts +30 -0
- package/ts/standards/rules/demo.groups.ts +74 -0
- package/ts/standards/rules/demo.required.ts +49 -0
- package/ts/standards/rules/demo.separate-file.ts +40 -0
- package/ts/standards/rules/demo.shape.ts +42 -0
- package/ts/standards/rules/docs.component-index.ts +88 -0
- package/ts/standards/rules/element.exported.ts +35 -0
- package/ts/standards/rules/element.literal-tag.ts +30 -0
- package/ts/standards/rules/element.reachable.ts +49 -0
- package/ts/standards/rules/element.tag-map.ts +87 -0
- package/ts/standards/rules/i18n.literals.ts +58 -0
- package/ts/standards/rules/index.ts +87 -0
- package/ts/standards/rules/layout.element-folder.ts +49 -0
- package/ts/standards/rules/layout.entry-file-name.ts +73 -0
- package/ts/standards/rules/layout.entry.ts +40 -0
- package/ts/standards/rules/layout.group-folder.ts +23 -0
- package/ts/standards/rules/layout.shared-00.ts +37 -0
- package/ts/standards/rules/naming.class-matches-tag.ts +27 -0
- package/ts/standards/rules/naming.lowercase-files.ts +27 -0
- package/ts/standards/rules/naming.tag-prefix.ts +24 -0
- package/ts/standards/rules/props.accessor.ts +37 -0
- package/ts/standards/rules/props.object-no-attribute.ts +45 -0
- package/ts/standards/rules/props.reflect-primitive.ts +44 -0
- package/ts/standards/rules/props.typed.ts +70 -0
- package/ts/standards/rules/shared.ts +127 -0
- package/ts/standards/rules/style.bdtheme.ts +31 -0
- package/ts_web/00_commitinfo_data.ts +1 -1
package/dist_shell/bundle.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var f2=Object.create;var Zl=Object.defineProperty;var d2=Object.getOwnPropertyDescriptor;var G8=Object.getOwnPropertyNames;var Q8=Object.getPrototypeOf,K8=Object.prototype.hasOwnProperty;var h2=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),eu=t=>{throw TypeError(t)};var m2=(t,e,r)=>e in t?Zl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var o=(t,e)=>Zl(t,"name",{value:e,configurable:!0});var he=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var ri=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},ke=(t,e)=>{for(var r in e)Zl(t,r,{get:e[r],enumerable:!0})},X8=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of G8(e))!K8.call(t,i)&&i!==r&&Zl(t,i,{get:()=>e[i],enumerable:!(n=d2(e,i))||n.enumerable});return t};var us=(t,e,r)=>(r=t!=null?f2(Q8(t)):{},X8(e||!t||!t.__esModule?Zl(r,"default",{value:t,enumerable:!0}):r,t));var un=t=>[,,,f2(t?.[h2("metadata")]??null)],p2=["class","method","getter","setter","accessor","field","value","get","set"],Nd=t=>t!==void 0&&typeof t!="function"?eu("Function expected"):t,J8=(t,e,r,n,i)=>({kind:p2[t],name:e,metadata:n,addInitializer:s=>r._?eu("Already initialized"):i.push(Nd(s||null))}),Z8=(t,e)=>m2(e,h2("metadata"),t[3]),B=(t,e,r,n)=>{for(var i=0,s=t[e>>1],a=s&&s.length;i<a;i++)e&1?s[i].call(r):n=s[i].call(r,n);return n},te=(t,e,r,n,i,s)=>{var a,c,l,u,f,d=e&7,h=!!(e&8),m=!!(e&16),p=d>3?t.length+1:d?h?1:2:0,g=p2[d+5],y=d>3&&(t[p-1]=[]),b=t[p]||(t[p]=[]),w=d&&(!m&&!h&&(i=i.prototype),d<5&&(d>3||!m)&&d2(d<4?i:{get[r](){return l2(this,s)},set[r](T){return u2(this,s,T)}},r));d?m&&d<4&&o(s,(d>2?"set ":d>1?"get ":"")+r):o(i,r);for(var k=n.length-1;k>=0;k--)u=J8(d,r,l={},t[3],b),d&&(u.static=h,u.private=m,f=u.access={has:m?T=>e5(i,T):T=>r in T},d^3&&(f.get=m?T=>(d^1?l2:t5)(T,i,d^4?s:w.get):T=>T[r]),d>2&&(f.set=m?(T,v)=>u2(T,i,v,d^4?s:w.set):(T,v)=>T[r]=v)),c=(0,n[k])(d?d<4?m?s:w[g]:d>4?void 0:{get:w.get,set:w.set}:i,u),l._=1,d^4||c===void 0?Nd(c)&&(d>4?y.unshift(c):d?m?s=c:w[g]=c:i=c):typeof c!="object"||c===null?eu("Object expected"):(Nd(a=c.get)&&(w.get=a),Nd(a=c.set)&&(w.set=a),Nd(a=c.init)&&y.unshift(a));return d||Z8(t,i),w&&Zl(i,r,w),m?d^4?s:w:i},$e=(t,e,r)=>m2(t,typeof e!="symbol"?e+"":e,r),gS=(t,e,r)=>e.has(t)||eu("Cannot "+r),e5=(t,e)=>Object(e)!==e?eu('Cannot use the "in" operator on this value'):t.has(e),l2=(t,e,r)=>(gS(t,e,"read from private field"),r?r.call(t):e.get(t)),ie=(t,e,r)=>e.has(t)?eu("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),u2=(t,e,r,n)=>(gS(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),t5=(t,e,r)=>(gS(t,e,"access private method"),r);var YR=ri((CT,PT)=>{(function(t,e){typeof CT=="object"&&typeof PT<"u"?PT.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs=e()})(CT,(function(){"use strict";var t=1e3,e=6e4,r=36e5,n="millisecond",i="second",s="minute",a="hour",c="day",l="week",u="month",f="quarter",d="year",h="date",m="Invalid Date",p=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,g=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,y={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:o(function(A){var R=["th","st","nd","rd"],F=A%100;return"["+A+(R[(F-20)%10]||R[F]||R[0])+"]"},"ordinal")},b=o(function(A,R,F){var $=String(A);return!$||$.length>=R?A:""+Array(R+1-$.length).join(F)+A},"m"),w={s:b,z:o(function(A){var R=-A.utcOffset(),F=Math.abs(R),$=Math.floor(F/60),W=F%60;return(R<=0?"+":"-")+b($,2,"0")+":"+b(W,2,"0")},"z"),m:o(function A(R,F){if(R.date()<F.date())return-A(F,R);var $=12*(F.year()-R.year())+(F.month()-R.month()),W=R.clone().add($,u),Q=F-W<0,re=R.clone().add($+(Q?-1:1),u);return+(-($+(F-W)/(Q?W-re:re-W))||0)},"t"),a:o(function(A){return A<0?Math.ceil(A)||0:Math.floor(A)},"a"),p:o(function(A){return{M:u,y:d,w:l,d:c,D:h,h:a,m:s,s:i,ms:n,Q:f}[A]||String(A||"").toLowerCase().replace(/s$/,"")},"p"),u:o(function(A){return A===void 0},"u")},k="en",T={};T[k]=y;var v="$isDayjsObject",S=o(function(A){return A instanceof O||!(!A||!A[v])},"S"),M=o(function A(R,F,$){var W;if(!R)return k;if(typeof R=="string"){var Q=R.toLowerCase();T[Q]&&(W=Q),F&&(T[Q]=F,W=Q);var re=R.split("-");if(!W&&re.length>1)return A(re[0])}else{var fe=R.name;T[fe]=R,W=fe}return!$&&W&&(k=W),W||!$&&k},"t"),P=o(function(A,R){if(S(A))return A.clone();var F=typeof R=="object"?R:{};return F.date=A,F.args=arguments,new O(F)},"O"),N=w;N.l=M,N.i=S,N.w=function(A,R){return P(A,{locale:R.$L,utc:R.$u,x:R.$x,$offset:R.$offset})};var O=(function(){function A(F){this.$L=M(F.locale,null,!0),this.parse(F),this.$x=this.$x||F.x||{},this[v]=!0}o(A,"M");var R=A.prototype;return R.parse=function(F){this.$d=(function($){var W=$.date,Q=$.utc;if(W===null)return new Date(NaN);if(N.u(W))return new Date;if(W instanceof Date)return new Date(W);if(typeof W=="string"&&!/Z$/i.test(W)){var re=W.match(p);if(re){var fe=re[2]-1||0,E=(re[7]||"0").substring(0,3);return Q?new Date(Date.UTC(re[1],fe,re[3]||1,re[4]||0,re[5]||0,re[6]||0,E)):new Date(re[1],fe,re[3]||1,re[4]||0,re[5]||0,re[6]||0,E)}}return new Date(W)})(F),this.init()},R.init=function(){var F=this.$d;this.$y=F.getFullYear(),this.$M=F.getMonth(),this.$D=F.getDate(),this.$W=F.getDay(),this.$H=F.getHours(),this.$m=F.getMinutes(),this.$s=F.getSeconds(),this.$ms=F.getMilliseconds()},R.$utils=function(){return N},R.isValid=function(){return this.$d.toString()!==m},R.isSame=function(F,$){var W=P(F);return this.startOf($)<=W&&W<=this.endOf($)},R.isAfter=function(F,$){return P(F)<this.startOf($)},R.isBefore=function(F,$){return this.endOf($)<P(F)},R.$g=function(F,$,W){return N.u(F)?this[$]:this.set(W,F)},R.unix=function(){return Math.floor(this.valueOf()/1e3)},R.valueOf=function(){return this.$d.getTime()},R.startOf=function(F,$){var W=this,Q=!!N.u($)||$,re=N.p(F),fe=o(function(L,_){var z=N.w(W.$u?Date.UTC(W.$y,_,L):new Date(W.$y,_,L),W);return Q?z:z.endOf(c)},"l"),E=o(function(L,_){return N.w(W.toDate()[L].apply(W.toDate("s"),(Q?[0,0,0,0]:[23,59,59,999]).slice(_)),W)},"$"),_e=this.$W,Ge=this.$M,D=this.$D,yt="set"+(this.$u?"UTC":"");switch(re){case d:return Q?fe(1,0):fe(31,11);case u:return Q?fe(1,Ge):fe(0,Ge+1);case l:var Yt=this.$locale().weekStart||0,Nn=(_e<Yt?_e+7:_e)-Yt;return fe(Q?D-Nn:D+(6-Nn),Ge);case c:case h:return E(yt+"Hours",0);case a:return E(yt+"Minutes",1);case s:return E(yt+"Seconds",2);case i:return E(yt+"Milliseconds",3);default:return this.clone()}},R.endOf=function(F){return this.startOf(F,!1)},R.$set=function(F,$){var W,Q=N.p(F),re="set"+(this.$u?"UTC":""),fe=(W={},W[c]=re+"Date",W[h]=re+"Date",W[u]=re+"Month",W[d]=re+"FullYear",W[a]=re+"Hours",W[s]=re+"Minutes",W[i]=re+"Seconds",W[n]=re+"Milliseconds",W)[Q],E=Q===c?this.$D+($-this.$W):$;if(Q===u||Q===d){var _e=this.clone().set(h,1);_e.$d[fe](E),_e.init(),this.$d=_e.set(h,Math.min(this.$D,_e.daysInMonth())).$d}else fe&&this.$d[fe](E);return this.init(),this},R.set=function(F,$){return this.clone().$set(F,$)},R.get=function(F){return this[N.p(F)]()},R.add=function(F,$){var W,Q=this;F=Number(F);var re=N.p($),fe=o(function(Ge){var D=P(Q);return N.w(D.date(D.date()+Math.round(Ge*F)),Q)},"y");if(re===u)return this.set(u,this.$M+F);if(re===d)return this.set(d,this.$y+F);if(re===c)return fe(1);if(re===l)return fe(7);var E=(W={},W[s]=e,W[a]=r,W[i]=t,W)[re]||1,_e=this.$d.getTime()+F*E;return N.w(_e,this)},R.subtract=function(F,$){return this.add(-1*F,$)},R.format=function(F){var $=this,W=this.$locale();if(!this.isValid())return W.invalidDate||m;var Q=F||"YYYY-MM-DDTHH:mm:ssZ",re=N.z(this),fe=this.$H,E=this.$m,_e=this.$M,Ge=W.weekdays,D=W.months,yt=W.meridiem,Yt=o(function(_,z,U,q){return _&&(_[z]||_($,Q))||U[z].slice(0,q)},"h"),Nn=o(function(_){return N.s(fe%12||12,_,"0")},"d"),L=yt||function(_,z,U){var q=_<12?"AM":"PM";return U?q.toLowerCase():q};return Q.replace(g,(function(_,z){return z||(function(U){switch(U){case"YY":return String($.$y).slice(-2);case"YYYY":return N.s($.$y,4,"0");case"M":return _e+1;case"MM":return N.s(_e+1,2,"0");case"MMM":return Yt(W.monthsShort,_e,D,3);case"MMMM":return Yt(D,_e);case"D":return $.$D;case"DD":return N.s($.$D,2,"0");case"d":return String($.$W);case"dd":return Yt(W.weekdaysMin,$.$W,Ge,2);case"ddd":return Yt(W.weekdaysShort,$.$W,Ge,3);case"dddd":return Ge[$.$W];case"H":return String(fe);case"HH":return N.s(fe,2,"0");case"h":return Nn(1);case"hh":return Nn(2);case"a":return L(fe,E,!0);case"A":return L(fe,E,!1);case"m":return String(E);case"mm":return N.s(E,2,"0");case"s":return String($.$s);case"ss":return N.s($.$s,2,"0");case"SSS":return N.s($.$ms,3,"0");case"Z":return re}return null})(_)||re.replace(":","")}))},R.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},R.diff=function(F,$,W){var Q,re=this,fe=N.p($),E=P(F),_e=(E.utcOffset()-this.utcOffset())*e,Ge=this-E,D=o(function(){return N.m(re,E)},"D");switch(fe){case d:Q=D()/12;break;case u:Q=D();break;case f:Q=D()/3;break;case l:Q=(Ge-_e)/6048e5;break;case c:Q=(Ge-_e)/864e5;break;case a:Q=Ge/r;break;case s:Q=Ge/e;break;case i:Q=Ge/t;break;default:Q=Ge}return W?Q:N.a(Q)},R.daysInMonth=function(){return this.endOf(u).$D},R.$locale=function(){return T[this.$L]},R.locale=function(F,$){if(!F)return this.$L;var W=this.clone(),Q=M(F,$,!0);return Q&&(W.$L=Q),W},R.clone=function(){return N.w(this.$d,this)},R.toDate=function(){return new Date(this.valueOf())},R.toJSON=function(){return this.isValid()?this.toISOString():null},R.toISOString=function(){return this.$d.toISOString()},R.toString=function(){return this.$d.toUTCString()},A})(),Y=O.prototype;return P.prototype=Y,[["$ms",n],["$s",i],["$m",s],["$H",a],["$W",c],["$M",u],["$y",d],["$D",h]].forEach((function(A){Y[A[1]]=function(R){return this.$g(R,A[0],A[1])}})),P.extend=function(A,R){return A.$i||(A(R,O,P),A.$i=!0),P},P.locale=M,P.isDayjs=S,P.unix=function(A){return P(1e3*A)},P.en=T[k],P.Ls=T,P.p={},P}))});var GR=ri((IT,_T)=>{(function(t,e){typeof IT=="object"&&typeof _T<"u"?_T.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs_plugin_isToday=e()})(IT,(function(){"use strict";return function(t,e,r){e.prototype.isToday=function(){var n="YYYY-MM-DD",i=r();return this.format(n)===i.format(n)}}}))});var JR=ri((_Ve,XR)=>{"use strict";XR.exports=class{static{o(this,"SymbolTreeNode")}constructor(){this.parent=null,this.previousSibling=null,this.nextSibling=null,this.firstChild=null,this.lastChild=null,this.childrenVersion=0,this.childIndexCachedUpTo=null,this.cachedIndex=-1,this.cachedIndexVersion=NaN}get isAttached(){return!!(this.parent||this.previousSibling||this.nextSibling)}get hasChildren(){return!!this.firstChild}childrenChanged(){this.childrenVersion=this.childrenVersion+1&4294967295,this.childIndexCachedUpTo=null}getCachedIndex(e){return this.cachedIndexVersion!==e.childrenVersion?(this.cachedIndexVersion=NaN,-1):this.cachedIndex}setCachedIndex(e,r){this.cachedIndexVersion=e.childrenVersion,this.cachedIndex=r}}});var eN=ri((MVe,ZR)=>{"use strict";ZR.exports=Object.freeze({DISCONNECTED:1,PRECEDING:2,FOLLOWING:4,CONTAINS:8,CONTAINED_BY:16})});var sN=ri((OVe,iN)=>{"use strict";var tN=Symbol(),rN=Symbol(),ma=Symbol(),nN=Symbol(),Ri=class{static{o(this,"TreeIterator")}constructor(e,r,n,i){this[tN]=e,this[rN]=r,this[ma]=n,this[nN]=i}next(){let e=this[tN],r=this[nN],n=this[rN];if(!this[ma])return{done:!0,value:n};let i=this[ma];return r===1?this[ma]=e._node(i).previousSibling:r===2?this[ma]=e._node(i).nextSibling:r===3?this[ma]=e._node(i).parent:r===4?this[ma]=e.preceding(i,{root:n}):this[ma]=e.following(i,{root:n}),{done:!1,value:i}}};Object.defineProperty(Ri.prototype,Symbol.iterator,{value:o(function(){return this},"value"),writable:!1}),Ri.PREV=1,Ri.NEXT=2,Ri.PARENT=3,Ri.PRECEDING=4,Ri.FOLLOWING=5,Object.freeze(Ri),Object.freeze(Ri.prototype),iN.exports=Ri});var aN=ri((NVe,oN)=>{"use strict";var qj=JR(),pa=eN(),ci=sN();function LT(){return!0}o(LT,"returnTrue");function Wu(t,e){return t[t.length-1-e]}o(Wu,"reverseArrayIndex");var Ub=class{static{o(this,"SymbolTree")}constructor(e){this.symbol=Symbol(e||"SymbolTree data")}initialize(e){return this._node(e),e}_node(e){if(!e)return null;let r=e[this.symbol];return r||(e[this.symbol]=new qj)}hasChildren(e){return this._node(e).hasChildren}firstChild(e){return this._node(e).firstChild}lastChild(e){return this._node(e).lastChild}previousSibling(e){return this._node(e).previousSibling}nextSibling(e){return this._node(e).nextSibling}parent(e){return this._node(e).parent}lastInclusiveDescendant(e){let r,n=e;for(;r=this._node(n).lastChild;)n=r;return n}preceding(e,r){let n=r&&r.root;if(e===n)return null;let i=this._node(e).previousSibling;return i?this.lastInclusiveDescendant(i):this._node(e).parent}following(e,r){let n=r&&r.root,s=!(r&&r.skipChildren)&&this._node(e).firstChild;if(s)return s;let a=e;do{if(a===n)return null;let c=this._node(a).nextSibling;if(c)return c;a=this._node(a).parent}while(a);return null}childrenToArray(e,r){let n=r&&r.array||[],i=r&&r.filter||LT,s=r&&r.thisArg||void 0,a=this._node(e),c=a.firstChild,l=0;for(;c;){let u=this._node(c);u.setCachedIndex(a,l),i.call(s,c)&&n.push(c),c=u.nextSibling,++l}return n}ancestorsToArray(e,r){let n=r&&r.array||[],i=r&&r.filter||LT,s=r&&r.thisArg||void 0,a=e;for(;a;)i.call(s,a)&&n.push(a),a=this._node(a).parent;return n}treeToArray(e,r){let n=r&&r.array||[],i=r&&r.filter||LT,s=r&&r.thisArg||void 0,a=e;for(;a;)i.call(s,a)&&n.push(a),a=this.following(a,{root:e});return n}childrenIterator(e,r){let n=r&&r.reverse,i=this._node(e);return new ci(this,e,n?i.lastChild:i.firstChild,n?ci.PREV:ci.NEXT)}previousSiblingsIterator(e){return new ci(this,e,this._node(e).previousSibling,ci.PREV)}nextSiblingsIterator(e){return new ci(this,e,this._node(e).nextSibling,ci.NEXT)}ancestorsIterator(e){return new ci(this,e,e,ci.PARENT)}treeIterator(e,r){let n=r&&r.reverse;return new ci(this,e,n?this.lastInclusiveDescendant(e):e,n?ci.PRECEDING:ci.FOLLOWING)}index(e){let r=this._node(e),n=this._node(r.parent);if(!n)return-1;let i=r.getCachedIndex(n);if(i>=0)return i;i=0;let s=n.firstChild;if(n.childIndexCachedUpTo){let a=this._node(n.childIndexCachedUpTo);s=a.nextSibling,i=a.getCachedIndex(n)+1}for(;s;){let a=this._node(s);if(a.setCachedIndex(n,i),s===e)break;++i,s=a.nextSibling}return n.childIndexCachedUpTo=e,i}childrenCount(e){let r=this._node(e);return r.lastChild?this.index(r.lastChild)+1:0}compareTreePosition(e,r){if(e===r)return 0;let n=[];{let f=e;for(;f;){if(f===r)return pa.CONTAINS|pa.PRECEDING;n.push(f),f=this.parent(f)}}let i=[];{let f=r;for(;f;){if(f===e)return pa.CONTAINED_BY|pa.FOLLOWING;i.push(f),f=this.parent(f)}}let s=Wu(n,0);if(!s||s!==Wu(i,0))return pa.DISCONNECTED;let a=0,c=Math.min(n.length,i.length);for(let f=0;f<c;++f){let d=Wu(n,f),h=Wu(i,f);if(d!==h)break;a=f}let l=this.index(Wu(n,a+1));return this.index(Wu(i,a+1))<l?pa.PRECEDING:pa.FOLLOWING}remove(e){let r=this._node(e),n=this._node(r.parent),i=this._node(r.previousSibling),s=this._node(r.nextSibling);return n&&(n.firstChild===e&&(n.firstChild=r.nextSibling),n.lastChild===e&&(n.lastChild=r.previousSibling)),i&&(i.nextSibling=r.nextSibling),s&&(s.previousSibling=r.previousSibling),r.parent=null,r.previousSibling=null,r.nextSibling=null,r.cachedIndex=-1,r.cachedIndexVersion=NaN,n&&n.childrenChanged(),e}insertBefore(e,r){let n=this._node(e),i=this._node(n.previousSibling),s=this._node(r),a=this._node(n.parent);if(s.isAttached)throw Error("Given object is already present in this SymbolTree, remove it first");return s.parent=n.parent,s.previousSibling=n.previousSibling,s.nextSibling=e,n.previousSibling=r,i&&(i.nextSibling=r),a&&a.firstChild===e&&(a.firstChild=r),a&&a.childrenChanged(),r}insertAfter(e,r){let n=this._node(e),i=this._node(n.nextSibling),s=this._node(r),a=this._node(n.parent);if(s.isAttached)throw Error("Given object is already present in this SymbolTree, remove it first");return s.parent=n.parent,s.previousSibling=e,s.nextSibling=n.nextSibling,n.nextSibling=r,i&&(i.previousSibling=r),a&&a.lastChild===e&&(a.lastChild=r),a&&a.childrenChanged(),r}prependChild(e,r){let n=this._node(e),i=this._node(r);if(i.isAttached)throw Error("Given object is already present in this SymbolTree, remove it first");return n.hasChildren?this.insertBefore(n.firstChild,r):(i.parent=e,n.firstChild=r,n.lastChild=r,n.childrenChanged()),r}appendChild(e,r){let n=this._node(e),i=this._node(r);if(i.isAttached)throw Error("Given object is already present in this SymbolTree, remove it first");return n.hasChildren?this.insertAfter(n.lastChild,r):(i.parent=e,n.firstChild=r,n.lastChild=r,n.childrenChanged()),r}};oN.exports=Ub,Ub.TreePosition=pa});var PN=ri((yje,CN)=>{"use strict";CN.exports=function(t,e){e||(e={}),typeof e=="function"&&(e={cmp:e});var r=typeof e.cycles=="boolean"?e.cycles:!1,n=e.cmp&&(function(s){return function(a){return function(c,l){var u={key:c,value:a[c]},f={key:l,value:a[l]};return s(u,f)}}})(e.cmp),i=[];return o((function s(a){if(a&&a.toJSON&&typeof a.toJSON=="function"&&(a=a.toJSON()),a!==void 0){if(typeof a=="number")return isFinite(a)?""+a:"null";if(typeof a!="object")return JSON.stringify(a);var c,l;if(Array.isArray(a)){for(l="[",c=0;c<a.length;c++)c&&(l+=","),l+=s(a[c])||"null";return l+"]"}if(a===null)return"null";if(i.indexOf(a)!==-1){if(r)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var u=i.push(a)-1,f=Object.keys(a).sort(n&&n(a));for(l="",c=0;c<f.length;c++){var d=f[c],h=s(a[d]);h&&(l&&(l+=","),l+=JSON.stringify(d)+":"+h)}return i.splice(u,1),"{"+l+"}"}}),"stringify")(t)}});var OB=ri((kct,MB)=>{"use strict";var O0=Object.prototype.hasOwnProperty,vB=Object.prototype.toString,EB=Object.defineProperty,CB=Object.getOwnPropertyDescriptor,PB=o(function(e){return typeof Array.isArray=="function"?Array.isArray(e):vB.call(e)==="[object Array]"},"isArray"),IB=o(function(e){if(!e||vB.call(e)!=="[object Object]")return!1;var r=O0.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&O0.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!n)return!1;var i;for(i in e);return typeof i>"u"||O0.call(e,i)},"isPlainObject"),_B=o(function(e,r){EB&&r.name==="__proto__"?EB(e,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):e[r.name]=r.newValue},"setProperty"),DB=o(function(e,r){if(r==="__proto__")if(O0.call(e,r)){if(CB)return CB(e,r).value}else return;return e[r]},"getProperty");MB.exports=o(function t(){var e,r,n,i,s,a,c=arguments[0],l=1,u=arguments.length,f=!1;for(typeof c=="boolean"&&(f=c,c=arguments[1]||{},l=2),(c==null||typeof c!="object"&&typeof c!="function")&&(c={});l<u;++l)if(e=arguments[l],e!=null)for(r in e)n=DB(c,r),i=DB(e,r),c!==i&&(f&&i&&(IB(i)||(s=PB(i)))?(s?(s=!1,a=n&&PB(n)?n:[]):a=n&&IB(n)?n:{},_B(c,{name:r,newValue:t(f,a,i)})):typeof i<"u"&&_B(c,{name:r,newValue:i}));return c},"extend")});var _3=ri((qpt,ZE)=>{(function(){var t;typeof ZE<"u"?t=ZE.exports=n:t=(function(){return this||(0,eval)("this")})(),t.format=n,t.vsprintf=r,typeof console<"u"&&typeof console.log=="function"&&(t.printf=e);function e(){console.log(n.apply(null,arguments))}o(e,"printf");function r(i,s){return n.apply(null,[i].concat(s))}o(r,"vsprintf");function n(i){for(var s=1,a=[].slice.call(arguments),c=0,l=i.length,u="",f,d=!1,h,m,p=!1,g,y=o(function(){return a[s++]},"nextArg"),b=o(function(){for(var w="";/\d/.test(i[c]);)w+=i[c++],f=i[c];return w.length>0?parseInt(w):null},"slurpNumber");c<l;++c)if(f=i[c],d)switch(d=!1,f=="."?(p=!1,f=i[++c]):f=="0"&&i[c+1]=="."?(p=!0,c+=2,f=i[c]):p=!0,g=b(),f){case"b":u+=parseInt(y(),10).toString(2);break;case"c":h=y(),typeof h=="string"||h instanceof String?u+=h:u+=String.fromCharCode(parseInt(h,10));break;case"d":u+=parseInt(y(),10);break;case"f":m=String(parseFloat(y()).toFixed(g||6)),u+=p?m:m.replace(/^0/,"");break;case"j":u+=JSON.stringify(y());break;case"o":u+="0"+parseInt(y(),10).toString(8);break;case"s":u+=y();break;case"x":u+="0x"+parseInt(y(),10).toString(16);break;case"X":u+="0x"+parseInt(y(),10).toString(16).toUpperCase();break;default:u+=f;break}else f==="%"?d=!0:u+=f;return u}o(n,"format")})()});var Q3=ri(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0}),Vi.PathError=Vi.TokenData=void 0,Vi.parse=fC,Vi.compile=UJ,Vi.match=HJ,Vi.pathToRegexp=q3,Vi.stringify=jJ;var cC="/",lC=o(t=>t,"NOOP_VALUE"),W3=/^[$_\p{ID_Start}]$/u,uC=/^[$\u200c\u200d\p{ID_Continue}]$/u,BJ={"{":"{","}":"}","(":"(",")":")","[":"[","]":"]","+":"+","?":"?","!":"!"};function zJ(t){return t.replace(/[{}()\[\]+?!:*\\]/g,"\\$&")}o(zJ,"escapeText");function Ls(t){return t.replace(/[.+*?^${}()[\]|/\\]/g,"\\$&")}o(Ls,"escape");var K0=class{static{o(this,"TokenData")}constructor(e,r){this.tokens=e,this.originalPath=r}};Vi.TokenData=K0;var pl=class extends TypeError{static{o(this,"PathError")}constructor(e,r){let n=e;r&&(n+=`: ${r}`),n+="; visit https://git.new/pathToRegexpError for info",super(n),this.originalPath=r}};Vi.PathError=pl;function fC(t,e={}){let{encodePath:r=lC}=e,n=[...t],i=[],s=0,a=0;function c(){let u="";if(W3.test(n[s]))do u+=n[s++];while(uC.test(n[s]));else if(n[s]==='"'){let f=s;for(;s++<n.length;){if(n[s]==='"'){s++,f=0;break}n[s]==="\\"&&s++,u+=n[s]}if(f)throw new pl(`Unterminated quote at index ${f}`,t)}if(!u)throw new pl(`Missing parameter name at index ${s}`,t);return u}for(o(c,"name");s<n.length;){let u=n[s],f=BJ[u];f?i.push({type:f,index:s++,value:u}):u==="\\"?i.push({type:"escape",index:s++,value:n[s++]}):u===":"?i.push({type:"param",index:s++,value:c()}):u==="*"?i.push({type:"wildcard",index:s++,value:c()}):i.push({type:"char",index:s++,value:u})}i.push({type:"end",index:s,value:""});function l(u){let f=[];for(;;){let d=i[a++];if(d.type===u)break;if(d.type==="char"||d.type==="escape"){let h=d.value,m=i[a];for(;m.type==="char"||m.type==="escape";)h+=m.value,m=i[++a];f.push({type:"text",value:r(h)});continue}if(d.type==="param"||d.type==="wildcard"){f.push({type:d.type,name:d.value});continue}if(d.type==="{"){f.push({type:"group",tokens:l("}")});continue}throw new pl(`Unexpected ${d.type} at index ${d.index}, expected ${u}`,t)}return f}return o(l,"consumeUntil"),new K0(l("end"),t)}o(fC,"parse");function UJ(t,e={}){let{encode:r=encodeURIComponent,delimiter:n=cC}=e,i=typeof t=="object"?t:fC(t,e),s=j3(i.tokens,n,r);return o(function(c={}){let[l,...u]=s(c);if(u.length)throw new TypeError(`Missing parameters: ${u.join(", ")}`);return l},"path")}o(UJ,"compile");function j3(t,e,r){let n=t.map(i=>$J(i,e,r));return i=>{let s=[""];for(let a of n){let[c,...l]=a(i);s[0]+=c,s.push(...l)}return s}}o(j3,"tokensToFunction");function $J(t,e,r){if(t.type==="text")return()=>[t.value];if(t.type==="group"){let i=j3(t.tokens,e,r);return s=>{let[a,...c]=i(s);return c.length?[""]:[a]}}let n=r||lC;return t.type==="wildcard"&&r!==!1?i=>{let s=i[t.name];if(s==null)return["",t.name];if(!Array.isArray(s)||s.length===0)throw new TypeError(`Expected "${t.name}" to be a non-empty array`);return[s.map((a,c)=>{if(typeof a!="string")throw new TypeError(`Expected "${t.name}/${c}" to be a string`);return n(a)}).join(e)]}:i=>{let s=i[t.name];if(s==null)return["",t.name];if(typeof s!="string")throw new TypeError(`Expected "${t.name}" to be a string`);return[n(s)]}}o($J,"tokenToFunction");function HJ(t,e={}){let{decode:r=decodeURIComponent,delimiter:n=cC}=e,{regexp:i,keys:s}=q3(t,e),a=s.map(c=>r===!1?lC:c.type==="param"?r:l=>l.split(n).map(r));return o(function(l){let u=i.exec(l);if(!u)return!1;let f=u[0],d=Object.create(null);for(let h=1;h<u.length;h++){if(u[h]===void 0)continue;let m=s[h-1],p=a[h-1];d[m.name]=p(u[h])}return{path:f,params:d}},"match")}o(HJ,"match");function q3(t,e={}){let{delimiter:r=cC,end:n=!0,sensitive:i=!1,trailing:s=!0}=e,a=[],c=i?"":"i",l=[];for(let d of Y3(t,[])){let h=typeof d=="object"?d:fC(d,e);for(let m of X0(h.tokens,0,[]))l.push(VJ(m,r,a,h.originalPath))}let u=`^(?:${l.join("|")})`;return s&&(u+=`(?:${Ls(r)}$)?`),u+=n?"$":`(?=${Ls(r)}|$)`,{regexp:new RegExp(u,c),keys:a}}o(q3,"pathToRegexp");function Y3(t,e){if(Array.isArray(t))for(let r of t)Y3(r,e);else e.push(t);return e}o(Y3,"pathsToArray");function*X0(t,e,r){if(e===t.length)return yield r;let n=t[e];if(n.type==="group")for(let i of X0(n.tokens,0,r.slice()))yield*X0(t,e+1,i);else r.push(n);yield*X0(t,e+1,r)}o(X0,"flatten");function VJ(t,e,r,n){let i="",s="",a=!0;for(let c of t){if(c.type==="text"){i+=Ls(c.value),s+=c.value,a||(a=c.value.includes(e));continue}if(c.type==="param"||c.type==="wildcard"){if(!a&&!s)throw new pl(`Missing text before "${c.name}" ${c.type}`,n);c.type==="param"?i+=`(${WJ(e,a?"":s)}+)`:i+="([\\s\\S]+)",r.push(c),s="",a=!1;continue}}return i}o(VJ,"toRegExpSource");function WJ(t,e){return e.length<2?t.length<2?`[^${Ls(t+e)}]`:`(?:(?!${Ls(t)})[^${Ls(e)}])`:t.length<2?`(?:(?!${Ls(e)})[^${Ls(t)}])`:`(?:(?!${Ls(e)}|${Ls(t)})[\\s\\S])`}o(WJ,"negate");function G3(t){let e="",r=0;function n(i){return qJ(i)&&YJ(t[r])?i:JSON.stringify(i)}for(o(n,"name");r<t.length;){let i=t[r++];if(i.type==="text"){e+=zJ(i.value);continue}if(i.type==="group"){e+=`{${G3(i.tokens)}}`;continue}if(i.type==="param"){e+=`:${n(i.name)}`;continue}if(i.type==="wildcard"){e+=`*${n(i.name)}`;continue}throw new TypeError(`Unknown token type: ${i.type}`)}return e}o(G3,"stringifyTokens");function jJ(t){return G3(t.tokens)}o(jJ,"stringify");function qJ(t){let[e,...r]=t;return W3.test(e)&&r.every(n=>uC.test(n))}o(qJ,"isNameSafe");function YJ(t){return t&&t.type==="text"?!uC.test(t.value[0]):!0}o(YJ,"isNextNameSafe")});var o4=ri((FC,LC)=>{(function(t,e){typeof FC=="object"&&typeof LC<"u"?LC.exports=e():typeof define=="function"&&define.amd?define(e):(t=t||self,t.SweetScroll=e())})(FC,function(){"use strict";var t=o(function(){return t=Object.assign||o(function(_){for(var z,U=1,q=arguments.length;U<q;U++){z=arguments[U];for(var be in z)Object.prototype.hasOwnProperty.call(z,be)&&(_[be]=z[be])}return _},"__assign"),t.apply(this,arguments)},"__assign"),e=!!(typeof window<"u"&&window.document&&window.document.createElement),r=e?window.history&&"pushState"in window.history&&window.location.protocol!=="file:":!1,n=(function(){var L=!1;if(!e)return L;try{var _=window,z=Object.defineProperty({},"passive",{get:o(function(){L=!0},"get")});_.addEventListener("test",null,z),_.removeEventListener("test",null,z)}catch{}return L})(),i=o(function(L){return typeof L=="string"},"isString"),s=o(function(L){return typeof L=="function"},"isFunction"),a=o(function(L){return Array.isArray(L)},"isArray"),c=o(function(L){return!a(L)&&L-parseFloat(L)+1>=0},"isNumeric"),l=o(function(L,_){return L&&L.hasOwnProperty(_)},"hasProp"),u=e?window.requestAnimationFrame.bind(window):null,f=e?window.cancelAnimationFrame.bind(window):null,d=Math.cos,h=Math.sin,m=Math.pow,p=Math.sqrt,g=Math.PI,y={linear:o(function(L){return L},"linear"),easeInQuad:o(function(L,_,z,U,q){return U*(_/=q)*_+z},"easeInQuad"),easeOutQuad:o(function(L,_,z,U,q){return-U*(_/=q)*(_-2)+z},"easeOutQuad"),easeInOutQuad:o(function(L,_,z,U,q){return(_/=q/2)<1?U/2*_*_+z:-U/2*(--_*(_-2)-1)+z},"easeInOutQuad"),easeInCubic:o(function(L,_,z,U,q){return U*(_/=q)*_*_+z},"easeInCubic"),easeOutCubic:o(function(L,_,z,U,q){return U*((_=_/q-1)*_*_+1)+z},"easeOutCubic"),easeInOutCubic:o(function(L,_,z,U,q){return(_/=q/2)<1?U/2*_*_*_+z:U/2*((_-=2)*_*_+2)+z},"easeInOutCubic"),easeInQuart:o(function(L,_,z,U,q){return U*(_/=q)*_*_*_+z},"easeInQuart"),easeOutQuart:o(function(L,_,z,U,q){return-U*((_=_/q-1)*_*_*_-1)+z},"easeOutQuart"),easeInOutQuart:o(function(L,_,z,U,q){return(_/=q/2)<1?U/2*_*_*_*_+z:-U/2*((_-=2)*_*_*_-2)+z},"easeInOutQuart"),easeInQuint:o(function(L,_,z,U,q){return U*(_/=q)*_*_*_*_+z},"easeInQuint"),easeOutQuint:o(function(L,_,z,U,q){return U*((_=_/q-1)*_*_*_*_+1)+z},"easeOutQuint"),easeInOutQuint:o(function(L,_,z,U,q){return(_/=q/2)<1?U/2*_*_*_*_*_+z:U/2*((_-=2)*_*_*_*_+2)+z},"easeInOutQuint"),easeInSine:o(function(L,_,z,U,q){return-U*d(_/q*(g/2))+U+z},"easeInSine"),easeOutSine:o(function(L,_,z,U,q){return U*h(_/q*(g/2))+z},"easeOutSine"),easeInOutSine:o(function(L,_,z,U,q){return-U/2*(d(g*_/q)-1)+z},"easeInOutSine"),easeInExpo:o(function(L,_,z,U,q){return _===0?z:U*m(2,10*(_/q-1))+z},"easeInExpo"),easeOutExpo:o(function(L,_,z,U,q){return _===q?z+U:U*(-m(2,-10*_/q)+1)+z},"easeOutExpo"),easeInOutExpo:o(function(L,_,z,U,q){return _===0?z:_===q?z+U:(_/=q/2)<1?U/2*m(2,10*(_-1))+z:U/2*(-m(2,-10*--_)+2)+z},"easeInOutExpo"),easeInCirc:o(function(L,_,z,U,q){return-U*(p(1-(_/=q)*_)-1)+z},"easeInCirc"),easeOutCirc:o(function(L,_,z,U,q){return U*p(1-(_=_/q-1)*_)+z},"easeOutCirc"),easeInOutCirc:o(function(L,_,z,U,q){return(_/=q/2)<1?-U/2*(p(1-_*_)-1)+z:U/2*(p(1-(_-=2)*_)+1)+z},"easeInOutCirc")},b=o(function(L){return Array.prototype.slice.call(L?document.querySelectorAll(L):[])},"$$"),w=o(function(L){return b(L).shift()||null},"$"),k=o(function(L){return L instanceof Element},"isElement"),T=o(function(L){return L===window},"isWindow"),v=o(function(L){return L===document.documentElement||L===document.body},"isRootContainer"),S=o(function(L,_){if(k(_))return L===_;for(var z=b(_),U=z.length;--U>=0&&z[U]!==L;);return U>-1},"matches"),M=o(function(L){return Math.max(L.scrollHeight,L.clientHeight,L.offsetHeight)},"getHeight"),P=o(function(L){return Math.max(L.scrollWidth,L.clientWidth,L.offsetWidth)},"getWidth"),N=o(function(L){return{width:P(L),height:M(L)}},"getSize"),O=o(function(L){var _=T(L)||v(L);return{viewport:{width:_?Math.min(window.innerWidth,document.documentElement.clientWidth):L.clientWidth,height:_?window.innerHeight:L.clientHeight},size:_?{width:Math.max(P(document.body),P(document.documentElement)),height:Math.max(M(document.body),M(document.documentElement))}:N(L)}},"getViewportAndElementSizes"),Y={y:"scrollTop",x:"scrollLeft"},A={y:"pageYOffset",x:"pageXOffset"},R=o(function(L,_){return T(L)?L[A[_]]:L[Y[_]]},"getScroll"),F=o(function(L,_,z){if(T(L)){var U=z==="y";L.scrollTo(U?L.pageXOffset:_,U?_:L.pageYOffset)}else L[Y[z]]=_},"setScroll"),$=o(function(L,_){var z=L.getBoundingClientRect();if(z.width||z.height){var U={top:0,left:0},q=void 0;if(T(_)||v(_))q=document.documentElement,U.top=window[A.y],U.left=window[A.x];else{q=_;var be=q.getBoundingClientRect();U.top=be.top*-1+q[Y.y],U.left=be.left*-1+q[Y.x]}return{top:z.top+U.top-q.clientTop,left:z.left+U.left-q.clientLeft}}return z},"getOffset"),W=(function(){return e?"onwheel"in document?"wheel":"mousewheel":"wheel"})(),Q=o(function(L){return L==="wheel"?W:L},"eventName"),re=o(function(L,_,z,U,q){z.split(" ").forEach(function(be){L[_](Q(be),U,n?{passive:q}:!1)})},"apply"),fe=o(function(L,_,z,U){return re(L,"addEventListener",_,z,U)},"addEvent"),E=o(function(L,_,z,U){return re(L,"removeEventListener",_,z,U)},"removeEvent"),_e=/^(\+|-)=(\d+(?:\.\d+)?)$/,Ge=o(function(L,_){var z={top:0,left:0,relative:!1};if(l(L,"top")||l(L,"left"))z=t({},z,L);else if(a(L))if(L.length>1)z.top=L[0],z.left=L[1];else if(L.length===1)z.top=_?L[0]:0,z.left=_?0:L[0];else return null;else if(c(L))_?z.top=L:z.left=L;else if(i(L)){var U=L.trim().match(_e);if(!U)return null;var q=U[1],be=parseInt(U[2],10);q==="+"?(z.top=_?be:0,z.left=_?0:be):(z.top=_?-be:0,z.left=_?0:-be),z.relative=!0}else return null;return z},"parseCoordinate"),D={trigger:"[data-scroll]",header:"[data-scroll-header]",duration:1e3,easing:"easeOutQuint",offset:0,vertical:!0,horizontal:!1,cancellable:!0,updateURL:!1,preventDefault:!0,stopPropagation:!0,before:null,after:null,cancel:null,complete:null,step:null},yt="click",Yt="wheel touchstart touchmove",Nn=(function(){function L(_,z){var U=this;this.$el=null,this.ctx={$trigger:null,opts:null,progress:!1,pos:null,startPos:null,easing:null,start:0,id:0,cancel:!1,hash:null},this.loop=function(be){var gt=U,mt=gt.$el,tt=gt.ctx;if(tt.start||(tt.start=be),!tt.progress||!mt){U.stop();return}var cn=tt.opts,dr=tt.pos,Yr=tt.start,Ii=tt.startPos,ss=tt.easing,An=cn.duration,ei={top:"y",left:"x"},ln=be-Yr,_t=Math.min(1,Math.max(ln/An,0));Object.keys(dr).forEach(function(os){var V=dr[os],K=Ii[os],ve=V-K;if(ve!==0){var Re=ss(_t,An*_t,0,1,An);F(mt,Math.round(K+ve*Re),ei[os])}}),ln<=An?(U.hook(cn,"step",_t),tt.id=L.raf(U.loop)):U.stop(!0)},this.handleClick=function(be){for(var gt=U.opts,mt=be.target;mt&&mt!==document;mt=mt.parentNode)if(S(mt,gt.trigger)){var tt=JSON.parse(mt.getAttribute("data-scroll-options")||"{}"),cn=mt.getAttribute("data-scroll"),dr=cn||mt.getAttribute("href"),Yr=t({},gt,tt),Ii=Yr.preventDefault,ss=Yr.stopPropagation,An=Yr.vertical,ei=Yr.horizontal;Ii&&be.preventDefault(),ss&&be.stopPropagation(),U.ctx.$trigger=mt,ei&&An?U.to(dr,Yr):An?U.toTop(dr,Yr):ei&&U.toLeft(dr,Yr);break}},this.handleStop=function(be){var gt=U.ctx,mt=gt.opts;mt&&mt.cancellable?(gt.cancel=!0,U.stop()):be.preventDefault()},this.opts=t({},D,_||{});var q=null;e&&(typeof z=="string"?q=w(z):z!=null?q=z:q=window),this.$el=q,q&&this.bind(!0,!1)}return o(L,"SweetScroll"),L.create=function(_,z){return new L(_,z)},L.prototype.to=function(_,z){if(e){var U=this,q=U.$el,be=U.ctx,gt=U.opts,mt=be.$trigger,tt=t({},gt,z||{}),cn=tt.offset,dr=tt.vertical,Yr=tt.horizontal,Ii=k(tt.header)?tt.header:w(tt.header),ss=/^#/,An=i(_)&&ss.test(_)?_:null;if(be.opts=tt,be.cancel=!1,be.hash=An,this.stop(),!!q){var ei=Ge(cn,dr),ln=Ge(_,dr),_t={top:0,left:0};if(ln)if(ln.relative){var os=R(q,dr?"y":"x");_t.top=dr?os+ln.top:ln.top,_t.left=dr?ln.left:os+ln.left}else _t=ln;else if(i(_)&&_!=="#"){var V=w(_);if(!V)return;_t=$(V,q)}ei&&(_t.top+=ei.top,_t.left+=ei.left),Ii&&(_t.top=Math.max(0,_t.top-N(Ii).height));var K=O(q),ve=K.viewport,Re=K.size;if(_t.top=dr?Math.max(0,Math.min(Re.height-ve.height,_t.top)):R(q,"y"),_t.left=Yr?Math.max(0,Math.min(Re.width-ve.width,_t.left)):R(q,"x"),this.hook(tt,"before",_t,mt)===!1){be.opts=null;return}be.pos=_t,this.start(tt),this.bind(!1,!0)}}},L.prototype.toTop=function(_,z){this.to(_,t({},z||{},{vertical:!0,horizontal:!1}))},L.prototype.toLeft=function(_,z){this.to(_,t({},z||{},{vertical:!1,horizontal:!0}))},L.prototype.toElement=function(_,z){var U=this.$el;!e||!U||this.to($(_,U),z||{})},L.prototype.stop=function(_){_===void 0&&(_=!1);var z=this,U=z.$el,q=z.ctx,be=q.pos;!U||!q.progress||(L.caf(q.id),q.progress=!1,q.start=0,q.id=0,_&&be&&(F(U,be.left,"x"),F(U,be.top,"y")),this.complete())},L.prototype.update=function(_){if(this.$el){var z=t({},this.opts,_);this.stop(),this.unbind(!0,!0),this.opts=z,this.bind(!0,!1)}},L.prototype.destroy=function(){this.$el&&(this.stop(),this.unbind(!0,!0),this.$el=null)},L.prototype.onBefore=function(_,z){return!0},L.prototype.onStep=function(_){},L.prototype.onAfter=function(_,z){},L.prototype.onCancel=function(){},L.prototype.onComplete=function(_){},L.prototype.start=function(_){var z=this.ctx;z.opts=_,z.progress=!0,z.easing=s(_.easing)?_.easing:y[_.easing];var U=this.$el,q={top:R(U,"y"),left:R(U,"x")};z.startPos=q,z.id=L.raf(this.loop)},L.prototype.complete=function(){var _=this,z=_.$el,U=_.ctx,q=U.hash,be=U.cancel,gt=U.opts,mt=U.pos,tt=U.$trigger;if(!(!z||!gt)){if(q!=null&&q!==window.location.hash){var cn=gt.updateURL;e&&r&&cn!==!1&&window.history[cn==="replace"?"replaceState":"pushState"](null,"",q)}this.unbind(!1,!0),U.opts=null,U.$trigger=null,be?this.hook(gt,"cancel"):this.hook(gt,"after",mt,tt),this.hook(gt,"complete",be)}},L.prototype.hook=function(_,z){for(var U=[],q=2;q<arguments.length;q++)U[q-2]=arguments[q];var be,gt=_[z],mt,tt;return s(gt)&&(mt=gt.apply(this,U.concat([this]))),tt=(be=this)["on"+(z[0].toUpperCase()+z.slice(1))].apply(be,U),mt!==void 0?mt:tt},L.prototype.bind=function(_,z){var U=this,q=U.$el,be=U.ctx.opts;q&&(_&&fe(q,yt,this.handleClick,!1),z&&fe(q,Yt,this.handleStop,be?be.cancellable:!0))},L.prototype.unbind=function(_,z){var U=this,q=U.$el,be=U.ctx.opts;q&&(_&&E(q,yt,this.handleClick,!1),z&&E(q,Yt,this.handleStop,be?be.cancellable:!0))},L.raf=u,L.caf=f,L})();return Nn})});function x(t){if(!t)throw new Error("Assertion failed.")}var Ha,Ze,El,Z,$s,bz,qe,ge,br,lt,Va,_P,ji,Cl,qi,Pl,Yi,Il,kx,jf,Tn,AP,FP,_o,ze,LP,ut,kTt,BP,qf,wz,xz,kt,_l,kz,Dl,Sz,Tz,Zm,Ht,Ft,Do,ep,Sx,vz,uee,Mo,Hs,zP,gz,UP,Ez,$a,DP,Wa,MP,Vs,OP,tp,RP,Cz,Ml,Tx,Gi,Pz,Iz,_z,Dz,vx,ja,qa,$P,Jm,yz,bx,NP,wx,fee,xx,STt,TTt,Mz,Oz,Ue=he(()=>{o(x,"assert");Ha=o(t=>{let e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},"normalizeRotation"),Ze=o(t=>t&&t[t.length-1],"last"),El=o(t=>t>=0&&t<2**32,"isU32"),Z=o(t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},"readExpGolomb"),$s=o(t=>{let e=Z(t);return(e&1)===0?-(e>>1):e+1>>1},"readSignedExpGolomb"),bz=o((t,e,r,n)=>{for(let i=e;i<r;i++){let s=Math.floor(i/8),a=t[s],c=7-(i&7);a&=~(1<<c),a|=(n&1<<r-i-1)>>r-i-1<<c,t[s]=a}},"writeBits"),qe=o(t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),"toUint8Array"),ge=o(t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),"toDataView"),br=new TextDecoder,lt=new TextEncoder,Va=o(t=>{for(let e=0;e<t.length;e++)if(t.charCodeAt(e)>255)return!1;return!0},"isIso88591Compatible"),_P=o(t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),"invertObject"),ji={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Cl=_P(ji),qi={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Pl=_P(qi),Yi={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Il=_P(Yi),kx=o(t=>!!t&&!!t.primaries&&!!t.transfer&&!!t.matrix&&t.fullRange!==void 0,"colorSpaceIsComplete"),jf=o(t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),"isAllowSharedBufferSource"),Tn=class{static{o(this,"AsyncMutex")}constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,r=new Promise(i=>{let s=!1;e=o(()=>{s||(i(),this.pending--,s=!0)},"resolver")}),n=this.currentPromise;return this.currentPromise=r,this.pending++,await n,e}},AP=o(t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),"bytesToHexString"),FP=o(t=>(t=t>>1&1431655765|(t&1431655765)<<1,t=t>>2&858993459|(t&858993459)<<2,t=t>>4&252645135|(t&252645135)<<4,t=t>>8&16711935|(t&16711935)<<8,t=t>>16&65535|(t&65535)<<16,t>>>0),"reverseBitsU32"),_o=o((t,e,r)=>{let n=0,i=t.length-1,s=-1;for(;n<=i;){let a=n+i>>1,c=r(t[a]);c===e?(s=a,i=a-1):c<e?n=a+1:i=a-1}return s},"binarySearchExact"),ze=o((t,e,r)=>{let n=0,i=t.length-1,s=-1;for(;n<=i;){let a=n+(i-n+1)/2|0;r(t[a])<=e?(s=a,n=a+1):i=a-1}return s},"binarySearchLessOrEqual"),LP=o((t,e,r)=>{let n=ze(t,r(e),r);t.splice(n+1,0,e)},"insertSorted"),ut=o(()=>{let t,e;return{promise:new Promise((n,i)=>{t=n,e=i}),resolve:t,reject:e}},"promiseWithResolvers"),kTt=o((t,e)=>{let r=t.indexOf(e);r!==-1&&t.splice(r,1)},"removeItem"),BP=o((t,e)=>{for(let r=t.length-1;r>=0;r--)if(e(t[r]))return t[r]},"findLast"),qf=o((t,e)=>{for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1},"findLastIndex"),wz=o(async function*(t){Symbol.iterator in t?yield*t[Symbol.iterator]():yield*t[Symbol.asyncIterator]()},"toAsyncIterator"),xz=o(t=>{if(!(Symbol.iterator in t)&&!(Symbol.asyncIterator in t))throw new TypeError("Argument must be an iterable or async iterable.")},"validateAnyIterable"),kt=o(t=>{throw new Error(`Unexpected value: ${t}`)},"assertNever"),_l=o((t,e,r)=>{let n=t.getUint8(e),i=t.getUint8(e+1),s=t.getUint8(e+2);return r?n|i<<8|s<<16:n<<16|i<<8|s},"getUint24"),kz=o((t,e,r)=>_l(t,e,r)<<8>>8,"getInt24"),Dl=o((t,e,r,n)=>{r=r>>>0,r=r&16777215,n?(t.setUint8(e,r&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r>>>16&255)):(t.setUint8(e,r>>>16&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r&255))},"setUint24"),Sz=o((t,e,r,n)=>{r=Ht(r,-8388608,8388607),r<0&&(r=r+16777216&16777215),Dl(t,e,r,n)},"setInt24"),Tz=o((t,e,r,n)=>{n?(t.setUint32(e+0,r,!0),t.setInt32(e+4,Math.floor(r/2**32),!0)):(t.setInt32(e+0,Math.floor(r/2**32),!0),t.setUint32(e+4,r,!0))},"setInt64"),Zm=o((t,e)=>({async next(){let r=await t.next();return r.done?{value:void 0,done:!0}:{value:e(r.value),done:!1}},return(){return t.return()},throw(r){return t.throw(r)},[Symbol.asyncIterator](){return this}}),"mapAsyncGenerator"),Ht=o((t,e,r)=>Math.max(e,Math.min(r,t)),"clamp"),Ft="und",Do=o(t=>{let e=Math.round(t);return Math.abs(t/e-1)<10*Number.EPSILON?e:t},"roundIfAlmostInteger"),ep=o((t,e)=>Math.round(t/e)*e,"roundToMultiple"),Sx=o((t,e)=>Math.floor(t/e)*e,"floorToMultiple"),vz=o(t=>{let e=0;for(;t;)e++,t>>=1;return e},"ilog"),uee=/^[a-z]{3}$/,Mo=o(t=>uee.test(t),"isIso639Dash2LanguageCode"),Hs=1e6*(1+Number.EPSILON),zP=o((t,e)=>{let r={...t,...e};if(t.headers||e.headers){let n=t.headers?gz(t.headers):{},i=e.headers?gz(e.headers):{},s={...n};Object.entries(i).forEach(([a,c])=>{let l=Object.keys(s).find(u=>u.toLowerCase()===a.toLowerCase());l&&delete s[l],s[a]=c}),r.headers=s}return r},"mergeRequestInit"),gz=o(t=>{if(t instanceof Headers){let e={};return t.forEach((r,n)=>{e[n]=r}),e}if(Array.isArray(t)){let e={};return t.forEach(([r,n])=>{e[r]=n}),e}return t},"normalizeHeaders"),UP=o(async(t,e,r,n,i)=>{let s=0;for(;;)try{return await t(e,r)}catch(a){if(i())throw a;s++;let c=n(s,a,e);if(c===null)throw a;if(console.error("Retrying failed fetch. Error:",a),!Number.isFinite(c)||c<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(c>0&&await new Promise(l=>setTimeout(l,1e3*c)),i())throw a}},"retriedFetch"),Ez=o((t,e)=>{let r=t<0?-1:1;t=Math.abs(t);let n=0,i=1,s=1,a=0,c=t;for(;;){let l=Math.floor(c),u=l*s+n,f=l*a+i;if(f>e)return{numerator:r*s,denominator:a};if(n=s,i=a,s=u,a=f,c=1/(c-l),!isFinite(c))break}return{numerator:r*s,denominator:a}},"computeRationalApproximation"),$a=class{static{o(this,"CallSerializer")}constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},DP=null,Wa=o(()=>DP!==null?DP:DP=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),"isWebKit"),MP=null,Vs=o(()=>MP!==null?MP:MP=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),"isFirefox"),OP=null,tp=o(()=>OP!==null?OP:OP=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),"isChromium"),RP=null,Cz=o(()=>{if(RP!==null)return RP;if(typeof navigator>"u")return null;let t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?RP=Number(t[1]):null},"getChromiumVersion"),Ml=o((t,e)=>t!==-1?t:e,"coalesceIndex"),Tx=o((t,e,r,n)=>t<=n&&r<=e,"closedIntervalsOverlap"),Gi=o(function*(t){for(let e in t){let r=t[e];r!==void 0&&(yield{key:e,value:r})}},"keyValueIterator"),Pz=o(t=>{switch(t.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},"imageMimeTypeToExtension"),Iz=o(t=>{let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r},"base64ToBytes"),_z=o(t=>{let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)},"bytesToBase64"),Dz=o((t,e)=>{if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0},"uint8ArraysAreEqual"),vx=o(()=>{Symbol.dispose??=Symbol("Symbol.dispose")},"polyfillSymbolDispose"),ja=o(t=>typeof t=="number"&&!Number.isNaN(t),"isNumber"),qa=o(t=>{x(t.den!==0);let e=Math.abs(t.num),r=Math.abs(t.den);for(;r!==0;){let i=e%r;e=r,r=i}let n=e||1;return{num:t.num/n,den:t.den/n}},"simplifyRational"),$P=o((t,e)=>{if(typeof t!="object"||!t)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)},"validateRectangle"),yz=1,bx=new Map,NP=new Map,wx=o(()=>typeof window>"u","shouldUseNativeTimers"),fee=o(()=>{let t=new Map,e=new Map;self.onmessage=r=>{let n=r.data;switch(n.type){case"set-timeout":{let i=setTimeout(()=>{t.delete(n.timerId),self.postMessage({type:"fire",timerId:n.timerId})},n.delay);t.set(n.timerId,i)}break;case"set-interval":{let i=setInterval(()=>{self.postMessage({type:"fire",timerId:n.timerId})},n.delay);e.set(n.timerId,i)}break;case"clear-timeout":{let i=t.get(n.timerId);i!==void 0&&(clearTimeout(i),t.delete(n.timerId))}break;case"clear-interval":{let i=e.get(n.timerId);i!==void 0&&(clearInterval(i),e.delete(n.timerId))}break}}},"unthrottledTimerWorkerMain"),xx=o(()=>{if(Jm)return Jm;let t=`(${fee.toString()})();`,e=URL.createObjectURL(new Blob([t],{type:"text/javascript"}));return Jm=new Worker(e),URL.revokeObjectURL(e),Jm.onmessage=r=>{let n=r.data,i=bx.get(n.timerId);if(i){bx.delete(n.timerId),i();return}let s=NP.get(n.timerId);s&&s()},Jm},"getUnthrottledTimerWorker"),STt=o((t,e)=>{if(wx())return{id:setTimeout(t,e)};let r=yz++;return bx.set(r,()=>{t()}),xx().postMessage({type:"set-timeout",timerId:r,delay:e}),{id:r}},"setTimeoutUnthrottled"),TTt=o(t=>{if(wx()){clearTimeout(t.id);return}x(typeof t.id=="number"),bx.delete(t.id),xx().postMessage({type:"clear-timeout",timerId:t.id})},"clearTimeoutUnthrottled"),Mz=o((t,e)=>{if(wx())return{id:setInterval(t,e)};let r=yz++;return NP.set(r,()=>{t()}),xx().postMessage({type:"set-interval",timerId:r,delay:e}),{id:r}},"setIntervalUnthrottled"),Oz=o(t=>{if(wx()){clearInterval(t.id);return}x(typeof t.id=="number"),NP.delete(t.id),xx().postMessage({type:"clear-interval",timerId:t.id})},"clearIntervalUnthrottled")});var Gn,Oo,rp,Ro,jr,Rz,lr=he(()=>{Gn=class{static{o(this,"RichImageData")}constructor(e,r){if(this.data=e,this.mimeType=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof r!="string")throw new TypeError("mimeType must be a string.")}},Oo=class{static{o(this,"AttachedFile")}constructor(e,r,n,i){if(this.data=e,this.mimeType=r,this.name=n,this.description=i,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!==void 0&&typeof r!="string")throw new TypeError("mimeType, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("name, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("description, when provided, must be a string.")}},rp=o(t=>{if(!t||typeof t!="object")throw new TypeError("tags must be an object.");if(t.title!==void 0&&typeof t.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(t.artist!==void 0&&typeof t.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(t.album!==void 0&&typeof t.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(t.albumArtist!==void 0&&typeof t.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(t.trackNumber!==void 0&&(!Number.isInteger(t.trackNumber)||t.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(t.tracksTotal!==void 0&&(!Number.isInteger(t.tracksTotal)||t.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(t.discNumber!==void 0&&(!Number.isInteger(t.discNumber)||t.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(t.discsTotal!==void 0&&(!Number.isInteger(t.discsTotal)||t.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(t.genre!==void 0&&typeof t.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(t.date!==void 0&&(!(t.date instanceof Date)||Number.isNaN(t.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(t.lyrics!==void 0&&typeof t.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(t.images!==void 0){if(!Array.isArray(t.images))throw new TypeError("tags.images, when provided, must be an array.");for(let e of t.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(t.comment!==void 0&&typeof t.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(t.raw!==void 0){if(!t.raw||typeof t.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(let e of Object.values(t.raw))if(e!==null&&typeof e!="string"&&!(e instanceof Uint8Array)&&!(e instanceof Gn)&&!(e instanceof Oo))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}},"validateMetadataTags"),Ro=o(t=>t.title===void 0&&t.description===void 0&&t.artist===void 0&&t.album===void 0&&t.albumArtist===void 0&&t.trackNumber===void 0&&t.tracksTotal===void 0&&t.discNumber===void 0&&t.discsTotal===void 0&&t.genre===void 0&&t.date===void 0&&t.lyrics===void 0&&(!t.images||t.images.length===0)&&t.comment===void 0&&(t.raw===void 0||Object.keys(t.raw).length===0),"metadataTagsAreEmpty"),jr={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},Rz=o(t=>{if(!t||typeof t!="object")throw new TypeError("disposition must be an object.");if(t.default!==void 0&&typeof t.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(t.forced!==void 0&&typeof t.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(t.original!==void 0&&typeof t.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(t.commentary!==void 0&&typeof t.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(t.hearingImpaired!==void 0&&typeof t.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(t.visuallyImpaired!==void 0&&typeof t.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")},"validateTrackDisposition")});var Te,Ti=he(()=>{Te=class t{static{o(this,"Bitstream")}constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),r=this.bytes[e]??0,n=7-(this.pos&7),i=(r&1<<n)>>n;return this.pos++,i}readBits(e){if(e===1)return this.readBit();let r=0;for(let n=0;n<e;n++)r<<=1,r|=this.readBit();return r}writeBits(e,r){let n=this.pos+e;for(let i=this.pos;i<n;i++){let s=Math.floor(i/8),a=this.bytes[s],c=7-(i&7);a&=~(1<<c),a|=(r&1<<n-i-1)>>n-i-1<<c,this.bytes[s]=a}this.pos=n}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,r=this.bytes[e]??0;return this.pos+=8,r}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new t(this.bytes);return e.pos=this.pos,e}}});var vi,Ws,js,Yf,Ex,Cx,qs=he(()=>{Ti();vi=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Ws=[-1,1,2,3,4,5,6,8],js=o(t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new Te(t),r=e.readBits(5);r===31&&(r=32+e.readBits(6));let n=e.readBits(4),i=null;n===15?i=e.readBits(24):n<vi.length&&(i=vi[n]);let s=e.readBits(4),a=null;return s>=1&&s<=7&&(a=Ws[s]),{objectType:r,frequencyIndex:n,sampleRate:i,channelConfiguration:s,numberOfChannels:a}},"parseAacAudioSpecificConfig"),Yf=o(t=>{let e=vi.indexOf(t.sampleRate),r=null;e===-1&&(e=15,r=t.sampleRate);let n=Ws.indexOf(t.numberOfChannels);if(n===-1)throw new TypeError(`Unsupported number of channels: ${t.numberOfChannels}`);let i=13;t.objectType>=32&&(i+=6),e===15&&(i+=24);let s=Math.ceil(i/8),a=new Uint8Array(s),c=new Te(a);return t.objectType<32?c.writeBits(5,t.objectType):(c.writeBits(5,31),c.writeBits(6,t.objectType-32)),c.writeBits(4,e),e===15&&c.writeBits(24,r),c.writeBits(4,n),a},"buildAacAudioSpecificConfig"),Ex=o(t=>{let e=new Uint8Array(7),r=new Te(e),{objectType:n,frequencyIndex:i,channelConfiguration:s}=t,a=n-1;return r.writeBits(12,4095),r.writeBits(1,0),r.writeBits(2,0),r.writeBits(1,1),r.writeBits(2,a),r.writeBits(4,i),r.writeBits(1,0),r.writeBits(3,s),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.skipBits(13),r.writeBits(11,2047),r.writeBits(2,0),{header:e,bitstream:r}},"buildAdtsHeaderTemplate"),Cx=o((t,e)=>{t.pos=30,t.writeBits(13,e)},"writeAdtsFrameLength")});var Vt,ht,Ys,Jt,vn,np,Nz,No,Az,Fz,Lz,zz,Uz,Px,Gf,$z,Qf,Qi,Bz,_r,HP,Hz,Vz,dee,hee,mee,pee,gee,Kf,yee,En,Ix,Zt=he(()=>{qs();Ue();Vt=["avc","hevc","vp9","av1","vp8"],ht=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],Ys=["aac","opus","mp3","vorbis","flac","ac3","eac3"],Jt=[...Ys,...ht],vn=["webvtt"],np=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],Nz=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],No=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],Az=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],Fz=".01.01.01.01.00",Lz=".0.110.01.01.01.0",zz=o((t,e,r,n)=>{if(t==="avc"){let s=Math.ceil(e/16)*Math.ceil(r/16),a=np.find(d=>s<=d.maxMacroblocks&&n<=d.maxBitrate)??Ze(np),c=a?a.level:0,l="64".padStart(2,"0"),u="00",f=c.toString(16).padStart(2,"0");return`avc1.${l}${u}${f}`}else if(t==="hevc"){let c=e*r,l=Nz.find(f=>c<=f.maxPictureSize&&n<=f.maxBitrate)??Ze(Nz);return`hev1.1.6.${l.tier}${l.level}.B0`}else{if(t==="vp8")return"vp8";if(t==="vp9"){let s=e*r;return`vp09.00.${(No.find(l=>s<=l.maxPictureSize&&n<=l.maxBitrate)??Ze(No)).level.toString().padStart(2,"0")}.08`}else if(t==="av1"){let s=e*r,a=Az.find(u=>s<=u.maxPictureSize&&n<=u.maxBitrate)??Ze(Az);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}}throw new TypeError(`Unhandled codec '${t}'.`)},"buildVideoCodecString"),Uz=o(t=>{let e=t.split("."),r=Number(e[1]),n=Number(e[2]),i=Number(e[3]),s=e[4]?Number(e[4]):1;return[1,1,r,2,1,n,3,1,i,4,1,s]},"generateVp9CodecConfigurationFromCodecString"),Px=o(t=>{let e=t.split("."),i=(1<<7)+1,s=Number(e[1]),a=e[2],c=Number(a.slice(0,-1)),l=(s<<5)+c,u=a.slice(-1)==="H"?1:0,d=Number(e[3])===8?0:1,h=0,m=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,g=e[5]?Number(e[5][1]):1,y=e[5]?Number(e[5][2]):0,b=(u<<7)+(d<<6)+(h<<5)+(m<<4)+(p<<3)+(g<<2)+y;return[i,l,b,0]},"generateAv1CodecConfigurationFromCodecString"),Gf=o(t=>{let{codec:e,codecDescription:r,colorSpace:n,avcCodecInfo:i,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:c}=t;if(e==="avc"){if(x(t.avcType!==null),i){let l=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${t.avcType}.${AP(l)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${AP(r.subarray(1,4))}`}else if(e==="hevc"){let l,u,f,d,h,m;if(s)l=s.generalProfileSpace,u=s.generalProfileIdc,f=FP(s.generalProfileCompatibilityFlags),d=s.generalTierFlag,h=s.generalLevelIdc,m=[...s.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let g=ge(r),y=g.getUint8(1);l=y>>6&3,u=y&31,f=FP(g.getUint32(2)),d=y>>5&1,h=g.getUint8(12),m=[];for(let b=0;b<6;b++)m.push(g.getUint8(6+b))}let p="hev1.";for(p+=["","A","B","C"][l]+u,p+=".",p+=f.toString(16).toUpperCase(),p+=".",p+=d===0?"L":"H",p+=h;m.length>0&&m[m.length-1]===0;)m.pop();return m.length>0&&(p+=".",p+=m.map(g=>g.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){let b=t.width*t.height,w=Ze(No).level;for(let k of No)if(b<=k.maxPictureSize){w=k.level;break}return`vp09.00.${w.toString().padStart(2,"0")}.08`}let l=a.profile.toString().padStart(2,"0"),u=a.level.toString().padStart(2,"0"),f=a.bitDepth.toString().padStart(2,"0"),d=a.chromaSubsampling.toString().padStart(2,"0"),h=a.colourPrimaries.toString().padStart(2,"0"),m=a.transferCharacteristics.toString().padStart(2,"0"),p=a.matrixCoefficients.toString().padStart(2,"0"),g=a.videoFullRangeFlag.toString().padStart(2,"0"),y=`vp09.${l}.${u}.${f}.${d}`;return y+=`.${h}.${m}.${p}.${g}`,y.endsWith(Fz)&&(y=y.slice(0,-Fz.length)),y}else if(e==="av1"){if(!c){let k=t.width*t.height,T=Ze(No).level;for(let v of No)if(k<=v.maxPictureSize){T=v.level;break}return`av01.0.${T.toString().padStart(2,"0")}M.08`}let l=c.profile,u=c.level.toString().padStart(2,"0"),f=c.tier?"H":"M",d=c.bitDepth.toString().padStart(2,"0"),h=c.monochrome?"1":"0",m=100*c.chromaSubsamplingX+10*c.chromaSubsamplingY+1*(c.chromaSubsamplingX&&c.chromaSubsamplingY?c.chromaSamplePosition:0),p=n?.primaries?ji[n.primaries]:1,g=n?.transfer?qi[n.transfer]:1,y=n?.matrix?Yi[n.matrix]:1,b=n?.fullRange?1:0,w=`av01.${l}.${u}${f}.${d}`;return w+=`.${h}.${m.toString().padStart(3,"0")}`,w+=`.${p.toString().padStart(2,"0")}`,w+=`.${g.toString().padStart(2,"0")}`,w+=`.${y.toString().padStart(2,"0")}`,w+=`.${b}`,w.endsWith(Lz)&&(w=w.slice(0,-Lz.length)),w}}throw new TypeError(`Unhandled codec '${e}'.`)},"extractVideoCodecString"),$z=o((t,e,r)=>{if(t==="aac")return e>=2&&r<=24e3?"mp4a.40.29":r<=24e3?"mp4a.40.5":"mp4a.40.2";if(t==="mp3")return"mp3";if(t==="opus")return"opus";if(t==="vorbis")return"vorbis";if(t==="flac")return"flac";if(t==="ac3")return"ac-3";if(t==="eac3")return"ec-3";if(ht.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},"buildAudioCodecString"),Qf=o(t=>{let{codec:e,codecDescription:r,aacCodecInfo:n}=t;if(e==="aac"){if(!n)throw new TypeError("AAC codec info must be provided.");if(n.isMpeg2)return"mp4a.67";{let i;return n.objectType!==null?i=n.objectType:i=js(r).objectType,`mp4a.40.${i}`}}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e==="ac3")return"ac-3";if(e==="eac3")return"ec-3";if(e&&ht.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},"extractAudioCodecString"),Qi=48e3,Bz=/^pcm-([usf])(\d+)+(be)?$/,_r=o(t=>{if(x(ht.includes(t)),t==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(t==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=Bz.exec(t);x(e);let r;e[1]==="u"?r="unsigned":e[1]==="s"?r="signed":r="float";let n=Number(e[2])/8,i=e[3]!=="be",s=t==="pcm-u8"?2**7:0;return{dataType:r,sampleSize:n,littleEndian:i,silentValue:s}},"parsePcmCodec"),HP=o(t=>t.startsWith("avc1")||t.startsWith("avc3")?"avc":t.startsWith("hev1")||t.startsWith("hvc1")?"hevc":t==="vp8"?"vp8":t.startsWith("vp09")?"vp9":t.startsWith("av01")?"av1":t.startsWith("mp4a.40")||t==="mp4a.67"?"aac":t==="mp3"||t==="mp4a.69"||t==="mp4a.6B"||t==="mp4a.6b"?"mp3":t==="opus"?"opus":t==="vorbis"?"vorbis":t==="flac"?"flac":t==="ac-3"||t==="ac3"?"ac3":t==="ec-3"||t==="eac3"?"eac3":t==="ulaw"?"ulaw":t==="alaw"?"alaw":Bz.test(t)?t:t==="webvtt"?"webvtt":null,"inferCodecFromCodecString"),Hz=o(t=>t==="avc"?{avc:{format:"avc"}}:t==="hevc"?{hevc:{format:"hevc"}}:{},"getVideoEncoderConfigExtension"),Vz=o(t=>t==="aac"?{aac:{format:"aac"}}:t==="opus"?{opus:{format:"opus"}}:{},"getAudioEncoderConfigExtension"),dee=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],hee=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,mee=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,pee=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,gee=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Kf=o(t=>{if(!t)throw new TypeError("Video chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Video chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!dee.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(t.decoderConfig.codedWidth)||t.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(t.decoderConfig.codedHeight)||t.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(t.decoderConfig.description!==void 0&&!jf(t.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.colorSpace!==void 0){let{colorSpace:e}=t.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let r=Object.keys(ji);if(e.primaries!=null&&!r.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);let n=Object.keys(qi);if(e.transfer!=null&&!n.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${n.join(", ")}.`);let i=Object.keys(Yi);if(e.matrix!=null&&!i.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(t.decoderConfig.codec.startsWith("avc1")||t.decoderConfig.codec.startsWith("avc3")){if(!hee.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(t.decoderConfig.codec.startsWith("hev1")||t.decoderConfig.codec.startsWith("hvc1")){if(!mee.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(t.decoderConfig.codec.startsWith("vp8")){if(t.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(t.decoderConfig.codec.startsWith("vp09")){if(!pee.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(t.decoderConfig.codec.startsWith("av01")&&!gee.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},"validateVideoChunkMetadata"),yee=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],En=o(t=>{if(!t)throw new TypeError("Audio chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!yee.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(t.decoderConfig.sampleRate)||t.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(t.decoderConfig.numberOfChannels)||t.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(t.decoderConfig.description!==void 0&&!jf(t.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.codec.startsWith("mp4a")&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(t.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("mp3")||t.decoderConfig.codec.startsWith("mp4a")){if(t.decoderConfig.codec!=="mp3"&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(t.decoderConfig.codec.startsWith("opus")){if(t.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(t.decoderConfig.description&&t.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(t.decoderConfig.codec.startsWith("vorbis")){if(t.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("flac")){if(t.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("ac-3")||t.decoderConfig.codec.startsWith("ac3")){if(t.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(t.decoderConfig.codec.startsWith("ec-3")||t.decoderConfig.codec.startsWith("eac3")){if(t.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!ht.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${ht.join(", ")}).`)},"validateAudioChunkMetadata"),Ix=o(t=>{if(!t)throw new TypeError("Subtitle metadata must be provided.");if(typeof t!="object")throw new TypeError("Subtitle metadata must be an object.");if(!t.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof t.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof t.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")},"validateSubtitleMetadata")});var Ya,bee,_x,Ga,Xf,Dx,Qa,Ol,Wz,Mx,Ka=he(()=>{Ya=4,bee=[44100,48e3,32e3],_x=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],Ga=1483304551,Xf=1231971951,Dx=o((t,e,r,n,i)=>e===0?0:e===1?Math.floor(144*r/(n<<t))+i:e===2?Math.floor(144*r/n)+i:(Math.floor(12*r/n)+i)*4,"computeMp3FrameSize"),Qa=o((t,e)=>t===3?e===3?21:36:e===3?13:21,"getXingOffset"),Ol=o((t,e)=>{let r=t>>>24,n=t>>>16&255,i=t>>>8&255,s=t&255;if(r!==255&&n!==255&&i!==255&&s!==255)return{header:null,bytesAdvanced:4};if(r!==255)return{header:null,bytesAdvanced:1};if((n&224)!==224)return{header:null,bytesAdvanced:1};let a=0,c=0;n&16?a=n&8?0:1:(a=1,c=1);let l=n>>3&3,u=n>>1&3,f=i>>4&15,d=(i>>2&3)%3,h=i>>1&1,m=s>>6&3,p=s>>4&3,g=s>>3&1,y=s>>2&1,b=s&3,w=_x[a*16*4+u*16+f];if(w===-1)return{header:null,bytesAdvanced:1};let k=w*1e3,T=bee[d]>>a+c,v=Dx(a,u,k,T,h);if(e!==null&&e<v)return{header:null,bytesAdvanced:1};let S;return l===3?S=u===3?384:1152:u===3?S=384:u===2?S=1152:S=576,{header:{totalSize:v,mpegVersionId:l,layer:u,bitrate:k,frequencyIndex:d,sampleRate:T,channel:m,modeExtension:p,copyright:g,original:y,emphasis:b,audioSamplesInFrame:S},bytesAdvanced:1}},"readMp3FrameHeader"),Wz=o(t=>{let e=127,r=0,n=t;for(;(e^2147483647)!==0;)r=n&~e,r<<=1,r|=n&e,e=(e+1<<8)-1,n=r;return r},"encodeSynchsafe"),Mx=o(t=>{let e=2130706432,r=0;for(;e!==0;)r>>=1,r|=t&e,e>>=8;return r},"decodeSynchsafe")});var Rl,VP,Ox=he(()=>{Rl=[48e3,44100,32e3],VP=[24e3,22050,16e3]});var Cn,vt,Xa,Nx,jP,Ao,Rx,WP,Ax,qP,Qz,Jf,Kz,Fx,jz,ip,qz,YP,Gs,GP,Zf,wee,xee,kee,See,Tee,vee,Yz,Xz,Jz,Lx,Gz,Bx,Ja,Eee,Zz,zx,Ux,Ei,sp,op,ap,$x,eU,tU,cp,lp,QP,Hx,rU,Vx,Wx,sn=he(()=>{Zt();Ue();Ox();Ti();(function(t){t[t.NON_IDR_SLICE=1]="NON_IDR_SLICE",t[t.SLICE_DPA=2]="SLICE_DPA",t[t.SLICE_DPB=3]="SLICE_DPB",t[t.SLICE_DPC=4]="SLICE_DPC",t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.AUD=9]="AUD",t[t.SPS_EXT=13]="SPS_EXT"})(Cn||(Cn={}));(function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.AUD_NUT=35]="AUD_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(vt||(vt={}));Xa=o(function*(t){let e=0,r=-1;for(;e<t.length-2;){let n=t.indexOf(0,e);if(n===-1||n>=t.length-2)break;e=n;let i=0;if(e+3<t.length&&t[e+1]===0&&t[e+2]===0&&t[e+3]===1?i=4:t[e+1]===0&&t[e+2]===1&&(i=3),i===0){e++;continue}r!==-1&&e>r&&(yield{offset:r,length:e-r}),r=e+i,e=r}r!==-1&&r<t.length&&(yield{offset:r,length:t.length-r})},"iterateNalUnitsInAnnexB"),Nx=o(function*(t,e){let r=0,n=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;r+e<=t.length;){let i;e===1?i=n.getUint8(r):e===2?i=n.getUint16(r,!1):e===3?i=_l(n,r,!1):(x(e===4),i=n.getUint32(r,!1)),r+=e,yield{offset:r,length:i},r+=i}},"iterateNalUnitsInLengthPrefixed"),jP=o((t,e)=>{if(e.description){let i=(qe(e.description)[4]&3)+1;return Nx(t,i)}else return Xa(t)},"iterateAvcNalUnits"),Ao=o(t=>t&31,"extractNalUnitTypeForAvc"),Rx=o(t=>{let e=[],r=t.length;for(let n=0;n<r;n++)n+2<r&&t[n]===0&&t[n+1]===0&&t[n+2]===3?(e.push(0,0),n+=2):e.push(t[n]);return new Uint8Array(e)},"removeEmulationPreventionBytes"),WP=new Uint8Array([0,0,0,1]),Ax=o(t=>{let e=t.reduce((i,s)=>i+WP.byteLength+s.byteLength,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(WP,n),n+=WP.byteLength,r.set(i,n),n+=i.byteLength;return r},"concatNalUnitsInAnnexB"),qP=o((t,e)=>{let r=t.reduce((s,a)=>s+e+a.byteLength,0),n=new Uint8Array(r),i=0;for(let s of t){let a=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(e){case 1:a.setUint8(i,s.byteLength);break;case 2:a.setUint16(i,s.byteLength,!1);break;case 3:Dl(a,i,s.byteLength,!1);break;case 4:a.setUint32(i,s.byteLength,!1);break}i+=e,n.set(s,i),i+=s.byteLength}return n},"concatNalUnitsInLengthPrefixed"),Qz=o((t,e)=>{if(e.description){let i=(qe(e.description)[4]&3)+1;return qP(t,i)}else return Ax(t)},"concatAvcNalUnits"),Jf=o(t=>{try{let e=[],r=[],n=[];for(let c of Xa(t)){let l=t.subarray(c.offset,c.offset+c.length),u=Ao(l[0]);u===Cn.SPS?e.push(l):u===Cn.PPS?r.push(l):u===Cn.SPS_EXT&&n.push(l)}if(e.length===0||r.length===0)return null;let i=e[0],s=ip(i);x(s!==null);let a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:r,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?n:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},"extractAvcDecoderConfigurationRecord"),Kz=o(t=>{let e=[];e.push(t.configurationVersion),e.push(t.avcProfileIndication),e.push(t.profileCompatibility),e.push(t.avcLevelIndication),e.push(252|t.lengthSizeMinusOne&3),e.push(224|t.sequenceParameterSets.length&31);for(let r of t.sequenceParameterSets){let n=r.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(r[i])}e.push(t.pictureParameterSets.length);for(let r of t.pictureParameterSets){let n=r.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(r[i])}if(t.avcProfileIndication===100||t.avcProfileIndication===110||t.avcProfileIndication===122||t.avcProfileIndication===144){x(t.chromaFormat!==null),x(t.bitDepthLumaMinus8!==null),x(t.bitDepthChromaMinus8!==null),x(t.sequenceParameterSetExt!==null),e.push(252|t.chromaFormat&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.sequenceParameterSetExt.length);for(let r of t.sequenceParameterSetExt){let n=r.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(r[i])}}return new Uint8Array(e)},"serializeAvcDecoderConfigurationRecord"),Fx=o(t=>{try{let e=ge(t),r=0,n=e.getUint8(r++),i=e.getUint8(r++),s=e.getUint8(r++),a=e.getUint8(r++),c=e.getUint8(r++)&3,l=e.getUint8(r++)&31,u=[];for(let m=0;m<l;m++){let p=e.getUint16(r,!1);r+=2,u.push(t.subarray(r,r+p)),r+=p}let f=e.getUint8(r++),d=[];for(let m=0;m<f;m++){let p=e.getUint16(r,!1);r+=2,d.push(t.subarray(r,r+p)),r+=p}let h={configurationVersion:n,avcProfileIndication:i,profileCompatibility:s,avcLevelIndication:a,lengthSizeMinusOne:c,sequenceParameterSets:u,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&r+4<=t.length){let m=e.getUint8(r++)&3,p=e.getUint8(r++)&7,g=e.getUint8(r++)&7,y=e.getUint8(r++);h.chromaFormat=m,h.bitDepthLumaMinus8=p,h.bitDepthChromaMinus8=g;let b=[];for(let w=0;w<y;w++){let k=e.getUint16(r,!1);r+=2,b.push(t.subarray(r,r+k)),r+=k}h.sequenceParameterSetExt=b}return h}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},"deserializeAvcDecoderConfigurationRecord"),jz={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},ip=o(t=>{try{let e=new Te(Rx(t));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let n=e.readAlignedByte(),i=e.readAlignedByte(),s=e.readAlignedByte();Z(e);let a=1,c=0,l=0,u=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(a=Z(e),a===3&&(u=e.readBits(1)),c=Z(e),l=Z(e),e.skipBits(1),e.readBits(1))){for(let A=0;A<(a!==3?8:12);A++)if(e.readBits(1)){let F=A<6?16:64,$=8,W=8;for(let Q=0;Q<F;Q++){if(W!==0){let re=$s(e);W=($+re+256)%256}$=W===0?$:W}}}Z(e);let f=Z(e);if(f===0)Z(e);else if(f===1){e.skipBits(1),$s(e),$s(e);let Y=Z(e);for(let A=0;A<Y;A++)$s(e)}Z(e),e.skipBits(1);let d=Z(e),h=Z(e),m=16*(d+1),p=16*(h+1),g=m,y=p,b=e.readBits(1);if(b||e.skipBits(1),e.skipBits(1),e.readBits(1)){let Y=Z(e),A=Z(e),R=Z(e),F=Z(e),$,W;if((u===0?a:0)===0)$=1,W=2-b;else{let re=a===3?1:2,fe=a===1?2:1;$=re,W=fe*(2-b)}g-=$*(Y+A),y-=W*(R+F)}let k=2,T=2,v=2,S=0,M={num:1,den:1},P=null,N=null;if(e.readBits(1)){if(e.readBits(1)){let fe=e.readBits(8);if(fe===255)M={num:e.readBits(16),den:e.readBits(16)};else{let E=jz[fe];E&&(M=E)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),S=e.readBits(1),e.readBits(1)&&(k=e.readBits(8),T=e.readBits(8),v=e.readBits(8))),e.readBits(1)&&(Z(e),Z(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));let W=e.readBits(1);W&&qz(e);let Q=e.readBits(1);Q&&qz(e),(W||Q)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),Z(e),Z(e),Z(e),Z(e),P=Z(e),N=Z(e))}if(P===null){x(N===null);let Y=i&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&Y)P=0,N=0;else{let A=d+1,R=h+1,F=(2-b)*R,$=np.find(Q=>Q.level>=s)??Ze(np),W=Math.min(Math.floor($.maxDpbMbs/(A*F)),16);P=W,N=W}}return x(N!==null),{profileIdc:n,constraintFlags:i,levelIdc:s,frameMbsOnlyFlag:b,chromaFormatIdc:a,bitDepthLumaMinus8:c,bitDepthChromaMinus8:l,codedWidth:m,codedHeight:p,displayWidth:g,displayHeight:y,pixelAspectRatio:M,colourPrimaries:k,matrixCoefficients:v,transferCharacteristics:T,fullRangeFlag:S,numReorderFrames:P,maxDecFrameBuffering:N}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},"parseAvcSps"),qz=o(t=>{let e=Z(t);t.skipBits(4),t.skipBits(4);for(let r=0;r<=e;r++)Z(t),Z(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},"skipAvcHrdParameters"),YP=o((t,e)=>{if(e.description){let i=(qe(e.description)[21]&3)+1;return Nx(t,i)}else return Xa(t)},"iterateHevcNalUnits"),Gs=o(t=>t>>1&63,"extractNalUnitTypeForHevc"),GP=o(t=>{try{let e=new Te(Rx(t));e.skipBits(16),e.readBits(4);let r=e.readBits(3),n=e.readBits(1),{general_profile_space:i,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:c,general_constraint_indicator_flags:l,general_level_idc:u}=wee(e,r);Z(e);let f=Z(e),d=0;f===3&&(d=e.readBits(1));let h=Z(e),m=Z(e),p=h,g=m;if(e.readBits(1)){let A=Z(e),R=Z(e),F=Z(e),$=Z(e),W=1,Q=1,re=d===0?f:0;re===1?(W=2,Q=2):re===2&&(W=2,Q=1),p-=(A+R)*W,g-=(F+$)*Q}let y=Z(e),b=Z(e);Z(e);let k=e.readBits(1)?0:r,T=0;for(let A=k;A<=r;A++)Z(e),T=Z(e),Z(e);Z(e),Z(e),Z(e),Z(e),Z(e),Z(e),e.readBits(1)&&e.readBits(1)&&xee(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),Z(e),Z(e),e.skipBits(1));let v=Z(e);if(kee(e,v),e.readBits(1)){let A=Z(e);for(let R=0;R<A;R++)Z(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let S=2,M=2,P=2,N=0,O=0,Y={num:1,den:1};if(e.readBits(1)){let A=Tee(e,r);Y=A.pixelAspectRatio,S=A.colourPrimaries,M=A.transferCharacteristics,P=A.matrixCoefficients,N=A.fullRangeFlag,O=A.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:g,pixelAspectRatio:Y,colourPrimaries:S,transferCharacteristics:M,matrixCoefficients:P,fullRangeFlag:N,maxDecFrameBuffering:T+1,spsMaxSubLayersMinus1:r,spsTemporalIdNestingFlag:n,generalProfileSpace:i,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:u,chromaFormatIdc:f,bitDepthLumaMinus8:y,bitDepthChromaMinus8:b,minSpatialSegmentationIdc:O}}catch(e){return console.error("Error parsing HEVC SPS:",e),null}},"parseHevcSps"),Zf=o(t=>{try{let e=[],r=[],n=[],i=[];for(let u of Xa(t)){let f=t.subarray(u.offset,u.offset+u.length),d=Gs(f[0]);d===vt.VPS_NUT?e.push(f):d===vt.SPS_NUT?r.push(f):d===vt.PPS_NUT?n.push(f):(d===vt.PREFIX_SEI_NUT||d===vt.SUFFIX_SEI_NUT)&&i.push(f)}if(r.length===0||n.length===0)return null;let s=GP(r[0]);if(!s)return null;let a=0;if(n.length>0){let u=n[0],f=new Te(Rx(u));f.skipBits(16),Z(f),Z(f),f.skipBits(1),f.skipBits(1),f.skipBits(3),f.skipBits(1),f.skipBits(1),Z(f),Z(f),$s(f),f.skipBits(1),f.skipBits(1),f.readBits(1)&&Z(f),$s(f),$s(f),f.skipBits(1),f.skipBits(1),f.skipBits(1),f.skipBits(1);let d=f.readBits(1),h=f.readBits(1);!d&&!h?a=0:d&&!h?a=2:!d&&h?a=3:a=0}let c=[...e.length?[{arrayCompleteness:1,nalUnitType:vt.VPS_NUT,nalUnits:e}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:vt.SPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:vt.PPS_NUT,nalUnits:n}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Gs(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:c}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},"extractHevcDecoderConfigurationRecord"),wee=o((t,e)=>{let r=t.readBits(2),n=t.readBits(1),i=t.readBits(5),s=0;for(let f=0;f<32;f++)s=s<<1|t.readBits(1);let a=new Uint8Array(6);for(let f=0;f<6;f++)a[f]=t.readBits(8);let c=t.readBits(8),l=[],u=[];for(let f=0;f<e;f++)l.push(t.readBits(1)),u.push(t.readBits(1));if(e>0)for(let f=e;f<8;f++)t.skipBits(2);for(let f=0;f<e;f++)l[f]&&t.skipBits(88),u[f]&&t.skipBits(8);return{general_profile_space:r,general_tier_flag:n,general_profile_idc:i,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:c}},"parseProfileTierLevel"),xee=o(t=>{for(let e=0;e<4;e++)for(let r=0;r<(e===3?2:6);r++)if(!t.readBits(1))Z(t);else{let i=Math.min(64,1<<4+(e<<1));e>1&&$s(t);for(let s=0;s<i;s++)$s(t)}},"skipScalingListData"),kee=o((t,e)=>{let r=[];for(let n=0;n<e;n++)r[n]=See(t,n,e,r)},"skipAllStRefPicSets"),See=o((t,e,r,n)=>{let i=0,s=0,a=0;if(e!==0&&(s=t.readBits(1)),s){if(e===r){let l=Z(t);a=e-(l+1)}else a=e-1;t.readBits(1),Z(t);let c=n[a]??0;for(let l=0;l<=c;l++)t.readBits(1)||t.readBits(1);i=n[a]}else{let c=Z(t),l=Z(t);for(let u=0;u<c;u++)Z(t),t.readBits(1);for(let u=0;u<l;u++)Z(t),t.readBits(1);i=c+l}return i},"skipStRefPicSet"),Tee=o((t,e)=>{let r=2,n=2,i=2,s=0,a=0,c={num:1,den:1};if(t.readBits(1)){let l=t.readBits(8);if(l===255)c={num:t.readBits(16),den:t.readBits(16)};else{let u=jz[l];u&&(c=u)}}return t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),s=t.readBits(1),t.readBits(1)&&(r=t.readBits(8),n=t.readBits(8),i=t.readBits(8))),t.readBits(1)&&(Z(t),Z(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(Z(t),Z(t),Z(t),Z(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&Z(t),t.readBits(1)&&vee(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),a=Z(t),Z(t),Z(t),Z(t),Z(t)),{pixelAspectRatio:c,colourPrimaries:r,transferCharacteristics:n,matrixCoefficients:i,fullRangeFlag:s,minSpatialSegmentationIdc:a}},"parseHevcVui"),vee=o((t,e,r)=>{let n=!1,i=!1,s=!1;e&&(n=t.readBits(1)===1,i=t.readBits(1)===1,(n||i)&&(s=t.readBits(1)===1,s&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5)));for(let a=0;a<=r;a++){let c=t.readBits(1)===1,l=!0;c||(l=t.readBits(1)===1);let u=!1;l?Z(t):u=t.readBits(1)===1;let f=1;u||(f=Z(t)+1),n&&Yz(t,f,s),i&&Yz(t,f,s)}},"skipHevcHrdParameters"),Yz=o((t,e,r)=>{for(let n=0;n<e;n++)Z(t),Z(t),r&&(Z(t),Z(t)),t.readBits(1)},"skipSubLayerHrdParameters"),Xz=o(t=>{let e=[];e.push(t.configurationVersion),e.push((t.generalProfileSpace&3)<<6|(t.generalTierFlag&1)<<5|t.generalProfileIdc&31),e.push(t.generalProfileCompatibilityFlags>>>24&255),e.push(t.generalProfileCompatibilityFlags>>>16&255),e.push(t.generalProfileCompatibilityFlags>>>8&255),e.push(t.generalProfileCompatibilityFlags&255),e.push(...t.generalConstraintIndicatorFlags),e.push(t.generalLevelIdc&255),e.push(240|t.minSpatialSegmentationIdc>>8&15),e.push(t.minSpatialSegmentationIdc&255),e.push(252|t.parallelismType&3),e.push(252|t.chromaFormatIdc&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.avgFrameRate>>8&255),e.push(t.avgFrameRate&255),e.push((t.constantFrameRate&3)<<6|(t.numTemporalLayers&7)<<3|(t.temporalIdNested&1)<<2|t.lengthSizeMinusOne&3),e.push(t.arrays.length&255);for(let r of t.arrays){e.push((r.arrayCompleteness&1)<<7|0|r.nalUnitType&63),e.push(r.nalUnits.length>>8&255),e.push(r.nalUnits.length&255);for(let n of r.nalUnits){e.push(n.length>>8&255),e.push(n.length&255);for(let i=0;i<n.length;i++)e.push(n[i])}}return new Uint8Array(e)},"serializeHevcDecoderConfigurationRecord"),Jz=o(t=>{try{let e=ge(t),r=0,n=e.getUint8(r++),i=e.getUint8(r++),s=i>>6&3,a=i>>5&1,c=i&31,l=e.getUint32(r,!1);r+=4;let u=t.subarray(r,r+6);r+=6;let f=e.getUint8(r++),d=(e.getUint8(r++)&15)<<8|e.getUint8(r++),h=e.getUint8(r++)&3,m=e.getUint8(r++)&3,p=e.getUint8(r++)&7,g=e.getUint8(r++)&7,y=e.getUint16(r,!1);r+=2;let b=e.getUint8(r++),w=b>>6&3,k=b>>3&7,T=b>>2&1,v=b&3,S=e.getUint8(r++),M=[];for(let P=0;P<S;P++){let N=e.getUint8(r++),O=N>>7&1,Y=N&63,A=e.getUint16(r,!1);r+=2;let R=[];for(let F=0;F<A;F++){let $=e.getUint16(r,!1);r+=2,R.push(t.subarray(r,r+$)),r+=$}M.push({arrayCompleteness:O,nalUnitType:Y,nalUnits:R})}return{configurationVersion:n,generalProfileSpace:s,generalTierFlag:a,generalProfileIdc:c,generalProfileCompatibilityFlags:l,generalConstraintIndicatorFlags:u,generalLevelIdc:f,minSpatialSegmentationIdc:d,parallelismType:h,chromaFormatIdc:m,bitDepthLumaMinus8:p,bitDepthChromaMinus8:g,avgFrameRate:y,constantFrameRate:w,numTemporalLayers:k,temporalIdNested:T,lengthSizeMinusOne:v,arrays:M}}catch(e){return console.error("Error deserializing HEVC Decoder Configuration Record:",e),null}},"deserializeHevcDecoderConfigurationRecord"),Lx=o(t=>{let e=new Te(t);if(e.readBits(2)!==2)return null;let n=e.readBits(1),s=(e.readBits(1)<<1)+n;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let u=8;s>=2&&(u=e.readBits(1)?12:10);let f=e.readBits(3),d=0,h=0;if(f!==7)if(h=e.readBits(1),s===1||s===3){let M=e.readBits(1),P=e.readBits(1);d=!M&&!P?3:M&&!P?2:1,e.skipBits(1)}else d=1;else d=3,h=1;let m=e.readBits(16),p=e.readBits(16),g=m+1,y=p+1,b=g*y,w=Ze(No).level;for(let S of No)if(b<=S.maxPictureSize){w=S.level;break}return{profile:s,level:w,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:h,colourPrimaries:f===2?1:f===1?6:2,transferCharacteristics:f===2?1:f===1?6:2,matrixCoefficients:f===7?0:f===2?1:f===1?6:2}},"extractVp9CodecInfoFromPacket"),Gz=o(function*(t){let e=new Te(t),r=o(()=>{let n=0;for(let i=0;i<8;i++){let s=e.readAlignedByte();if(n|=(s&127)<<i*7,!(s&128))break;if(i===7&&s&128)return null}return n>=2**32-1?null:n},"readLeb128");for(;e.getBitsLeft()>=8;){e.skipBits(1);let n=e.readBits(4),i=e.readBits(1),s=e.readBits(1);e.skipBits(1),i&&e.skipBits(8);let a;if(s){let c=r();if(c===null)return;a=c}else a=Math.floor(e.getBitsLeft()/8);x(e.pos%8===0),yield{type:n,data:t.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},"iterateAv1PacketObus"),Bx=o(t=>{for(let{type:e,data:r}of Gz(t)){if(e!==1)continue;let n=new Te(r),i=n.readBits(3),s=n.readBits(1),a=n.readBits(1),c=0,l=0,u=0;if(a)c=n.readBits(5);else{if(n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.readBits(1)))return null;let S=n.readBits(1);S&&(u=n.readBits(5),n.skipBits(32),n.skipBits(5),n.skipBits(5));let M=n.readBits(5);for(let P=0;P<=M;P++){n.skipBits(12);let N=n.readBits(5);if(P===0&&(c=N),N>7){let Y=n.readBits(1);P===0&&(l=Y)}if(S&&n.readBits(1)){let A=u+1;n.skipBits(A),n.skipBits(A),n.skipBits(1)}n.readBits(1)&&n.skipBits(4)}}let f=n.readBits(4),d=n.readBits(4),h=f+1;n.skipBits(h);let m=d+1;n.skipBits(m);let p=0;if(a?p=0:p=n.readBits(1),p&&(n.skipBits(4),n.skipBits(3)),n.skipBits(1),n.skipBits(1),n.skipBits(1),!a){n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let v=n.readBits(1);v&&(n.skipBits(1),n.skipBits(1));let S=n.readBits(1),M=0;S?M=2:M=n.readBits(1),M>0&&(n.readBits(1)||n.skipBits(1)),v&&n.skipBits(3)}n.skipBits(1),n.skipBits(1),n.skipBits(1);let g=n.readBits(1),y=8;i===2&&g?y=n.readBits(1)?12:10:i<=2&&(y=g?10:8);let b=0;i!==1&&(b=n.readBits(1));let w=1,k=1,T=0;return b||(i===0?(w=1,k=1):i===1?(w=0,k=0):y===12&&(w=n.readBits(1),w&&(k=n.readBits(1))),w&&k&&(T=n.readBits(2))),{profile:i,level:c,tier:l,bitDepth:y,monochrome:b,chromaSubsamplingX:w,chromaSubsamplingY:k,chromaSamplePosition:T}}return null},"extractAv1CodecInfoFromPacket"),Ja=o(t=>{let e=ge(t),r=e.getUint8(9),n=e.getUint16(10,!0),i=e.getUint32(12,!0),s=e.getInt16(16,!0),a=e.getUint8(18),c=null;return a&&(c=t.subarray(19,21+r)),{outputChannelCount:r,preSkip:n,inputSampleRate:i,outputGain:s,channelMappingFamily:a,channelMappingTable:c}},"parseOpusIdentificationHeader"),Eee=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],Zz=o(t=>{let e=t[0]>>3;return{durationInSamples:Eee[e]}},"parseOpusTocByte"),zx=o(t=>{if(t.length<7)throw new Error("Setup header is too short.");if(t[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...t.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let r=t.length,n=new Uint8Array(r);for(let d=0;d<r;d++)n[d]=t[r-1-d];let i=new Te(n),s=0;for(;i.getBitsLeft()>97;)if(i.readBits(1)===1){s=i.pos;break}if(s===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,c=!1,l=0;for(;i.getBitsLeft()>=97;){let d=i.pos,h=i.readBits(8),m=i.readBits(16),p=i.readBits(16);if(h>63||m!==0||p!==0){i.pos=d;break}if(i.skipBits(1),a++,a>64)break;i.clone().readBits(6)+1===a&&(c=!0,l=a)}if(!c)throw new Error("Invalid Setup header: mode header not found.");if(l>63)throw new Error(`Unsupported mode count: ${l}.`);let u=l;i.pos=0,i.skipBits(s);let f=Array(u).fill(0);for(let d=u-1;d>=0;d--)i.skipBits(40),f[d]=i.readBits(1);return{modeBlockflags:f}},"parseModesFromVorbisSetupPacket"),Ux=o((t,e,r)=>{switch(t){case"avc":{for(let n of jP(r,e)){let i=r[n.offset],s=Ao(i);if(s>=Cn.NON_IDR_SLICE&&s<=Cn.SLICE_DPC)return"delta";if(s===Cn.IDR)return"key";if(s===Cn.SEI&&(!tp()||Cz()>=144)){let a=r.subarray(n.offset,n.offset+n.length),c=Rx(a),l=1;do{let u=0;for(;;){let h=c[l++];if(h===void 0||(u+=h,h<255))break}let f=0;for(;;){let h=c[l++];if(h===void 0||(f+=h,h<255))break}if(u===6){let h=new Te(c);h.pos=8*l;let m=Z(h),p=h.readBits(1);if(m===0&&p===1)return"key"}l+=f}while(l<c.length-1)}}return"delta"}case"hevc":{for(let n of YP(r,e)){let i=Gs(r[n.offset]);if(i<vt.BLA_W_LP)return"delta";if(i<=vt.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(r[0]&1)===0?"key":"delta";case"vp9":{let n=new Te(r);if(n.readBits(2)!==2)return null;let i=n.readBits(1);return(n.readBits(1)<<1)+i===3&&n.skipBits(1),n.readBits(1)?null:n.readBits(1)===0?"key":"delta"}case"av1":{let n=!1;for(let{type:i,data:s}of Gz(r))if(i===1){let a=new Te(s);a.skipBits(4),n=!!a.readBits(1)}else if(i===3||i===6||i===7){if(n)return"key";let a=new Te(s);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}default:kt(t),x(!1)}},"determineVideoPacketType");(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(Ei||(Ei={}));sp=o((t,e)=>{let r=ge(t),n=0,i=r.getUint32(n,!0);n+=4;let s=br.decode(t.subarray(n,n+i));n+=i,i>0&&(e.raw??={},e.raw.vendor??=s);let a=r.getUint32(n,!0);n+=4;for(let c=0;c<a;c++){let l=r.getUint32(n,!0);n+=4;let u=br.decode(t.subarray(n,n+l));n+=l;let f=u.indexOf("=");if(f===-1)continue;let d=u.slice(0,f).toUpperCase(),h=u.slice(f+1);switch(e.raw??={},e.raw[d]??=h,d){case"TITLE":e.title??=h;break;case"DESCRIPTION":e.description??=h;break;case"ARTIST":e.artist??=h;break;case"ALBUM":e.album??=h;break;case"ALBUMARTIST":e.albumArtist??=h;break;case"COMMENT":e.comment??=h;break;case"LYRICS":e.lyrics??=h;break;case"TRACKNUMBER":{let m=h.split("/"),p=Number.parseInt(m[0],10),g=m[1]&&Number.parseInt(m[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.tracksTotal??=g)}break;case"TRACKTOTAL":{let m=Number.parseInt(h,10);Number.isInteger(m)&&m>0&&(e.tracksTotal??=m)}break;case"DISCNUMBER":{let m=h.split("/"),p=Number.parseInt(m[0],10),g=m[1]&&Number.parseInt(m[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.discsTotal??=g)}break;case"DISCTOTAL":{let m=Number.parseInt(h,10);Number.isInteger(m)&&m>0&&(e.discsTotal??=m)}break;case"DATE":{let m=new Date(h);Number.isNaN(m.getTime())||(e.date??=m)}break;case"GENRE":e.genre??=h;break;case"METADATA_BLOCK_PICTURE":{let m=Iz(h),p=ge(m),g=p.getUint32(0,!1),y=p.getUint32(4,!1),b=String.fromCharCode(...m.subarray(8,8+y)),w=p.getUint32(8+y,!1),k=br.decode(m.subarray(12+y,12+y+w)),T=p.getUint32(y+w+28),v=m.subarray(y+w+32,y+w+32+T);e.images??=[],e.images.push({data:v,mimeType:b,kind:g===3?"coverFront":g===4?"coverBack":"unknown",name:void 0,description:k||void 0})}break}}},"readVorbisComments"),op=o((t,e,r)=>{let n=[t],s=lt.encode("Mediabunny"),a=new Uint8Array(4+s.length),c=new DataView(a.buffer);c.setUint32(0,s.length,!0),a.set(s,4),n.push(a);let l=new Set,u=o((p,g)=>{let y=`${p}=${g}`,b=lt.encode(y);a=new Uint8Array(4+b.length),c=new DataView(a.buffer),c.setUint32(0,b.length,!0),a.set(b,4),n.push(a),l.add(p)},"addCommentTag");for(let{key:p,value:g}of Gi(e))switch(p){case"title":u("TITLE",g);break;case"description":u("DESCRIPTION",g);break;case"artist":u("ARTIST",g);break;case"album":u("ALBUM",g);break;case"albumArtist":u("ALBUMARTIST",g);break;case"genre":u("GENRE",g);break;case"date":{let y=e.raw?.DATE??e.raw?.date;y&&typeof y=="string"?u("DATE",y):u("DATE",g.toISOString().slice(0,10))}break;case"comment":u("COMMENT",g);break;case"lyrics":u("LYRICS",g);break;case"trackNumber":u("TRACKNUMBER",g.toString());break;case"tracksTotal":u("TRACKTOTAL",g.toString());break;case"discNumber":u("DISCNUMBER",g.toString());break;case"discsTotal":u("DISCTOTAL",g.toString());break;case"images":{if(!r)break;for(let y of g){let b=y.kind==="coverFront"?3:y.kind==="coverBack"?4:0,w=new Uint8Array(y.mimeType.length);for(let M=0;M<y.mimeType.length;M++)w[M]=y.mimeType.charCodeAt(M);let k=lt.encode(y.description??""),T=new Uint8Array(8+w.length+4+k.length+16+4+y.data.length),v=ge(T);v.setUint32(0,b,!1),v.setUint32(4,w.length,!1),T.set(w,8),v.setUint32(8+w.length,k.length,!1),T.set(k,12+w.length),v.setUint32(28+w.length+k.length,y.data.length,!1),T.set(y.data,32+w.length+k.length);let S=_z(T);u("METADATA_BLOCK_PICTURE",S)}}break;case"raw":break;default:kt(p)}if(e.raw)for(let p in e.raw){let g=e.raw[p]??e.raw[p.toLowerCase()];p==="vendor"||g==null||l.has(p)||typeof g=="string"&&u(p,g)}let f=new Uint8Array(4);ge(f).setUint32(0,l.size,!0),n.splice(2,0,f);let d=n.reduce((p,g)=>p+g.length,0),h=new Uint8Array(d),m=0;for(let p of n)h.set(p,m),m+=p.length;return h},"createVorbisComments"),ap=[2,1,2,3,3,4,4,5],$x=o(t=>{if(t.length<7||t[0]!==11||t[1]!==119)return null;let e=new Te(t);e.skipBits(16),e.skipBits(16);let r=e.readBits(2);if(r===3)return null;let n=e.readBits(6),i=e.readBits(5);if(i>8)return null;let s=e.readBits(3),a=e.readBits(3);(a&1)!==0&&a!==1&&e.skipBits(2),(a&4)!==0&&e.skipBits(2),a===2&&e.skipBits(2);let c=e.readBits(1),l=Math.floor(n/2);return{fscod:r,bsid:i,bsmod:s,acmod:a,lfeon:c,bitRateCode:l}},"parseAc3SyncFrame"),eU=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],tU=1536,cp=new Uint8Array([5,4,65,67,45,51]),lp=new Uint8Array([5,4,69,65,67,51]),QP=[1,2,3,6],Hx=o(t=>{if(t.length<6||t[0]!==11||t[1]!==119)return null;let e=new Te(t);e.skipBits(16);let r=e.readBits(2);if(e.skipBits(3),r!==0&&r!==2)return null;let n=e.readBits(11),i=e.readBits(2),s=0,a;i===3?(s=e.readBits(2),a=3):a=e.readBits(2);let c=e.readBits(3),l=e.readBits(1),u=e.readBits(5);if(u<11||u>16)return null;let f=QP[a],d;return i<3?d=Rl[i]/1e3:d=VP[s]/1e3,{dataRate:Math.round((n+1)*d/(f*16)),substreams:[{fscod:i,fscod2:s,bsid:u,bsmod:0,acmod:c,lfeon:l,numDepSub:0,chanLoc:0}]}},"parseEac3SyncFrame"),rU=o(t=>{if(t.length<2)return null;let e=new Te(t),r=e.readBits(13),n=e.readBits(3),i=[];for(let s=0;s<=n&&!(Math.ceil(e.pos/8)+3>t.length);s++){let a=e.readBits(2),c=e.readBits(5);e.skipBits(1),e.skipBits(1);let l=e.readBits(3),u=e.readBits(3),f=e.readBits(1);e.skipBits(3);let d=e.readBits(4),h=0;d>0?h=e.readBits(9):e.skipBits(1),i.push({fscod:a,fscod2:null,bsid:c,bsmod:l,acmod:u,lfeon:f,numDepSub:d,chanLoc:h})}return i.length===0?null:{dataRate:r,substreams:i}},"parseEac3Config"),Vx=o(t=>{let e=t.substreams[0];return x(e),e.fscod<3?Rl[e.fscod]:e.fscod2!==null&&e.fscod2<3?VP[e.fscod2]:null},"getEac3SampleRate"),Wx=o(t=>{let e=t.substreams[0];x(e);let r=ap[e.acmod]+e.lfeon;if(e.numDepSub>0){let n=[2,2,1,1,2,2,2,1,1];for(let i=0;i<9;i++)e.chanLoc&1<<8-i&&(r+=n[i])}return r},"getEac3ChannelCount")});var wr,Fo=he(()=>{wr=class{static{o(this,"Demuxer")}constructor(e){this.input=e}}});var up,fp,dp,hp,ed,td,Nl,Al,nU,iU,rd=he(()=>{up=class{static{o(this,"CustomVideoDecoder")}static supports(e,r){return!1}},fp=class{static{o(this,"CustomAudioDecoder")}static supports(e,r){return!1}},dp=class{static{o(this,"CustomVideoEncoder")}static supports(e,r){return!1}},hp=class{static{o(this,"CustomAudioEncoder")}static supports(e,r){return!1}},ed=[],td=[],Nl=[],Al=[],nU=o(t=>{if(t.prototype instanceof up){let e=t;if(ed.includes(e)){console.warn("Video decoder already registered.");return}ed.push(e)}else if(t.prototype instanceof fp){let e=t;if(td.includes(e)){console.warn("Audio decoder already registered.");return}td.push(e)}else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},"registerDecoder"),iU=o(t=>{if(t.prototype instanceof dp){let e=t;if(Nl.includes(e)){console.warn("Video encoder already registered.");return}Nl.push(e)}else if(t.prototype instanceof hp){let e=t;if(Al.includes(e)){console.warn("Audio encoder already registered.");return}Al.push(e)}else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")},"registerEncoder")});var Wt,je,Qn=he(()=>{Ue();Wt=new Uint8Array(0),je=class t{static{o(this,"EncodedPacket")}constructor(e,r,n,i,s=-1,a,c){if(this.data=e,this.type=r,this.timestamp=n,this.duration=i,this.sequenceNumber=s,e===Wt&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!=="key"&&r!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(n))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(i)||i<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(c!==void 0&&(typeof c!="object"||!c))throw new TypeError("sideData, when provided, must be an object.");if(c?.alpha!==void 0&&!(c.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(c?.alphaByteLength!==void 0&&(!Number.isInteger(c.alphaByteLength)||c.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=c??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Wt}get microsecondTimestamp(){return Math.trunc(Hs*this.timestamp)}get microsecondDuration(){return Math.trunc(Hs*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,r){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let n=new Uint8Array(e.byteLength);return e.copyTo(n),new t(n,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,r)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new t(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}}});var sU,oU,aU,cU,KP=he(()=>{sU=o(t=>{let n=t,i=4096,s=0,a=12,c=0;for(n<0&&(n=-n,s=128),n+=33,n>8191&&(n=8191);(n&i)!==i&&a>=5;)i>>=1,a--;return c=n>>a-4&15,~(s|a-5<<4|c)&255},"toUlaw"),oU=o(t=>{let r=0,n=0,i=~t;i&128&&(i&=-129,r=-1),n=((i&240)>>4)+5;let s=(1<<n|(i&15)<<n-4|1<<n-5)-33;return r===0?s:-s},"fromUlaw"),aU=o(t=>{let r=2048,n=0,i=11,s=0,a=t;for(a<0&&(a=-a,n=128),a>4095&&(a=4095);(a&r)!==r&&i>=5;)r>>=1,i--;return s=a>>(i===4?1:i-4)&15,(n|i-4<<4|s)^85},"toAlaw"),cU=o(t=>{let e=0,r=0,n=t^85;n&128&&(n&=-129,e=-1),r=((n&240)>>4)+4;let i=0;return r!==4?i=1<<r|(n&15)<<r-4|1<<r-5:i=n<<1|1,e===0?i:-i},"fromAlaw")});var lU,uU,mp,jx,Cee,ur,Bl,Fl,gp,yp,fU,Pee,Iee,XP,Dr,Ll,nd,dU,hU,pp,_ee,bp=he(()=>{Ue();vx();lU=-1/0,uU=-1/0,mp=null;typeof FinalizationRegistry<"u"&&(mp=new FinalizationRegistry(t=>{let e=Date.now();t.type==="video"?(e-lU>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),lU=e),typeof VideoFrame<"u"&&t.data instanceof VideoFrame&&t.data.close()):(e-uU>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),uU=e),typeof AudioData<"u"&&t.data instanceof AudioData&&t.data.close())}));jx=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Cee=new Set(jx),ur=class t{static{o(this,"VideoSample")}get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(Hs*this.timestamp)}get microsecondDuration(){return Math.trunc(Hs*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,r){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.format===void 0||!Cee.has(r.format))throw new TypeError("init.format must be one of: "+jx.join(", "));if(!Number.isInteger(r.codedWidth)||r.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(r.codedHeight)||r.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("init.layout, when provided, must be an array.");for(let n of r.layout){if(!n||typeof n!="object"||Array.isArray(n))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(n.offset)||n.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(n.stride)||n.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.visibleRect!==void 0&&$P(r.visibleRect,"init.visibleRect"),r.displayWidth!==void 0&&(!Number.isInteger(r.displayWidth)||r.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(r.displayHeight!==void 0&&(!Number.isInteger(r.displayHeight)||r.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(r.displayWidth!==void 0!=(r.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this._data=qe(e).slice(),this._layout=r.layout??Pee(r.format,r.codedWidth,r.codedHeight),this.format=r.format,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Bl(r.colorSpace),this.visibleRect={left:r.visibleRect?.left??0,top:r.visibleRect?.top??0,width:r.visibleRect?.width??r.codedWidth,height:r.visibleRect?.height??r.codedHeight},r.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?r.displayWidth:r.displayHeight,this.squarePixelHeight=this.rotation%180===0?r.displayHeight:r.displayWidth):(this.squarePixelWidth=this.codedWidth,this.squarePixelHeight=this.codedHeight)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(r?.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(r?.timestamp!==void 0&&!Number.isFinite(r?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(r?.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");r?.visibleRect!==void 0&&$P(r.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=r?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=r?.timestamp??e.timestamp/1e6,this.duration=r?.duration??(e.duration??0)/1e6,this.colorSpace=new Bl(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new t(new VideoFrame(e,{timestamp:Math.trunc(r.timestamp*Hs),duration:Math.trunc((r.duration??0)*Hs)||void 0}),r);let n=0,i=0;if("naturalWidth"in e?(n=e.naturalWidth,i=e.naturalHeight):"videoWidth"in e?(n=e.videoWidth,i=e.videoHeight):"width"in e&&(n=Number(e.width),i=Number(e.height)),!n||!i)throw new TypeError("Could not determine dimensions.");let s=new OffscreenCanvas(n,i),a=s.getContext("2d",{alpha:Vs(),willReadFrequently:!0});x(a),a.drawImage(e,0,0),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:n,height:i},this.squarePixelWidth=n,this.squarePixelHeight=i,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Bl({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");this.pixelAspectRatio=qa({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),mp?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return x(this._data!==null),Fl(this._data)?new t(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(x(this._layout),new t(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})):new t(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})}close(){this._closed||(mp?.unregister(this),Fl(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(fU(e),this._closed)throw new Error("VideoSample is closed.");if(this.format===null)throw new Error("Cannot get allocation size when format is null. Sorry!");if(x(this._data!==null),!Fl(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let r=this.toVideoFrame(),n=r.allocationSize(e);return r.close(),n}return Fl(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,r={}){if(!jf(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(fU(r),this._closed)throw new Error("VideoSample is closed.");if(this.format===null)throw new Error("Cannot copy video sample data when format is null. Sorry!");if(x(this._data!==null),!Fl(this._data)&&(r.colorSpace||r.format&&r.format!==this.format||r.layout||r.rect)){let n=this.toVideoFrame(),i=await n.copyTo(e,r);return n.close(),i}if(Fl(this._data))return this._data.copyTo(e,r);if(this._data instanceof Uint8Array)return x(this._layout),qe(e).set(this._data),this._layout;{let i=this._data.getContext("2d");x(i);let s=i.getImageData(0,0,this.codedWidth,this.codedHeight);return qe(e).set(s.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return x(this._data!==null),Fl(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,r,n,i,s,a,c,l,u){let f=0,d=0,h=this.displayWidth,m=this.displayHeight,p=0,g=0,y=this.displayWidth,b=this.displayHeight;if(a!==void 0?(f=r,d=n,h=i,m=s,p=a,g=c,l!==void 0?(y=l,b=u):(y=h,b=m)):(p=r,g=n,i!==void 0&&(y=i,b=s)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(f))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(m)||m<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(g))throw new TypeError("dy must be a number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(b)||b<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:f,sy:d,sWidth:h,sHeight:m}=this._rotateSourceRegion(f,d,h,m,this.rotation));let w=this.toCanvasImageSource();e.save();let k=p+y/2,T=g+b/2;e.translate(k,T),e.rotate(this.rotation*Math.PI/180);let v=this.rotation%180===0?1:y/b;e.scale(1/v,v),e.drawImage(w,f,d,h,m,-y/2,-b/2,y,b),e.restore()}drawWithFit(e,r){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(r.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");r.crop!==void 0&&yp(r.crop,"options.");let n=e.canvas.width,i=e.canvas.height,s=r.rotation??this.rotation,[a,c]=s%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];r.crop&&gp(r.crop,a,c);let l,u,f,d,{sx:h,sy:m,sWidth:p,sHeight:g}=this._rotateSourceRegion(r.crop?.left??0,r.crop?.top??0,r.crop?.width??a,r.crop?.height??c,s);if(r.fit==="fill")l=0,u=0,f=n,d=i;else{let[b,w]=r.crop?[r.crop.width,r.crop.height]:[a,c],k=r.fit==="contain"?Math.min(n/b,i/w):Math.max(n/b,i/w);f=b*k,d=w*k,l=(n-f)/2,u=(i-d)/2}e.save();let y=s%180===0?1:f/d;e.translate(n/2,i/2),e.rotate(s*Math.PI/180),e.scale(1/y,y),e.translate(-n/2,-i/2),e.drawImage(this.toCanvasImageSource(),h,m,p,g,l,u,f,d),e.restore()}_rotateSourceRegion(e,r,n,i,s){return s===90?[e,r,n,i]=[r,this.squarePixelHeight-e-n,i,n]:s===180?[e,r]=[this.squarePixelWidth-e-n,this.squarePixelHeight-r-i]:s===270&&([e,r,n,i]=[this.squarePixelWidth-r-i,e,i,n]),{sx:e,sy:r,sWidth:n,sHeight:i}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(x(this._data!==null),this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}},Bl=class{static{o(this,"VideoSampleColorSpace")}constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");let r=Object.keys(ji);if(e.primaries!=null&&!r.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${r.join(", ")}.`);let n=Object.keys(qi);if(e.transfer!=null&&!n.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${n.join(", ")}.`);let i=Object.keys(Yi);if(e.matrix!=null&&!i.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${i.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},Fl=o(t=>typeof VideoFrame<"u"&&t instanceof VideoFrame,"isVideoFrame"),gp=o((t,e,r)=>{t.left=Math.min(t.left,e),t.top=Math.min(t.top,r),t.width=Math.min(t.width,e-t.left),t.height=Math.min(t.height,r-t.top),x(t.width>=0),x(t.height>=0)},"clampCropRectangle"),yp=o((t,e)=>{if(!t||typeof t!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},"validateCropRectangle"),fU=o(t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.colorSpace!==void 0&&!["display-p3","srgb"].includes(t.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(t.format!==void 0&&typeof t.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of t.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.rect!==void 0){if(!t.rect||typeof t.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(t.rect.x!==void 0&&(!Number.isInteger(t.rect.x)||t.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(t.rect.y!==void 0&&(!Number.isInteger(t.rect.y)||t.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(t.rect.width!==void 0&&(!Number.isInteger(t.rect.width)||t.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(t.rect.height!==void 0&&(!Number.isInteger(t.rect.height)||t.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},"validateVideoFrameCopyToOptions"),Pee=o((t,e,r)=>{let n=Iee(t),i=[],s=0;for(let a of n){let c=Math.ceil(e/a.widthDivisor),l=Math.ceil(r/a.heightDivisor),u=c*a.sampleBytes,f=u*l;i.push({offset:s,stride:u}),s+=f}return i},"createDefaultPlaneLayout"),Iee=o(t=>{let e=o((r,n,i,s,a)=>{let c=[{sampleBytes:r,widthDivisor:1,heightDivisor:1},{sampleBytes:n,widthDivisor:i,heightDivisor:s},{sampleBytes:n,widthDivisor:i,heightDivisor:s}];return a&&c.push({sampleBytes:r,widthDivisor:1,heightDivisor:1}),c},"yuv");switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:kt(t),x(!1)}},"getPlaneConfigs"),XP=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),Dr=class t{static{o(this,"AudioSample")}get microsecondTimestamp(){return Math.trunc(Hs*this.timestamp)}get microsecondDuration(){return Math.trunc(Hs*this.duration)}constructor(e){if(this._closed=!1,pp(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!XP.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");let r=e.data.byteLength/(Ll(e.format)*e.numberOfChannels);if(!Number.isInteger(r))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=r,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=r/e.sampleRate;let n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let i=this.numberOfFrames*this.numberOfChannels*Ll(this.format);if(n.byteLength<i)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=n}mp?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!XP.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let r=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let i=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-n;if(i>this.numberOfFrames-n)throw new RangeError("frameCount out of range");let s=Ll(r),a=nd(r);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?i:i*this.numberOfChannels)*s}copyTo(e,r){if(!jf(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(r.planeIndex)||r.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(r.format!==void 0&&!XP.has(r.format))throw new TypeError("Invalid format.");if(r.frameOffset!==void 0&&(!Number.isInteger(r.frameOffset)||r.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(r.frameCount!==void 0&&(!Number.isInteger(r.frameCount)||r.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{planeIndex:n,format:i,frameCount:s,frameOffset:a}=r,c=this.format,l=i??this.format;if(!l)throw new Error("Destination format not determined");let u=this.numberOfFrames,f=this.numberOfChannels,d=a??0;if(d>=u)throw new RangeError("frameOffset out of range");let h=s!==void 0?s:u-d;if(h>u-d)throw new RangeError("frameCount out of range");let m=Ll(l),p=nd(l);if(p&&n>=f)throw new RangeError("planeIndex out of range");if(!p&&n!==0)throw new RangeError("planeIndex out of range");let y=(p?h:h*f)*m;if(e.byteLength<y)throw new RangeError("Destination buffer is too small");let b=ge(e),w=hU(l);if(pp(this._data))Wa()&&f>2&&l!==c?_ee(this._data,b,c,l,f,n,d,h):this._data.copyTo(e,{planeIndex:n,frameOffset:d,frameCount:h,format:l});else{let k=this._data,T=ge(k),v=dU(c),S=Ll(c),M=nd(c);for(let P=0;P<h;P++)if(p){let N=P*m,O;M?O=(n*u+(P+d))*S:O=((P+d)*f+n)*S;let Y=v(T,O);w(b,N,Y)}else for(let N=0;N<f;N++){let Y=(P*f+N)*m,A;M?A=(N*u+(P+d))*S:A=((P+d)*f+N)*S;let R=v(T,A);w(b,Y,R)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(pp(this._data)){let e=new t(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new t({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(mp?.unregister(this),pp(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(pp(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(nd(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),r=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(r,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:r})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),r=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(r,{planeIndex:n,format:"f32-planar"}),e.copyToChannel(r,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,i=e.numberOfChannels,s=e.sampleRate,a=e.length,c=Math.floor(n/i),l=0,u=a;for(;u>0;){let f=Math.min(c,u),d=new Float32Array(i*f);for(let h=0;h<i;h++)e.copyFromChannel(d.subarray(h*f,(h+1)*f),h,l);yield new t({format:"f32-planar",sampleRate:s,numberOfFrames:f,numberOfChannels:i,timestamp:r+l/s,data:d}),l+=f,u-=f}}static fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,i=e.numberOfChannels,s=e.sampleRate,a=e.length,c=Math.floor(n/i),l=0,u=a,f=[];for(;u>0;){let d=Math.min(c,u),h=new Float32Array(i*d);for(let p=0;p<i;p++)e.copyFromChannel(h.subarray(p*d,(p+1)*d),p,l);let m=new t({format:"f32-planar",sampleRate:s,numberOfFrames:d,numberOfChannels:i,timestamp:r+l/s,data:h});f.push(m),l+=d,u-=d}return f}},Ll=o(t=>{switch(t){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},"getBytesPerSample"),nd=o(t=>{switch(t){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},"formatIsPlanar"),dU=o(t=>{switch(t){case"u8":case"u8-planar":return(e,r)=>(e.getUint8(r)-128)/128;case"s16":case"s16-planar":return(e,r)=>e.getInt16(r,!0)/32768;case"s32":case"s32-planar":return(e,r)=>e.getInt32(r,!0)/2147483648;case"f32":case"f32-planar":return(e,r)=>e.getFloat32(r,!0)}},"getReadFunction"),hU=o(t=>{switch(t){case"u8":case"u8-planar":return(e,r,n)=>e.setUint8(r,Ht((n+1)*127.5,0,255));case"s16":case"s16-planar":return(e,r,n)=>e.setInt16(r,Ht(Math.round(n*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,r,n)=>e.setInt32(r,Ht(Math.round(n*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,r,n)=>e.setFloat32(r,n,!0)}},"getWriteFunction"),pp=o(t=>typeof AudioData<"u"&&t instanceof AudioData,"isAudioData"),_ee=o((t,e,r,n,i,s,a,c)=>{let l=dU(r),u=hU(n),f=Ll(r),d=Ll(n),h=nd(r);if(nd(n))if(h){let p=new ArrayBuffer(c*f),g=ge(p);t.copyTo(p,{planeIndex:s,frameOffset:a,frameCount:c,format:r});for(let y=0;y<c;y++){let b=y*f,w=y*d,k=l(g,b);u(e,w,k)}}else{let p=new ArrayBuffer(c*i*f),g=ge(p);t.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:c,format:r});for(let y=0;y<c;y++){let b=(y*i+s)*f,w=y*d,k=l(g,b);u(e,w,k)}}else if(h){let p=c*f,g=new ArrayBuffer(p),y=ge(g);for(let b=0;b<i;b++){t.copyTo(g,{planeIndex:b,frameOffset:a,frameCount:c,format:r});for(let w=0;w<c;w++){let k=w*f,T=(w*i+b)*d,v=l(y,k);u(e,T,v)}}}else{let p=new ArrayBuffer(c*i*f),g=ge(p);t.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:c,format:r});for(let y=0;y<c;y++)for(let b=0;b<i;b++){let w=y*i+b,k=w*f,T=w*d,v=l(g,k);u(e,T,v)}}},"doAudioDataCopyToWebKitWorkaround")});var zl,Lo,JP,Ki,wp,id,mU,ZP,eI,Za,sd,tI,rI,ec,qx,Yx=he(()=>{Zt();sn();rd();od();Xi();Ue();Qn();KP();bp();zl=o(t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.metadataOnly!==void 0&&typeof t.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(t.verifyKeyPackets!==void 0&&typeof t.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(t.verifyKeyPackets&&t.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},"validatePacketRetrievalOptions"),Lo=o(t=>{if(!ja(t))throw new TypeError("timestamp must be a number.")},"validateTimestamp"),JP=o((t,e,r)=>r.verifyKeyPackets?e.then(async n=>{if(!n||n.type==="delta")return n;let i=await t.determinePacketType(n);return i&&(n.type=i),n}):e,"maybeFixPacketType"),Ki=class{static{o(this,"EncodedPacketSink")}constructor(e){if(!(e instanceof tc))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(zl(e),this._track.input._disposed)throw new er;return JP(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){zl(e);let r=await this.getFirstPacket(e);return r?r.type==="key"?r:this.getNextKeyPacket(r,e):null}getPacket(e,r={}){if(Lo(e),zl(r),this._track.input._disposed)throw new er;return JP(this._track,this._track._backing.getPacket(e,r),r)}getNextPacket(e,r={}){if(!(e instanceof je))throw new TypeError("packet must be an EncodedPacket.");if(zl(r),this._track.input._disposed)throw new er;return JP(this._track,this._track._backing.getNextPacket(e,r),r)}async getKeyPacket(e,r={}){if(Lo(e),zl(r),this._track.input._disposed)throw new er;if(!r.verifyKeyPackets)return this._track._backing.getKeyPacket(e,r);let n=await this._track._backing.getKeyPacket(e,r);return n&&(x(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getKeyPacket(n.timestamp-1/this._track.timeResolution,r):n)}async getNextKeyPacket(e,r={}){if(!(e instanceof je))throw new TypeError("packet must be an EncodedPacket.");if(zl(r),this._track.input._disposed)throw new er;if(!r.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,r);let n=await this._track._backing.getNextKeyPacket(e,r);return n&&(x(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getNextKeyPacket(n,r):n)}packets(e,r,n={}){if(e!==void 0&&!(e instanceof je))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(r!==void 0&&!(r instanceof je))throw new TypeError("endPacket must be an EncodedPacket.");if(zl(n),this._track.input._disposed)throw new er;let i=[],{promise:s,resolve:a}=ut(),{promise:c,resolve:l}=ut(),u=!1,f=!1,d=null,h=[],m=o(()=>Math.max(2,h.length),"maxQueueSize");(async()=>{let g=e??await this.getFirstPacket(n);for(;g&&!f&&!this._track.input._disposed&&!(r&&g.sequenceNumber>=r?.sequenceNumber);){if(i.length>m()){({promise:c,resolve:l}=ut()),await c;continue}i.push(g),a(),{promise:s,resolve:a}=ut(),g=await this.getNextPacket(g,n)}u=!0,a()})().catch(g=>{d||(d=g,a())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new er;if(f)return{value:void 0,done:!0};if(d)throw d;if(i.length>0){let g=i.shift(),y=performance.now();for(h.push(y);h.length>0&&y-h[0]>=1e3;)h.shift();return l(),{value:g,done:!1}}else{if(u)return{value:void 0,done:!0};await s}}},async return(){return f=!0,l(),a(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},wp=class{static{o(this,"DecoderWrapper")}constructor(e,r){this.onSample=e,this.onError=r}},id=class{static{o(this,"BaseMediaSampleSink")}mediaSamplesInRange(e=0,r=1/0){Lo(e),Lo(r);let n=[],i=!1,s=null,{promise:a,resolve:c}=ut(),{promise:l,resolve:u}=ut(),f=!1,d=!1,h=!1,m=null;(async()=>{let y=await this._createDecoder(S=>{if(u(),S.timestamp>=r&&(d=!0),d){S.close();return}s&&(S.timestamp>e?(n.push(s),i=!0):s.close()),S.timestamp>=e&&(n.push(S),i=!0),s=i?null:S,n.length>0&&(c(),{promise:a,resolve:c}=ut())},S=>{m||(m=S,c())}),b=this._createPacketSink(),w=await b.getKeyPacket(e,{verifyKeyPackets:!0})??await b.getFirstKeyPacket({verifyKeyPackets:!0}),k=w,v=b.packets(w??void 0,void 0);for(await v.next();k&&!d&&!this._track.input._disposed;){let S=mU(n.length);if(n.length+y.getDecodeQueueSize()>S){({promise:l,resolve:u}=ut()),await l;continue}y.decode(k);let M=await v.next();if(M.done)break;k=M.value}await v.return(),!h&&!this._track.input._disposed&&await y.flush(),y.close(),!i&&s&&n.push(s),f=!0,c()})().catch(y=>{m||(m=y,c())});let p=this._track,g=o(()=>{s?.close();for(let y of n)y.close()},"closeSamples");return{async next(){for(;;){if(p.input._disposed)throw g(),new er;if(h)return{value:void 0,done:!0};if(m)throw g(),m;if(n.length>0){let y=n.shift();return u(),{value:y,done:!1}}else if(!f)await a;else return{value:void 0,done:!0}}},async return(){return h=!0,d=!0,u(),c(),g(),{value:void 0,done:!0}},async throw(y){throw y},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){xz(e);let r=wz(e),n=[],i=[],{promise:s,resolve:a}=ut(),{promise:c,resolve:l}=ut(),u=!1,f=!1,d=null,h=o(g=>{i.push(g),a(),{promise:s,resolve:a}=ut()},"pushToQueue");(async()=>{let g=await this._createDecoder(S=>{if(l(),f){S.close();return}let M=0;for(;n.length>0&&S.timestamp-n[0]>-1e-10;)M++,n.shift();if(M>0)for(let P=0;P<M;P++)h(P<M-1?S.clone():S);else S.close()},S=>{d||(d=S,a())}),y=this._createPacketSink(),b=null,w=null,k=-1,T=o(async()=>{x(w);let S=w;for(g.decode(S);S.sequenceNumber<k;){let M=mU(i.length);for(;i.length+g.getDecodeQueueSize()>M&&!f;)({promise:c,resolve:l}=ut()),await c;if(f)break;let P=await y.getNextPacket(S);x(P),g.decode(P),S=P}k=-1},"decodePackets"),v=o(async()=>{await g.flush();for(let S=0;S<n.length;S++)h(null);n.length=0},"flushDecoder");for await(let S of r){if(Lo(S),f||this._track.input._disposed)break;let M=await y.getPacket(S),P=M&&await y.getKeyPacket(S,{verifyKeyPackets:!0});if(!P){k!==-1&&(await T(),await v()),h(null),b=null;continue}b&&(P.sequenceNumber!==w.sequenceNumber||M.timestamp<b.timestamp)&&(await T(),await v()),n.push(M.timestamp),k=Math.max(M.sequenceNumber,k),b=M,w=P}!f&&!this._track.input._disposed&&(k!==-1&&await T(),await v()),g.close(),u=!0,a()})().catch(g=>{d||(d=g,a())});let m=this._track,p=o(()=>{for(let g of i)g?.close()},"closeSamples");return{async next(){for(;;){if(m.input._disposed)throw p(),new er;if(f)return{value:void 0,done:!0};if(d)throw p(),d;if(i.length>0){let g=i.shift();return x(g!==void 0),l(),{value:g,done:!1}}else if(!u)await s;else return{value:void 0,done:!0}}},async return(){return f=!0,l(),a(),p(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},mU=o(t=>t===0?40:8,"computeMaxQueueSize"),ZP=class extends wp{static{o(this,"VideoDecoderWrapper")}constructor(e,r,n,i,s,a){super(e,r),this.codec=n,this.decoderConfig=i,this.rotation=s,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new $a,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;let c=ed.find(l=>l.supports(n,i));if(c)this.customDecoder=new c,this.customDecoder.codec=n,this.customDecoder.config=i,this.customDecoder.onSample=l=>{if(!(l instanceof ur))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(l)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let l=o(f=>{if(this.alphaQueue.length>0){let d=this.alphaQueue.shift();x(d!==void 0),this.mergeAlpha(f,d)}else this.colorQueue.push(f)},"colorHandler");if(n==="avc"&&this.decoderConfig.description&&tp()){let f=Fx(qe(this.decoderConfig.description));if(f&&f.sequenceParameterSets.length>0){let d=ip(f.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let u=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:o(f=>{try{l(f)}catch(d){this.onError(d)}},"output"),error:o(f=>{f.stack=u,this.onError(f)},"error")}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(x(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(x(this.decoder),Wa()||LP(this.inputTimestamps,e.timestamp,r=>r),tp()&&this.currentPacketIndex===0&&this.codec==="avc"){let r=[];for(let i of jP(e.data,this.decoderConfig)){let s=Ao(e.data[i.offset]);s>=20&&s<=31||r.push(e.data.subarray(i.offset,i.offset+i.length))}let n=Qz(r,this.decoderConfig);e=new je(n,e.type,e.timestamp,e.duration)}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed){this.pushNullAlphaFrame();return}if(!this.merger)try{this.merger=new eI}catch(n){console.error("Due to an error, only color data will be decoded.",n),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let n=o(s=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let a=this.colorQueue.shift();x(a!==void 0),this.mergeAlpha(a,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let a=this.colorQueue.shift();x(a!==void 0),this.mergeAlpha(a,null)}else this.alphaQueue.push(null)},"alphaHandler"),i=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:o(s=>{try{n(s)}catch(a){this.onError(a)}},"output"),error:o(s=>{s.stack=i,this.onError(s)},"error")}),this.alphaDecoder.configure(this.decoderConfig)}let r=Ux(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=r==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(r??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let r of YP(e,this.decoderConfig)){let n=Gs(e[r.offset]);if(n===vt.RASL_N||n===vt.RASL_R)return!0}return!1}sampleHandler(e){if(Wa()){if(this.sampleQueue.length>0&&e.timestamp>=Ze(this.sampleQueue).timestamp){for(let r of this.sampleQueue)this.finalizeAndEmitSample(r);this.sampleQueue.length=0}LP(this.sampleQueue,e,r=>r.timestamp)}else{let r=this.inputTimestamps.shift();x(r!==void 0),e.setTimestamp(r),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,r){if(!r){let s=new ur(e);this.sampleHandler(s);return}x(this.merger),this.merger.update(e,r),e.close(),r.close();let n=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),i=new ur(n);this.sampleHandler(i)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(x(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Wa()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(x(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},eI=class{static{o(this,"ColorAlphaMerger")}constructor(){typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
1
|
+
var f2=Object.create;var Zl=Object.defineProperty;var d2=Object.getOwnPropertyDescriptor;var G8=Object.getOwnPropertyNames;var Q8=Object.getPrototypeOf,K8=Object.prototype.hasOwnProperty;var h2=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),eu=t=>{throw TypeError(t)};var m2=(t,e,r)=>e in t?Zl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var o=(t,e)=>Zl(t,"name",{value:e,configurable:!0});var he=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var ri=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},ke=(t,e)=>{for(var r in e)Zl(t,r,{get:e[r],enumerable:!0})},X8=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of G8(e))!K8.call(t,i)&&i!==r&&Zl(t,i,{get:()=>e[i],enumerable:!(n=d2(e,i))||n.enumerable});return t};var us=(t,e,r)=>(r=t!=null?f2(Q8(t)):{},X8(e||!t||!t.__esModule?Zl(r,"default",{value:t,enumerable:!0}):r,t));var un=t=>[,,,f2(t?.[h2("metadata")]??null)],p2=["class","method","getter","setter","accessor","field","value","get","set"],Nd=t=>t!==void 0&&typeof t!="function"?eu("Function expected"):t,J8=(t,e,r,n,i)=>({kind:p2[t],name:e,metadata:n,addInitializer:s=>r._?eu("Already initialized"):i.push(Nd(s||null))}),Z8=(t,e)=>m2(e,h2("metadata"),t[3]),B=(t,e,r,n)=>{for(var i=0,s=t[e>>1],a=s&&s.length;i<a;i++)e&1?s[i].call(r):n=s[i].call(r,n);return n},te=(t,e,r,n,i,s)=>{var a,c,l,u,f,d=e&7,h=!!(e&8),m=!!(e&16),p=d>3?t.length+1:d?h?1:2:0,g=p2[d+5],y=d>3&&(t[p-1]=[]),b=t[p]||(t[p]=[]),w=d&&(!m&&!h&&(i=i.prototype),d<5&&(d>3||!m)&&d2(d<4?i:{get[r](){return l2(this,s)},set[r](T){return u2(this,s,T)}},r));d?m&&d<4&&o(s,(d>2?"set ":d>1?"get ":"")+r):o(i,r);for(var k=n.length-1;k>=0;k--)u=J8(d,r,l={},t[3],b),d&&(u.static=h,u.private=m,f=u.access={has:m?T=>e5(i,T):T=>r in T},d^3&&(f.get=m?T=>(d^1?l2:t5)(T,i,d^4?s:w.get):T=>T[r]),d>2&&(f.set=m?(T,v)=>u2(T,i,v,d^4?s:w.set):(T,v)=>T[r]=v)),c=(0,n[k])(d?d<4?m?s:w[g]:d>4?void 0:{get:w.get,set:w.set}:i,u),l._=1,d^4||c===void 0?Nd(c)&&(d>4?y.unshift(c):d?m?s=c:w[g]=c:i=c):typeof c!="object"||c===null?eu("Object expected"):(Nd(a=c.get)&&(w.get=a),Nd(a=c.set)&&(w.set=a),Nd(a=c.init)&&y.unshift(a));return d||Z8(t,i),w&&Zl(i,r,w),m?d^4?s:w:i},$e=(t,e,r)=>m2(t,typeof e!="symbol"?e+"":e,r),gS=(t,e,r)=>e.has(t)||eu("Cannot "+r),e5=(t,e)=>Object(e)!==e?eu('Cannot use the "in" operator on this value'):t.has(e),l2=(t,e,r)=>(gS(t,e,"read from private field"),r?r.call(t):e.get(t)),ie=(t,e,r)=>e.has(t)?eu("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),u2=(t,e,r,n)=>(gS(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),t5=(t,e,r)=>(gS(t,e,"access private method"),r);var YR=ri((CT,PT)=>{(function(t,e){typeof CT=="object"&&typeof PT<"u"?PT.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs=e()})(CT,(function(){"use strict";var t=1e3,e=6e4,r=36e5,n="millisecond",i="second",s="minute",a="hour",c="day",l="week",u="month",f="quarter",d="year",h="date",m="Invalid Date",p=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,g=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,y={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:o(function(A){var R=["th","st","nd","rd"],F=A%100;return"["+A+(R[(F-20)%10]||R[F]||R[0])+"]"},"ordinal")},b=o(function(A,R,F){var $=String(A);return!$||$.length>=R?A:""+Array(R+1-$.length).join(F)+A},"m"),w={s:b,z:o(function(A){var R=-A.utcOffset(),F=Math.abs(R),$=Math.floor(F/60),W=F%60;return(R<=0?"+":"-")+b($,2,"0")+":"+b(W,2,"0")},"z"),m:o(function A(R,F){if(R.date()<F.date())return-A(F,R);var $=12*(F.year()-R.year())+(F.month()-R.month()),W=R.clone().add($,u),Q=F-W<0,re=R.clone().add($+(Q?-1:1),u);return+(-($+(F-W)/(Q?W-re:re-W))||0)},"t"),a:o(function(A){return A<0?Math.ceil(A)||0:Math.floor(A)},"a"),p:o(function(A){return{M:u,y:d,w:l,d:c,D:h,h:a,m:s,s:i,ms:n,Q:f}[A]||String(A||"").toLowerCase().replace(/s$/,"")},"p"),u:o(function(A){return A===void 0},"u")},k="en",T={};T[k]=y;var v="$isDayjsObject",S=o(function(A){return A instanceof O||!(!A||!A[v])},"S"),M=o(function A(R,F,$){var W;if(!R)return k;if(typeof R=="string"){var Q=R.toLowerCase();T[Q]&&(W=Q),F&&(T[Q]=F,W=Q);var re=R.split("-");if(!W&&re.length>1)return A(re[0])}else{var fe=R.name;T[fe]=R,W=fe}return!$&&W&&(k=W),W||!$&&k},"t"),P=o(function(A,R){if(S(A))return A.clone();var F=typeof R=="object"?R:{};return F.date=A,F.args=arguments,new O(F)},"O"),N=w;N.l=M,N.i=S,N.w=function(A,R){return P(A,{locale:R.$L,utc:R.$u,x:R.$x,$offset:R.$offset})};var O=(function(){function A(F){this.$L=M(F.locale,null,!0),this.parse(F),this.$x=this.$x||F.x||{},this[v]=!0}o(A,"M");var R=A.prototype;return R.parse=function(F){this.$d=(function($){var W=$.date,Q=$.utc;if(W===null)return new Date(NaN);if(N.u(W))return new Date;if(W instanceof Date)return new Date(W);if(typeof W=="string"&&!/Z$/i.test(W)){var re=W.match(p);if(re){var fe=re[2]-1||0,E=(re[7]||"0").substring(0,3);return Q?new Date(Date.UTC(re[1],fe,re[3]||1,re[4]||0,re[5]||0,re[6]||0,E)):new Date(re[1],fe,re[3]||1,re[4]||0,re[5]||0,re[6]||0,E)}}return new Date(W)})(F),this.init()},R.init=function(){var F=this.$d;this.$y=F.getFullYear(),this.$M=F.getMonth(),this.$D=F.getDate(),this.$W=F.getDay(),this.$H=F.getHours(),this.$m=F.getMinutes(),this.$s=F.getSeconds(),this.$ms=F.getMilliseconds()},R.$utils=function(){return N},R.isValid=function(){return this.$d.toString()!==m},R.isSame=function(F,$){var W=P(F);return this.startOf($)<=W&&W<=this.endOf($)},R.isAfter=function(F,$){return P(F)<this.startOf($)},R.isBefore=function(F,$){return this.endOf($)<P(F)},R.$g=function(F,$,W){return N.u(F)?this[$]:this.set(W,F)},R.unix=function(){return Math.floor(this.valueOf()/1e3)},R.valueOf=function(){return this.$d.getTime()},R.startOf=function(F,$){var W=this,Q=!!N.u($)||$,re=N.p(F),fe=o(function(L,_){var z=N.w(W.$u?Date.UTC(W.$y,_,L):new Date(W.$y,_,L),W);return Q?z:z.endOf(c)},"l"),E=o(function(L,_){return N.w(W.toDate()[L].apply(W.toDate("s"),(Q?[0,0,0,0]:[23,59,59,999]).slice(_)),W)},"$"),_e=this.$W,Ge=this.$M,D=this.$D,yt="set"+(this.$u?"UTC":"");switch(re){case d:return Q?fe(1,0):fe(31,11);case u:return Q?fe(1,Ge):fe(0,Ge+1);case l:var Yt=this.$locale().weekStart||0,Nn=(_e<Yt?_e+7:_e)-Yt;return fe(Q?D-Nn:D+(6-Nn),Ge);case c:case h:return E(yt+"Hours",0);case a:return E(yt+"Minutes",1);case s:return E(yt+"Seconds",2);case i:return E(yt+"Milliseconds",3);default:return this.clone()}},R.endOf=function(F){return this.startOf(F,!1)},R.$set=function(F,$){var W,Q=N.p(F),re="set"+(this.$u?"UTC":""),fe=(W={},W[c]=re+"Date",W[h]=re+"Date",W[u]=re+"Month",W[d]=re+"FullYear",W[a]=re+"Hours",W[s]=re+"Minutes",W[i]=re+"Seconds",W[n]=re+"Milliseconds",W)[Q],E=Q===c?this.$D+($-this.$W):$;if(Q===u||Q===d){var _e=this.clone().set(h,1);_e.$d[fe](E),_e.init(),this.$d=_e.set(h,Math.min(this.$D,_e.daysInMonth())).$d}else fe&&this.$d[fe](E);return this.init(),this},R.set=function(F,$){return this.clone().$set(F,$)},R.get=function(F){return this[N.p(F)]()},R.add=function(F,$){var W,Q=this;F=Number(F);var re=N.p($),fe=o(function(Ge){var D=P(Q);return N.w(D.date(D.date()+Math.round(Ge*F)),Q)},"y");if(re===u)return this.set(u,this.$M+F);if(re===d)return this.set(d,this.$y+F);if(re===c)return fe(1);if(re===l)return fe(7);var E=(W={},W[s]=e,W[a]=r,W[i]=t,W)[re]||1,_e=this.$d.getTime()+F*E;return N.w(_e,this)},R.subtract=function(F,$){return this.add(-1*F,$)},R.format=function(F){var $=this,W=this.$locale();if(!this.isValid())return W.invalidDate||m;var Q=F||"YYYY-MM-DDTHH:mm:ssZ",re=N.z(this),fe=this.$H,E=this.$m,_e=this.$M,Ge=W.weekdays,D=W.months,yt=W.meridiem,Yt=o(function(_,z,U,q){return _&&(_[z]||_($,Q))||U[z].slice(0,q)},"h"),Nn=o(function(_){return N.s(fe%12||12,_,"0")},"d"),L=yt||function(_,z,U){var q=_<12?"AM":"PM";return U?q.toLowerCase():q};return Q.replace(g,(function(_,z){return z||(function(U){switch(U){case"YY":return String($.$y).slice(-2);case"YYYY":return N.s($.$y,4,"0");case"M":return _e+1;case"MM":return N.s(_e+1,2,"0");case"MMM":return Yt(W.monthsShort,_e,D,3);case"MMMM":return Yt(D,_e);case"D":return $.$D;case"DD":return N.s($.$D,2,"0");case"d":return String($.$W);case"dd":return Yt(W.weekdaysMin,$.$W,Ge,2);case"ddd":return Yt(W.weekdaysShort,$.$W,Ge,3);case"dddd":return Ge[$.$W];case"H":return String(fe);case"HH":return N.s(fe,2,"0");case"h":return Nn(1);case"hh":return Nn(2);case"a":return L(fe,E,!0);case"A":return L(fe,E,!1);case"m":return String(E);case"mm":return N.s(E,2,"0");case"s":return String($.$s);case"ss":return N.s($.$s,2,"0");case"SSS":return N.s($.$ms,3,"0");case"Z":return re}return null})(_)||re.replace(":","")}))},R.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},R.diff=function(F,$,W){var Q,re=this,fe=N.p($),E=P(F),_e=(E.utcOffset()-this.utcOffset())*e,Ge=this-E,D=o(function(){return N.m(re,E)},"D");switch(fe){case d:Q=D()/12;break;case u:Q=D();break;case f:Q=D()/3;break;case l:Q=(Ge-_e)/6048e5;break;case c:Q=(Ge-_e)/864e5;break;case a:Q=Ge/r;break;case s:Q=Ge/e;break;case i:Q=Ge/t;break;default:Q=Ge}return W?Q:N.a(Q)},R.daysInMonth=function(){return this.endOf(u).$D},R.$locale=function(){return T[this.$L]},R.locale=function(F,$){if(!F)return this.$L;var W=this.clone(),Q=M(F,$,!0);return Q&&(W.$L=Q),W},R.clone=function(){return N.w(this.$d,this)},R.toDate=function(){return new Date(this.valueOf())},R.toJSON=function(){return this.isValid()?this.toISOString():null},R.toISOString=function(){return this.$d.toISOString()},R.toString=function(){return this.$d.toUTCString()},A})(),Y=O.prototype;return P.prototype=Y,[["$ms",n],["$s",i],["$m",s],["$H",a],["$W",c],["$M",u],["$y",d],["$D",h]].forEach((function(A){Y[A[1]]=function(R){return this.$g(R,A[0],A[1])}})),P.extend=function(A,R){return A.$i||(A(R,O,P),A.$i=!0),P},P.locale=M,P.isDayjs=S,P.unix=function(A){return P(1e3*A)},P.en=T[k],P.Ls=T,P.p={},P}))});var GR=ri((IT,_T)=>{(function(t,e){typeof IT=="object"&&typeof _T<"u"?_T.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs_plugin_isToday=e()})(IT,(function(){"use strict";return function(t,e,r){e.prototype.isToday=function(){var n="YYYY-MM-DD",i=r();return this.format(n)===i.format(n)}}}))});var JR=ri((_Ve,XR)=>{"use strict";XR.exports=class{static{o(this,"SymbolTreeNode")}constructor(){this.parent=null,this.previousSibling=null,this.nextSibling=null,this.firstChild=null,this.lastChild=null,this.childrenVersion=0,this.childIndexCachedUpTo=null,this.cachedIndex=-1,this.cachedIndexVersion=NaN}get isAttached(){return!!(this.parent||this.previousSibling||this.nextSibling)}get hasChildren(){return!!this.firstChild}childrenChanged(){this.childrenVersion=this.childrenVersion+1&4294967295,this.childIndexCachedUpTo=null}getCachedIndex(e){return this.cachedIndexVersion!==e.childrenVersion?(this.cachedIndexVersion=NaN,-1):this.cachedIndex}setCachedIndex(e,r){this.cachedIndexVersion=e.childrenVersion,this.cachedIndex=r}}});var eN=ri((MVe,ZR)=>{"use strict";ZR.exports=Object.freeze({DISCONNECTED:1,PRECEDING:2,FOLLOWING:4,CONTAINS:8,CONTAINED_BY:16})});var sN=ri((OVe,iN)=>{"use strict";var tN=Symbol(),rN=Symbol(),ma=Symbol(),nN=Symbol(),Ri=class{static{o(this,"TreeIterator")}constructor(e,r,n,i){this[tN]=e,this[rN]=r,this[ma]=n,this[nN]=i}next(){let e=this[tN],r=this[nN],n=this[rN];if(!this[ma])return{done:!0,value:n};let i=this[ma];return r===1?this[ma]=e._node(i).previousSibling:r===2?this[ma]=e._node(i).nextSibling:r===3?this[ma]=e._node(i).parent:r===4?this[ma]=e.preceding(i,{root:n}):this[ma]=e.following(i,{root:n}),{done:!1,value:i}}};Object.defineProperty(Ri.prototype,Symbol.iterator,{value:o(function(){return this},"value"),writable:!1}),Ri.PREV=1,Ri.NEXT=2,Ri.PARENT=3,Ri.PRECEDING=4,Ri.FOLLOWING=5,Object.freeze(Ri),Object.freeze(Ri.prototype),iN.exports=Ri});var aN=ri((NVe,oN)=>{"use strict";var qj=JR(),pa=eN(),ci=sN();function LT(){return!0}o(LT,"returnTrue");function Wu(t,e){return t[t.length-1-e]}o(Wu,"reverseArrayIndex");var Ub=class{static{o(this,"SymbolTree")}constructor(e){this.symbol=Symbol(e||"SymbolTree data")}initialize(e){return this._node(e),e}_node(e){if(!e)return null;let r=e[this.symbol];return r||(e[this.symbol]=new qj)}hasChildren(e){return this._node(e).hasChildren}firstChild(e){return this._node(e).firstChild}lastChild(e){return this._node(e).lastChild}previousSibling(e){return this._node(e).previousSibling}nextSibling(e){return this._node(e).nextSibling}parent(e){return this._node(e).parent}lastInclusiveDescendant(e){let r,n=e;for(;r=this._node(n).lastChild;)n=r;return n}preceding(e,r){let n=r&&r.root;if(e===n)return null;let i=this._node(e).previousSibling;return i?this.lastInclusiveDescendant(i):this._node(e).parent}following(e,r){let n=r&&r.root,s=!(r&&r.skipChildren)&&this._node(e).firstChild;if(s)return s;let a=e;do{if(a===n)return null;let c=this._node(a).nextSibling;if(c)return c;a=this._node(a).parent}while(a);return null}childrenToArray(e,r){let n=r&&r.array||[],i=r&&r.filter||LT,s=r&&r.thisArg||void 0,a=this._node(e),c=a.firstChild,l=0;for(;c;){let u=this._node(c);u.setCachedIndex(a,l),i.call(s,c)&&n.push(c),c=u.nextSibling,++l}return n}ancestorsToArray(e,r){let n=r&&r.array||[],i=r&&r.filter||LT,s=r&&r.thisArg||void 0,a=e;for(;a;)i.call(s,a)&&n.push(a),a=this._node(a).parent;return n}treeToArray(e,r){let n=r&&r.array||[],i=r&&r.filter||LT,s=r&&r.thisArg||void 0,a=e;for(;a;)i.call(s,a)&&n.push(a),a=this.following(a,{root:e});return n}childrenIterator(e,r){let n=r&&r.reverse,i=this._node(e);return new ci(this,e,n?i.lastChild:i.firstChild,n?ci.PREV:ci.NEXT)}previousSiblingsIterator(e){return new ci(this,e,this._node(e).previousSibling,ci.PREV)}nextSiblingsIterator(e){return new ci(this,e,this._node(e).nextSibling,ci.NEXT)}ancestorsIterator(e){return new ci(this,e,e,ci.PARENT)}treeIterator(e,r){let n=r&&r.reverse;return new ci(this,e,n?this.lastInclusiveDescendant(e):e,n?ci.PRECEDING:ci.FOLLOWING)}index(e){let r=this._node(e),n=this._node(r.parent);if(!n)return-1;let i=r.getCachedIndex(n);if(i>=0)return i;i=0;let s=n.firstChild;if(n.childIndexCachedUpTo){let a=this._node(n.childIndexCachedUpTo);s=a.nextSibling,i=a.getCachedIndex(n)+1}for(;s;){let a=this._node(s);if(a.setCachedIndex(n,i),s===e)break;++i,s=a.nextSibling}return n.childIndexCachedUpTo=e,i}childrenCount(e){let r=this._node(e);return r.lastChild?this.index(r.lastChild)+1:0}compareTreePosition(e,r){if(e===r)return 0;let n=[];{let f=e;for(;f;){if(f===r)return pa.CONTAINS|pa.PRECEDING;n.push(f),f=this.parent(f)}}let i=[];{let f=r;for(;f;){if(f===e)return pa.CONTAINED_BY|pa.FOLLOWING;i.push(f),f=this.parent(f)}}let s=Wu(n,0);if(!s||s!==Wu(i,0))return pa.DISCONNECTED;let a=0,c=Math.min(n.length,i.length);for(let f=0;f<c;++f){let d=Wu(n,f),h=Wu(i,f);if(d!==h)break;a=f}let l=this.index(Wu(n,a+1));return this.index(Wu(i,a+1))<l?pa.PRECEDING:pa.FOLLOWING}remove(e){let r=this._node(e),n=this._node(r.parent),i=this._node(r.previousSibling),s=this._node(r.nextSibling);return n&&(n.firstChild===e&&(n.firstChild=r.nextSibling),n.lastChild===e&&(n.lastChild=r.previousSibling)),i&&(i.nextSibling=r.nextSibling),s&&(s.previousSibling=r.previousSibling),r.parent=null,r.previousSibling=null,r.nextSibling=null,r.cachedIndex=-1,r.cachedIndexVersion=NaN,n&&n.childrenChanged(),e}insertBefore(e,r){let n=this._node(e),i=this._node(n.previousSibling),s=this._node(r),a=this._node(n.parent);if(s.isAttached)throw Error("Given object is already present in this SymbolTree, remove it first");return s.parent=n.parent,s.previousSibling=n.previousSibling,s.nextSibling=e,n.previousSibling=r,i&&(i.nextSibling=r),a&&a.firstChild===e&&(a.firstChild=r),a&&a.childrenChanged(),r}insertAfter(e,r){let n=this._node(e),i=this._node(n.nextSibling),s=this._node(r),a=this._node(n.parent);if(s.isAttached)throw Error("Given object is already present in this SymbolTree, remove it first");return s.parent=n.parent,s.previousSibling=e,s.nextSibling=n.nextSibling,n.nextSibling=r,i&&(i.previousSibling=r),a&&a.lastChild===e&&(a.lastChild=r),a&&a.childrenChanged(),r}prependChild(e,r){let n=this._node(e),i=this._node(r);if(i.isAttached)throw Error("Given object is already present in this SymbolTree, remove it first");return n.hasChildren?this.insertBefore(n.firstChild,r):(i.parent=e,n.firstChild=r,n.lastChild=r,n.childrenChanged()),r}appendChild(e,r){let n=this._node(e),i=this._node(r);if(i.isAttached)throw Error("Given object is already present in this SymbolTree, remove it first");return n.hasChildren?this.insertAfter(n.lastChild,r):(i.parent=e,n.firstChild=r,n.lastChild=r,n.childrenChanged()),r}};oN.exports=Ub,Ub.TreePosition=pa});var PN=ri((yje,CN)=>{"use strict";CN.exports=function(t,e){e||(e={}),typeof e=="function"&&(e={cmp:e});var r=typeof e.cycles=="boolean"?e.cycles:!1,n=e.cmp&&(function(s){return function(a){return function(c,l){var u={key:c,value:a[c]},f={key:l,value:a[l]};return s(u,f)}}})(e.cmp),i=[];return o((function s(a){if(a&&a.toJSON&&typeof a.toJSON=="function"&&(a=a.toJSON()),a!==void 0){if(typeof a=="number")return isFinite(a)?""+a:"null";if(typeof a!="object")return JSON.stringify(a);var c,l;if(Array.isArray(a)){for(l="[",c=0;c<a.length;c++)c&&(l+=","),l+=s(a[c])||"null";return l+"]"}if(a===null)return"null";if(i.indexOf(a)!==-1){if(r)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var u=i.push(a)-1,f=Object.keys(a).sort(n&&n(a));for(l="",c=0;c<f.length;c++){var d=f[c],h=s(a[d]);h&&(l&&(l+=","),l+=JSON.stringify(d)+":"+h)}return i.splice(u,1),"{"+l+"}"}}),"stringify")(t)}});var OB=ri((kct,MB)=>{"use strict";var O0=Object.prototype.hasOwnProperty,vB=Object.prototype.toString,EB=Object.defineProperty,CB=Object.getOwnPropertyDescriptor,PB=o(function(e){return typeof Array.isArray=="function"?Array.isArray(e):vB.call(e)==="[object Array]"},"isArray"),IB=o(function(e){if(!e||vB.call(e)!=="[object Object]")return!1;var r=O0.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&O0.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!n)return!1;var i;for(i in e);return typeof i>"u"||O0.call(e,i)},"isPlainObject"),_B=o(function(e,r){EB&&r.name==="__proto__"?EB(e,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):e[r.name]=r.newValue},"setProperty"),DB=o(function(e,r){if(r==="__proto__")if(O0.call(e,r)){if(CB)return CB(e,r).value}else return;return e[r]},"getProperty");MB.exports=o(function t(){var e,r,n,i,s,a,c=arguments[0],l=1,u=arguments.length,f=!1;for(typeof c=="boolean"&&(f=c,c=arguments[1]||{},l=2),(c==null||typeof c!="object"&&typeof c!="function")&&(c={});l<u;++l)if(e=arguments[l],e!=null)for(r in e)n=DB(c,r),i=DB(e,r),c!==i&&(f&&i&&(IB(i)||(s=PB(i)))?(s?(s=!1,a=n&&PB(n)?n:[]):a=n&&IB(n)?n:{},_B(c,{name:r,newValue:t(f,a,i)})):typeof i<"u"&&_B(c,{name:r,newValue:i}));return c},"extend")});var _3=ri((qpt,ZE)=>{(function(){var t;typeof ZE<"u"?t=ZE.exports=n:t=(function(){return this||(0,eval)("this")})(),t.format=n,t.vsprintf=r,typeof console<"u"&&typeof console.log=="function"&&(t.printf=e);function e(){console.log(n.apply(null,arguments))}o(e,"printf");function r(i,s){return n.apply(null,[i].concat(s))}o(r,"vsprintf");function n(i){for(var s=1,a=[].slice.call(arguments),c=0,l=i.length,u="",f,d=!1,h,m,p=!1,g,y=o(function(){return a[s++]},"nextArg"),b=o(function(){for(var w="";/\d/.test(i[c]);)w+=i[c++],f=i[c];return w.length>0?parseInt(w):null},"slurpNumber");c<l;++c)if(f=i[c],d)switch(d=!1,f=="."?(p=!1,f=i[++c]):f=="0"&&i[c+1]=="."?(p=!0,c+=2,f=i[c]):p=!0,g=b(),f){case"b":u+=parseInt(y(),10).toString(2);break;case"c":h=y(),typeof h=="string"||h instanceof String?u+=h:u+=String.fromCharCode(parseInt(h,10));break;case"d":u+=parseInt(y(),10);break;case"f":m=String(parseFloat(y()).toFixed(g||6)),u+=p?m:m.replace(/^0/,"");break;case"j":u+=JSON.stringify(y());break;case"o":u+="0"+parseInt(y(),10).toString(8);break;case"s":u+=y();break;case"x":u+="0x"+parseInt(y(),10).toString(16);break;case"X":u+="0x"+parseInt(y(),10).toString(16).toUpperCase();break;default:u+=f;break}else f==="%"?d=!0:u+=f;return u}o(n,"format")})()});var Q3=ri(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0}),Vi.PathError=Vi.TokenData=void 0,Vi.parse=fC,Vi.compile=UJ,Vi.match=HJ,Vi.pathToRegexp=q3,Vi.stringify=jJ;var cC="/",lC=o(t=>t,"NOOP_VALUE"),W3=/^[$_\p{ID_Start}]$/u,uC=/^[$\u200c\u200d\p{ID_Continue}]$/u,BJ={"{":"{","}":"}","(":"(",")":")","[":"[","]":"]","+":"+","?":"?","!":"!"};function zJ(t){return t.replace(/[{}()\[\]+?!:*\\]/g,"\\$&")}o(zJ,"escapeText");function Ls(t){return t.replace(/[.+*?^${}()[\]|/\\]/g,"\\$&")}o(Ls,"escape");var K0=class{static{o(this,"TokenData")}constructor(e,r){this.tokens=e,this.originalPath=r}};Vi.TokenData=K0;var pl=class extends TypeError{static{o(this,"PathError")}constructor(e,r){let n=e;r&&(n+=`: ${r}`),n+="; visit https://git.new/pathToRegexpError for info",super(n),this.originalPath=r}};Vi.PathError=pl;function fC(t,e={}){let{encodePath:r=lC}=e,n=[...t],i=[],s=0,a=0;function c(){let u="";if(W3.test(n[s]))do u+=n[s++];while(uC.test(n[s]));else if(n[s]==='"'){let f=s;for(;s++<n.length;){if(n[s]==='"'){s++,f=0;break}n[s]==="\\"&&s++,u+=n[s]}if(f)throw new pl(`Unterminated quote at index ${f}`,t)}if(!u)throw new pl(`Missing parameter name at index ${s}`,t);return u}for(o(c,"name");s<n.length;){let u=n[s],f=BJ[u];f?i.push({type:f,index:s++,value:u}):u==="\\"?i.push({type:"escape",index:s++,value:n[s++]}):u===":"?i.push({type:"param",index:s++,value:c()}):u==="*"?i.push({type:"wildcard",index:s++,value:c()}):i.push({type:"char",index:s++,value:u})}i.push({type:"end",index:s,value:""});function l(u){let f=[];for(;;){let d=i[a++];if(d.type===u)break;if(d.type==="char"||d.type==="escape"){let h=d.value,m=i[a];for(;m.type==="char"||m.type==="escape";)h+=m.value,m=i[++a];f.push({type:"text",value:r(h)});continue}if(d.type==="param"||d.type==="wildcard"){f.push({type:d.type,name:d.value});continue}if(d.type==="{"){f.push({type:"group",tokens:l("}")});continue}throw new pl(`Unexpected ${d.type} at index ${d.index}, expected ${u}`,t)}return f}return o(l,"consumeUntil"),new K0(l("end"),t)}o(fC,"parse");function UJ(t,e={}){let{encode:r=encodeURIComponent,delimiter:n=cC}=e,i=typeof t=="object"?t:fC(t,e),s=j3(i.tokens,n,r);return o(function(c={}){let[l,...u]=s(c);if(u.length)throw new TypeError(`Missing parameters: ${u.join(", ")}`);return l},"path")}o(UJ,"compile");function j3(t,e,r){let n=t.map(i=>$J(i,e,r));return i=>{let s=[""];for(let a of n){let[c,...l]=a(i);s[0]+=c,s.push(...l)}return s}}o(j3,"tokensToFunction");function $J(t,e,r){if(t.type==="text")return()=>[t.value];if(t.type==="group"){let i=j3(t.tokens,e,r);return s=>{let[a,...c]=i(s);return c.length?[""]:[a]}}let n=r||lC;return t.type==="wildcard"&&r!==!1?i=>{let s=i[t.name];if(s==null)return["",t.name];if(!Array.isArray(s)||s.length===0)throw new TypeError(`Expected "${t.name}" to be a non-empty array`);return[s.map((a,c)=>{if(typeof a!="string")throw new TypeError(`Expected "${t.name}/${c}" to be a string`);return n(a)}).join(e)]}:i=>{let s=i[t.name];if(s==null)return["",t.name];if(typeof s!="string")throw new TypeError(`Expected "${t.name}" to be a string`);return[n(s)]}}o($J,"tokenToFunction");function HJ(t,e={}){let{decode:r=decodeURIComponent,delimiter:n=cC}=e,{regexp:i,keys:s}=q3(t,e),a=s.map(c=>r===!1?lC:c.type==="param"?r:l=>l.split(n).map(r));return o(function(l){let u=i.exec(l);if(!u)return!1;let f=u[0],d=Object.create(null);for(let h=1;h<u.length;h++){if(u[h]===void 0)continue;let m=s[h-1],p=a[h-1];d[m.name]=p(u[h])}return{path:f,params:d}},"match")}o(HJ,"match");function q3(t,e={}){let{delimiter:r=cC,end:n=!0,sensitive:i=!1,trailing:s=!0}=e,a=[],c=i?"":"i",l=[];for(let d of Y3(t,[])){let h=typeof d=="object"?d:fC(d,e);for(let m of X0(h.tokens,0,[]))l.push(VJ(m,r,a,h.originalPath))}let u=`^(?:${l.join("|")})`;return s&&(u+=`(?:${Ls(r)}$)?`),u+=n?"$":`(?=${Ls(r)}|$)`,{regexp:new RegExp(u,c),keys:a}}o(q3,"pathToRegexp");function Y3(t,e){if(Array.isArray(t))for(let r of t)Y3(r,e);else e.push(t);return e}o(Y3,"pathsToArray");function*X0(t,e,r){if(e===t.length)return yield r;let n=t[e];if(n.type==="group")for(let i of X0(n.tokens,0,r.slice()))yield*X0(t,e+1,i);else r.push(n);yield*X0(t,e+1,r)}o(X0,"flatten");function VJ(t,e,r,n){let i="",s="",a=!0;for(let c of t){if(c.type==="text"){i+=Ls(c.value),s+=c.value,a||(a=c.value.includes(e));continue}if(c.type==="param"||c.type==="wildcard"){if(!a&&!s)throw new pl(`Missing text before "${c.name}" ${c.type}`,n);c.type==="param"?i+=`(${WJ(e,a?"":s)}+)`:i+="([\\s\\S]+)",r.push(c),s="",a=!1;continue}}return i}o(VJ,"toRegExpSource");function WJ(t,e){return e.length<2?t.length<2?`[^${Ls(t+e)}]`:`(?:(?!${Ls(t)})[^${Ls(e)}])`:t.length<2?`(?:(?!${Ls(e)})[^${Ls(t)}])`:`(?:(?!${Ls(e)}|${Ls(t)})[\\s\\S])`}o(WJ,"negate");function G3(t){let e="",r=0;function n(i){return qJ(i)&&YJ(t[r])?i:JSON.stringify(i)}for(o(n,"name");r<t.length;){let i=t[r++];if(i.type==="text"){e+=zJ(i.value);continue}if(i.type==="group"){e+=`{${G3(i.tokens)}}`;continue}if(i.type==="param"){e+=`:${n(i.name)}`;continue}if(i.type==="wildcard"){e+=`*${n(i.name)}`;continue}throw new TypeError(`Unknown token type: ${i.type}`)}return e}o(G3,"stringifyTokens");function jJ(t){return G3(t.tokens)}o(jJ,"stringify");function qJ(t){let[e,...r]=t;return W3.test(e)&&r.every(n=>uC.test(n))}o(qJ,"isNameSafe");function YJ(t){return t&&t.type==="text"?!uC.test(t.value[0]):!0}o(YJ,"isNextNameSafe")});var o4=ri((FC,LC)=>{(function(t,e){typeof FC=="object"&&typeof LC<"u"?LC.exports=e():typeof define=="function"&&define.amd?define(e):(t=t||self,t.SweetScroll=e())})(FC,function(){"use strict";var t=o(function(){return t=Object.assign||o(function(_){for(var z,U=1,q=arguments.length;U<q;U++){z=arguments[U];for(var be in z)Object.prototype.hasOwnProperty.call(z,be)&&(_[be]=z[be])}return _},"__assign"),t.apply(this,arguments)},"__assign"),e=!!(typeof window<"u"&&window.document&&window.document.createElement),r=e?window.history&&"pushState"in window.history&&window.location.protocol!=="file:":!1,n=(function(){var L=!1;if(!e)return L;try{var _=window,z=Object.defineProperty({},"passive",{get:o(function(){L=!0},"get")});_.addEventListener("test",null,z),_.removeEventListener("test",null,z)}catch{}return L})(),i=o(function(L){return typeof L=="string"},"isString"),s=o(function(L){return typeof L=="function"},"isFunction"),a=o(function(L){return Array.isArray(L)},"isArray"),c=o(function(L){return!a(L)&&L-parseFloat(L)+1>=0},"isNumeric"),l=o(function(L,_){return L&&L.hasOwnProperty(_)},"hasProp"),u=e?window.requestAnimationFrame.bind(window):null,f=e?window.cancelAnimationFrame.bind(window):null,d=Math.cos,h=Math.sin,m=Math.pow,p=Math.sqrt,g=Math.PI,y={linear:o(function(L){return L},"linear"),easeInQuad:o(function(L,_,z,U,q){return U*(_/=q)*_+z},"easeInQuad"),easeOutQuad:o(function(L,_,z,U,q){return-U*(_/=q)*(_-2)+z},"easeOutQuad"),easeInOutQuad:o(function(L,_,z,U,q){return(_/=q/2)<1?U/2*_*_+z:-U/2*(--_*(_-2)-1)+z},"easeInOutQuad"),easeInCubic:o(function(L,_,z,U,q){return U*(_/=q)*_*_+z},"easeInCubic"),easeOutCubic:o(function(L,_,z,U,q){return U*((_=_/q-1)*_*_+1)+z},"easeOutCubic"),easeInOutCubic:o(function(L,_,z,U,q){return(_/=q/2)<1?U/2*_*_*_+z:U/2*((_-=2)*_*_+2)+z},"easeInOutCubic"),easeInQuart:o(function(L,_,z,U,q){return U*(_/=q)*_*_*_+z},"easeInQuart"),easeOutQuart:o(function(L,_,z,U,q){return-U*((_=_/q-1)*_*_*_-1)+z},"easeOutQuart"),easeInOutQuart:o(function(L,_,z,U,q){return(_/=q/2)<1?U/2*_*_*_*_+z:-U/2*((_-=2)*_*_*_-2)+z},"easeInOutQuart"),easeInQuint:o(function(L,_,z,U,q){return U*(_/=q)*_*_*_*_+z},"easeInQuint"),easeOutQuint:o(function(L,_,z,U,q){return U*((_=_/q-1)*_*_*_*_+1)+z},"easeOutQuint"),easeInOutQuint:o(function(L,_,z,U,q){return(_/=q/2)<1?U/2*_*_*_*_*_+z:U/2*((_-=2)*_*_*_*_+2)+z},"easeInOutQuint"),easeInSine:o(function(L,_,z,U,q){return-U*d(_/q*(g/2))+U+z},"easeInSine"),easeOutSine:o(function(L,_,z,U,q){return U*h(_/q*(g/2))+z},"easeOutSine"),easeInOutSine:o(function(L,_,z,U,q){return-U/2*(d(g*_/q)-1)+z},"easeInOutSine"),easeInExpo:o(function(L,_,z,U,q){return _===0?z:U*m(2,10*(_/q-1))+z},"easeInExpo"),easeOutExpo:o(function(L,_,z,U,q){return _===q?z+U:U*(-m(2,-10*_/q)+1)+z},"easeOutExpo"),easeInOutExpo:o(function(L,_,z,U,q){return _===0?z:_===q?z+U:(_/=q/2)<1?U/2*m(2,10*(_-1))+z:U/2*(-m(2,-10*--_)+2)+z},"easeInOutExpo"),easeInCirc:o(function(L,_,z,U,q){return-U*(p(1-(_/=q)*_)-1)+z},"easeInCirc"),easeOutCirc:o(function(L,_,z,U,q){return U*p(1-(_=_/q-1)*_)+z},"easeOutCirc"),easeInOutCirc:o(function(L,_,z,U,q){return(_/=q/2)<1?-U/2*(p(1-_*_)-1)+z:U/2*(p(1-(_-=2)*_)+1)+z},"easeInOutCirc")},b=o(function(L){return Array.prototype.slice.call(L?document.querySelectorAll(L):[])},"$$"),w=o(function(L){return b(L).shift()||null},"$"),k=o(function(L){return L instanceof Element},"isElement"),T=o(function(L){return L===window},"isWindow"),v=o(function(L){return L===document.documentElement||L===document.body},"isRootContainer"),S=o(function(L,_){if(k(_))return L===_;for(var z=b(_),U=z.length;--U>=0&&z[U]!==L;);return U>-1},"matches"),M=o(function(L){return Math.max(L.scrollHeight,L.clientHeight,L.offsetHeight)},"getHeight"),P=o(function(L){return Math.max(L.scrollWidth,L.clientWidth,L.offsetWidth)},"getWidth"),N=o(function(L){return{width:P(L),height:M(L)}},"getSize"),O=o(function(L){var _=T(L)||v(L);return{viewport:{width:_?Math.min(window.innerWidth,document.documentElement.clientWidth):L.clientWidth,height:_?window.innerHeight:L.clientHeight},size:_?{width:Math.max(P(document.body),P(document.documentElement)),height:Math.max(M(document.body),M(document.documentElement))}:N(L)}},"getViewportAndElementSizes"),Y={y:"scrollTop",x:"scrollLeft"},A={y:"pageYOffset",x:"pageXOffset"},R=o(function(L,_){return T(L)?L[A[_]]:L[Y[_]]},"getScroll"),F=o(function(L,_,z){if(T(L)){var U=z==="y";L.scrollTo(U?L.pageXOffset:_,U?_:L.pageYOffset)}else L[Y[z]]=_},"setScroll"),$=o(function(L,_){var z=L.getBoundingClientRect();if(z.width||z.height){var U={top:0,left:0},q=void 0;if(T(_)||v(_))q=document.documentElement,U.top=window[A.y],U.left=window[A.x];else{q=_;var be=q.getBoundingClientRect();U.top=be.top*-1+q[Y.y],U.left=be.left*-1+q[Y.x]}return{top:z.top+U.top-q.clientTop,left:z.left+U.left-q.clientLeft}}return z},"getOffset"),W=(function(){return e?"onwheel"in document?"wheel":"mousewheel":"wheel"})(),Q=o(function(L){return L==="wheel"?W:L},"eventName"),re=o(function(L,_,z,U,q){z.split(" ").forEach(function(be){L[_](Q(be),U,n?{passive:q}:!1)})},"apply"),fe=o(function(L,_,z,U){return re(L,"addEventListener",_,z,U)},"addEvent"),E=o(function(L,_,z,U){return re(L,"removeEventListener",_,z,U)},"removeEvent"),_e=/^(\+|-)=(\d+(?:\.\d+)?)$/,Ge=o(function(L,_){var z={top:0,left:0,relative:!1};if(l(L,"top")||l(L,"left"))z=t({},z,L);else if(a(L))if(L.length>1)z.top=L[0],z.left=L[1];else if(L.length===1)z.top=_?L[0]:0,z.left=_?0:L[0];else return null;else if(c(L))_?z.top=L:z.left=L;else if(i(L)){var U=L.trim().match(_e);if(!U)return null;var q=U[1],be=parseInt(U[2],10);q==="+"?(z.top=_?be:0,z.left=_?0:be):(z.top=_?-be:0,z.left=_?0:-be),z.relative=!0}else return null;return z},"parseCoordinate"),D={trigger:"[data-scroll]",header:"[data-scroll-header]",duration:1e3,easing:"easeOutQuint",offset:0,vertical:!0,horizontal:!1,cancellable:!0,updateURL:!1,preventDefault:!0,stopPropagation:!0,before:null,after:null,cancel:null,complete:null,step:null},yt="click",Yt="wheel touchstart touchmove",Nn=(function(){function L(_,z){var U=this;this.$el=null,this.ctx={$trigger:null,opts:null,progress:!1,pos:null,startPos:null,easing:null,start:0,id:0,cancel:!1,hash:null},this.loop=function(be){var gt=U,mt=gt.$el,tt=gt.ctx;if(tt.start||(tt.start=be),!tt.progress||!mt){U.stop();return}var cn=tt.opts,dr=tt.pos,Yr=tt.start,Ii=tt.startPos,ss=tt.easing,An=cn.duration,ei={top:"y",left:"x"},ln=be-Yr,_t=Math.min(1,Math.max(ln/An,0));Object.keys(dr).forEach(function(os){var V=dr[os],K=Ii[os],ve=V-K;if(ve!==0){var Re=ss(_t,An*_t,0,1,An);F(mt,Math.round(K+ve*Re),ei[os])}}),ln<=An?(U.hook(cn,"step",_t),tt.id=L.raf(U.loop)):U.stop(!0)},this.handleClick=function(be){for(var gt=U.opts,mt=be.target;mt&&mt!==document;mt=mt.parentNode)if(S(mt,gt.trigger)){var tt=JSON.parse(mt.getAttribute("data-scroll-options")||"{}"),cn=mt.getAttribute("data-scroll"),dr=cn||mt.getAttribute("href"),Yr=t({},gt,tt),Ii=Yr.preventDefault,ss=Yr.stopPropagation,An=Yr.vertical,ei=Yr.horizontal;Ii&&be.preventDefault(),ss&&be.stopPropagation(),U.ctx.$trigger=mt,ei&&An?U.to(dr,Yr):An?U.toTop(dr,Yr):ei&&U.toLeft(dr,Yr);break}},this.handleStop=function(be){var gt=U.ctx,mt=gt.opts;mt&&mt.cancellable?(gt.cancel=!0,U.stop()):be.preventDefault()},this.opts=t({},D,_||{});var q=null;e&&(typeof z=="string"?q=w(z):z!=null?q=z:q=window),this.$el=q,q&&this.bind(!0,!1)}return o(L,"SweetScroll"),L.create=function(_,z){return new L(_,z)},L.prototype.to=function(_,z){if(e){var U=this,q=U.$el,be=U.ctx,gt=U.opts,mt=be.$trigger,tt=t({},gt,z||{}),cn=tt.offset,dr=tt.vertical,Yr=tt.horizontal,Ii=k(tt.header)?tt.header:w(tt.header),ss=/^#/,An=i(_)&&ss.test(_)?_:null;if(be.opts=tt,be.cancel=!1,be.hash=An,this.stop(),!!q){var ei=Ge(cn,dr),ln=Ge(_,dr),_t={top:0,left:0};if(ln)if(ln.relative){var os=R(q,dr?"y":"x");_t.top=dr?os+ln.top:ln.top,_t.left=dr?ln.left:os+ln.left}else _t=ln;else if(i(_)&&_!=="#"){var V=w(_);if(!V)return;_t=$(V,q)}ei&&(_t.top+=ei.top,_t.left+=ei.left),Ii&&(_t.top=Math.max(0,_t.top-N(Ii).height));var K=O(q),ve=K.viewport,Re=K.size;if(_t.top=dr?Math.max(0,Math.min(Re.height-ve.height,_t.top)):R(q,"y"),_t.left=Yr?Math.max(0,Math.min(Re.width-ve.width,_t.left)):R(q,"x"),this.hook(tt,"before",_t,mt)===!1){be.opts=null;return}be.pos=_t,this.start(tt),this.bind(!1,!0)}}},L.prototype.toTop=function(_,z){this.to(_,t({},z||{},{vertical:!0,horizontal:!1}))},L.prototype.toLeft=function(_,z){this.to(_,t({},z||{},{vertical:!1,horizontal:!0}))},L.prototype.toElement=function(_,z){var U=this.$el;!e||!U||this.to($(_,U),z||{})},L.prototype.stop=function(_){_===void 0&&(_=!1);var z=this,U=z.$el,q=z.ctx,be=q.pos;!U||!q.progress||(L.caf(q.id),q.progress=!1,q.start=0,q.id=0,_&&be&&(F(U,be.left,"x"),F(U,be.top,"y")),this.complete())},L.prototype.update=function(_){if(this.$el){var z=t({},this.opts,_);this.stop(),this.unbind(!0,!0),this.opts=z,this.bind(!0,!1)}},L.prototype.destroy=function(){this.$el&&(this.stop(),this.unbind(!0,!0),this.$el=null)},L.prototype.onBefore=function(_,z){return!0},L.prototype.onStep=function(_){},L.prototype.onAfter=function(_,z){},L.prototype.onCancel=function(){},L.prototype.onComplete=function(_){},L.prototype.start=function(_){var z=this.ctx;z.opts=_,z.progress=!0,z.easing=s(_.easing)?_.easing:y[_.easing];var U=this.$el,q={top:R(U,"y"),left:R(U,"x")};z.startPos=q,z.id=L.raf(this.loop)},L.prototype.complete=function(){var _=this,z=_.$el,U=_.ctx,q=U.hash,be=U.cancel,gt=U.opts,mt=U.pos,tt=U.$trigger;if(!(!z||!gt)){if(q!=null&&q!==window.location.hash){var cn=gt.updateURL;e&&r&&cn!==!1&&window.history[cn==="replace"?"replaceState":"pushState"](null,"",q)}this.unbind(!1,!0),U.opts=null,U.$trigger=null,be?this.hook(gt,"cancel"):this.hook(gt,"after",mt,tt),this.hook(gt,"complete",be)}},L.prototype.hook=function(_,z){for(var U=[],q=2;q<arguments.length;q++)U[q-2]=arguments[q];var be,gt=_[z],mt,tt;return s(gt)&&(mt=gt.apply(this,U.concat([this]))),tt=(be=this)["on"+(z[0].toUpperCase()+z.slice(1))].apply(be,U),mt!==void 0?mt:tt},L.prototype.bind=function(_,z){var U=this,q=U.$el,be=U.ctx.opts;q&&(_&&fe(q,yt,this.handleClick,!1),z&&fe(q,Yt,this.handleStop,be?be.cancellable:!0))},L.prototype.unbind=function(_,z){var U=this,q=U.$el,be=U.ctx.opts;q&&(_&&E(q,yt,this.handleClick,!1),z&&E(q,Yt,this.handleStop,be?be.cancellable:!0))},L.raf=u,L.caf=f,L})();return Nn})});function x(t){if(!t)throw new Error("Assertion failed.")}var Ha,Ze,El,Z,$s,bz,qe,ge,br,lt,Va,_P,ji,Cl,qi,Pl,Yi,Il,kx,jf,Tn,AP,FP,_o,ze,LP,ut,STt,BP,qf,wz,xz,kt,_l,kz,Dl,Sz,Tz,Zm,Ht,Ft,Do,ep,Sx,vz,uee,Mo,Hs,zP,gz,UP,Ez,$a,DP,Wa,MP,Vs,OP,tp,RP,Cz,Ml,Tx,Gi,Pz,Iz,_z,Dz,vx,ja,qa,$P,Jm,yz,bx,NP,wx,fee,xx,TTt,vTt,Mz,Oz,Ue=he(()=>{o(x,"assert");Ha=o(t=>{let e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},"normalizeRotation"),Ze=o(t=>t&&t[t.length-1],"last"),El=o(t=>t>=0&&t<2**32,"isU32"),Z=o(t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},"readExpGolomb"),$s=o(t=>{let e=Z(t);return(e&1)===0?-(e>>1):e+1>>1},"readSignedExpGolomb"),bz=o((t,e,r,n)=>{for(let i=e;i<r;i++){let s=Math.floor(i/8),a=t[s],c=7-(i&7);a&=~(1<<c),a|=(n&1<<r-i-1)>>r-i-1<<c,t[s]=a}},"writeBits"),qe=o(t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),"toUint8Array"),ge=o(t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),"toDataView"),br=new TextDecoder,lt=new TextEncoder,Va=o(t=>{for(let e=0;e<t.length;e++)if(t.charCodeAt(e)>255)return!1;return!0},"isIso88591Compatible"),_P=o(t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),"invertObject"),ji={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Cl=_P(ji),qi={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Pl=_P(qi),Yi={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Il=_P(Yi),kx=o(t=>!!t&&!!t.primaries&&!!t.transfer&&!!t.matrix&&t.fullRange!==void 0,"colorSpaceIsComplete"),jf=o(t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),"isAllowSharedBufferSource"),Tn=class{static{o(this,"AsyncMutex")}constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,r=new Promise(i=>{let s=!1;e=o(()=>{s||(i(),this.pending--,s=!0)},"resolver")}),n=this.currentPromise;return this.currentPromise=r,this.pending++,await n,e}},AP=o(t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),"bytesToHexString"),FP=o(t=>(t=t>>1&1431655765|(t&1431655765)<<1,t=t>>2&858993459|(t&858993459)<<2,t=t>>4&252645135|(t&252645135)<<4,t=t>>8&16711935|(t&16711935)<<8,t=t>>16&65535|(t&65535)<<16,t>>>0),"reverseBitsU32"),_o=o((t,e,r)=>{let n=0,i=t.length-1,s=-1;for(;n<=i;){let a=n+i>>1,c=r(t[a]);c===e?(s=a,i=a-1):c<e?n=a+1:i=a-1}return s},"binarySearchExact"),ze=o((t,e,r)=>{let n=0,i=t.length-1,s=-1;for(;n<=i;){let a=n+(i-n+1)/2|0;r(t[a])<=e?(s=a,n=a+1):i=a-1}return s},"binarySearchLessOrEqual"),LP=o((t,e,r)=>{let n=ze(t,r(e),r);t.splice(n+1,0,e)},"insertSorted"),ut=o(()=>{let t,e;return{promise:new Promise((n,i)=>{t=n,e=i}),resolve:t,reject:e}},"promiseWithResolvers"),STt=o((t,e)=>{let r=t.indexOf(e);r!==-1&&t.splice(r,1)},"removeItem"),BP=o((t,e)=>{for(let r=t.length-1;r>=0;r--)if(e(t[r]))return t[r]},"findLast"),qf=o((t,e)=>{for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1},"findLastIndex"),wz=o(async function*(t){Symbol.iterator in t?yield*t[Symbol.iterator]():yield*t[Symbol.asyncIterator]()},"toAsyncIterator"),xz=o(t=>{if(!(Symbol.iterator in t)&&!(Symbol.asyncIterator in t))throw new TypeError("Argument must be an iterable or async iterable.")},"validateAnyIterable"),kt=o(t=>{throw new Error(`Unexpected value: ${t}`)},"assertNever"),_l=o((t,e,r)=>{let n=t.getUint8(e),i=t.getUint8(e+1),s=t.getUint8(e+2);return r?n|i<<8|s<<16:n<<16|i<<8|s},"getUint24"),kz=o((t,e,r)=>_l(t,e,r)<<8>>8,"getInt24"),Dl=o((t,e,r,n)=>{r=r>>>0,r=r&16777215,n?(t.setUint8(e,r&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r>>>16&255)):(t.setUint8(e,r>>>16&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r&255))},"setUint24"),Sz=o((t,e,r,n)=>{r=Ht(r,-8388608,8388607),r<0&&(r=r+16777216&16777215),Dl(t,e,r,n)},"setInt24"),Tz=o((t,e,r,n)=>{n?(t.setUint32(e+0,r,!0),t.setInt32(e+4,Math.floor(r/2**32),!0)):(t.setInt32(e+0,Math.floor(r/2**32),!0),t.setUint32(e+4,r,!0))},"setInt64"),Zm=o((t,e)=>({async next(){let r=await t.next();return r.done?{value:void 0,done:!0}:{value:e(r.value),done:!1}},return(){return t.return()},throw(r){return t.throw(r)},[Symbol.asyncIterator](){return this}}),"mapAsyncGenerator"),Ht=o((t,e,r)=>Math.max(e,Math.min(r,t)),"clamp"),Ft="und",Do=o(t=>{let e=Math.round(t);return Math.abs(t/e-1)<10*Number.EPSILON?e:t},"roundIfAlmostInteger"),ep=o((t,e)=>Math.round(t/e)*e,"roundToMultiple"),Sx=o((t,e)=>Math.floor(t/e)*e,"floorToMultiple"),vz=o(t=>{let e=0;for(;t;)e++,t>>=1;return e},"ilog"),uee=/^[a-z]{3}$/,Mo=o(t=>uee.test(t),"isIso639Dash2LanguageCode"),Hs=1e6*(1+Number.EPSILON),zP=o((t,e)=>{let r={...t,...e};if(t.headers||e.headers){let n=t.headers?gz(t.headers):{},i=e.headers?gz(e.headers):{},s={...n};Object.entries(i).forEach(([a,c])=>{let l=Object.keys(s).find(u=>u.toLowerCase()===a.toLowerCase());l&&delete s[l],s[a]=c}),r.headers=s}return r},"mergeRequestInit"),gz=o(t=>{if(t instanceof Headers){let e={};return t.forEach((r,n)=>{e[n]=r}),e}if(Array.isArray(t)){let e={};return t.forEach(([r,n])=>{e[r]=n}),e}return t},"normalizeHeaders"),UP=o(async(t,e,r,n,i)=>{let s=0;for(;;)try{return await t(e,r)}catch(a){if(i())throw a;s++;let c=n(s,a,e);if(c===null)throw a;if(console.error("Retrying failed fetch. Error:",a),!Number.isFinite(c)||c<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(c>0&&await new Promise(l=>setTimeout(l,1e3*c)),i())throw a}},"retriedFetch"),Ez=o((t,e)=>{let r=t<0?-1:1;t=Math.abs(t);let n=0,i=1,s=1,a=0,c=t;for(;;){let l=Math.floor(c),u=l*s+n,f=l*a+i;if(f>e)return{numerator:r*s,denominator:a};if(n=s,i=a,s=u,a=f,c=1/(c-l),!isFinite(c))break}return{numerator:r*s,denominator:a}},"computeRationalApproximation"),$a=class{static{o(this,"CallSerializer")}constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},DP=null,Wa=o(()=>DP!==null?DP:DP=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),"isWebKit"),MP=null,Vs=o(()=>MP!==null?MP:MP=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),"isFirefox"),OP=null,tp=o(()=>OP!==null?OP:OP=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),"isChromium"),RP=null,Cz=o(()=>{if(RP!==null)return RP;if(typeof navigator>"u")return null;let t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?RP=Number(t[1]):null},"getChromiumVersion"),Ml=o((t,e)=>t!==-1?t:e,"coalesceIndex"),Tx=o((t,e,r,n)=>t<=n&&r<=e,"closedIntervalsOverlap"),Gi=o(function*(t){for(let e in t){let r=t[e];r!==void 0&&(yield{key:e,value:r})}},"keyValueIterator"),Pz=o(t=>{switch(t.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},"imageMimeTypeToExtension"),Iz=o(t=>{let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r},"base64ToBytes"),_z=o(t=>{let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)},"bytesToBase64"),Dz=o((t,e)=>{if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0},"uint8ArraysAreEqual"),vx=o(()=>{Symbol.dispose??=Symbol("Symbol.dispose")},"polyfillSymbolDispose"),ja=o(t=>typeof t=="number"&&!Number.isNaN(t),"isNumber"),qa=o(t=>{x(t.den!==0);let e=Math.abs(t.num),r=Math.abs(t.den);for(;r!==0;){let i=e%r;e=r,r=i}let n=e||1;return{num:t.num/n,den:t.den/n}},"simplifyRational"),$P=o((t,e)=>{if(typeof t!="object"||!t)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)},"validateRectangle"),yz=1,bx=new Map,NP=new Map,wx=o(()=>typeof window>"u","shouldUseNativeTimers"),fee=o(()=>{let t=new Map,e=new Map;self.onmessage=r=>{let n=r.data;switch(n.type){case"set-timeout":{let i=setTimeout(()=>{t.delete(n.timerId),self.postMessage({type:"fire",timerId:n.timerId})},n.delay);t.set(n.timerId,i)}break;case"set-interval":{let i=setInterval(()=>{self.postMessage({type:"fire",timerId:n.timerId})},n.delay);e.set(n.timerId,i)}break;case"clear-timeout":{let i=t.get(n.timerId);i!==void 0&&(clearTimeout(i),t.delete(n.timerId))}break;case"clear-interval":{let i=e.get(n.timerId);i!==void 0&&(clearInterval(i),e.delete(n.timerId))}break}}},"unthrottledTimerWorkerMain"),xx=o(()=>{if(Jm)return Jm;let t=`(${fee.toString()})();`,e=URL.createObjectURL(new Blob([t],{type:"text/javascript"}));return Jm=new Worker(e),URL.revokeObjectURL(e),Jm.onmessage=r=>{let n=r.data,i=bx.get(n.timerId);if(i){bx.delete(n.timerId),i();return}let s=NP.get(n.timerId);s&&s()},Jm},"getUnthrottledTimerWorker"),TTt=o((t,e)=>{if(wx())return{id:setTimeout(t,e)};let r=yz++;return bx.set(r,()=>{t()}),xx().postMessage({type:"set-timeout",timerId:r,delay:e}),{id:r}},"setTimeoutUnthrottled"),vTt=o(t=>{if(wx()){clearTimeout(t.id);return}x(typeof t.id=="number"),bx.delete(t.id),xx().postMessage({type:"clear-timeout",timerId:t.id})},"clearTimeoutUnthrottled"),Mz=o((t,e)=>{if(wx())return{id:setInterval(t,e)};let r=yz++;return NP.set(r,()=>{t()}),xx().postMessage({type:"set-interval",timerId:r,delay:e}),{id:r}},"setIntervalUnthrottled"),Oz=o(t=>{if(wx()){clearInterval(t.id);return}x(typeof t.id=="number"),NP.delete(t.id),xx().postMessage({type:"clear-interval",timerId:t.id})},"clearIntervalUnthrottled")});var Gn,Oo,rp,Ro,jr,Rz,lr=he(()=>{Gn=class{static{o(this,"RichImageData")}constructor(e,r){if(this.data=e,this.mimeType=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof r!="string")throw new TypeError("mimeType must be a string.")}},Oo=class{static{o(this,"AttachedFile")}constructor(e,r,n,i){if(this.data=e,this.mimeType=r,this.name=n,this.description=i,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!==void 0&&typeof r!="string")throw new TypeError("mimeType, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("name, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("description, when provided, must be a string.")}},rp=o(t=>{if(!t||typeof t!="object")throw new TypeError("tags must be an object.");if(t.title!==void 0&&typeof t.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(t.artist!==void 0&&typeof t.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(t.album!==void 0&&typeof t.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(t.albumArtist!==void 0&&typeof t.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(t.trackNumber!==void 0&&(!Number.isInteger(t.trackNumber)||t.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(t.tracksTotal!==void 0&&(!Number.isInteger(t.tracksTotal)||t.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(t.discNumber!==void 0&&(!Number.isInteger(t.discNumber)||t.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(t.discsTotal!==void 0&&(!Number.isInteger(t.discsTotal)||t.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(t.genre!==void 0&&typeof t.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(t.date!==void 0&&(!(t.date instanceof Date)||Number.isNaN(t.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(t.lyrics!==void 0&&typeof t.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(t.images!==void 0){if(!Array.isArray(t.images))throw new TypeError("tags.images, when provided, must be an array.");for(let e of t.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(t.comment!==void 0&&typeof t.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(t.raw!==void 0){if(!t.raw||typeof t.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(let e of Object.values(t.raw))if(e!==null&&typeof e!="string"&&!(e instanceof Uint8Array)&&!(e instanceof Gn)&&!(e instanceof Oo))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}},"validateMetadataTags"),Ro=o(t=>t.title===void 0&&t.description===void 0&&t.artist===void 0&&t.album===void 0&&t.albumArtist===void 0&&t.trackNumber===void 0&&t.tracksTotal===void 0&&t.discNumber===void 0&&t.discsTotal===void 0&&t.genre===void 0&&t.date===void 0&&t.lyrics===void 0&&(!t.images||t.images.length===0)&&t.comment===void 0&&(t.raw===void 0||Object.keys(t.raw).length===0),"metadataTagsAreEmpty"),jr={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},Rz=o(t=>{if(!t||typeof t!="object")throw new TypeError("disposition must be an object.");if(t.default!==void 0&&typeof t.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(t.forced!==void 0&&typeof t.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(t.original!==void 0&&typeof t.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(t.commentary!==void 0&&typeof t.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(t.hearingImpaired!==void 0&&typeof t.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(t.visuallyImpaired!==void 0&&typeof t.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")},"validateTrackDisposition")});var Te,Ti=he(()=>{Te=class t{static{o(this,"Bitstream")}constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),r=this.bytes[e]??0,n=7-(this.pos&7),i=(r&1<<n)>>n;return this.pos++,i}readBits(e){if(e===1)return this.readBit();let r=0;for(let n=0;n<e;n++)r<<=1,r|=this.readBit();return r}writeBits(e,r){let n=this.pos+e;for(let i=this.pos;i<n;i++){let s=Math.floor(i/8),a=this.bytes[s],c=7-(i&7);a&=~(1<<c),a|=(r&1<<n-i-1)>>n-i-1<<c,this.bytes[s]=a}this.pos=n}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,r=this.bytes[e]??0;return this.pos+=8,r}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new t(this.bytes);return e.pos=this.pos,e}}});var vi,Ws,js,Yf,Ex,Cx,qs=he(()=>{Ti();vi=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Ws=[-1,1,2,3,4,5,6,8],js=o(t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new Te(t),r=e.readBits(5);r===31&&(r=32+e.readBits(6));let n=e.readBits(4),i=null;n===15?i=e.readBits(24):n<vi.length&&(i=vi[n]);let s=e.readBits(4),a=null;return s>=1&&s<=7&&(a=Ws[s]),{objectType:r,frequencyIndex:n,sampleRate:i,channelConfiguration:s,numberOfChannels:a}},"parseAacAudioSpecificConfig"),Yf=o(t=>{let e=vi.indexOf(t.sampleRate),r=null;e===-1&&(e=15,r=t.sampleRate);let n=Ws.indexOf(t.numberOfChannels);if(n===-1)throw new TypeError(`Unsupported number of channels: ${t.numberOfChannels}`);let i=13;t.objectType>=32&&(i+=6),e===15&&(i+=24);let s=Math.ceil(i/8),a=new Uint8Array(s),c=new Te(a);return t.objectType<32?c.writeBits(5,t.objectType):(c.writeBits(5,31),c.writeBits(6,t.objectType-32)),c.writeBits(4,e),e===15&&c.writeBits(24,r),c.writeBits(4,n),a},"buildAacAudioSpecificConfig"),Ex=o(t=>{let e=new Uint8Array(7),r=new Te(e),{objectType:n,frequencyIndex:i,channelConfiguration:s}=t,a=n-1;return r.writeBits(12,4095),r.writeBits(1,0),r.writeBits(2,0),r.writeBits(1,1),r.writeBits(2,a),r.writeBits(4,i),r.writeBits(1,0),r.writeBits(3,s),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.skipBits(13),r.writeBits(11,2047),r.writeBits(2,0),{header:e,bitstream:r}},"buildAdtsHeaderTemplate"),Cx=o((t,e)=>{t.pos=30,t.writeBits(13,e)},"writeAdtsFrameLength")});var Vt,ht,Ys,Jt,vn,np,Nz,No,Az,Fz,Lz,zz,Uz,Px,Gf,$z,Qf,Qi,Bz,_r,HP,Hz,Vz,dee,hee,mee,pee,gee,Kf,yee,En,Ix,Zt=he(()=>{qs();Ue();Vt=["avc","hevc","vp9","av1","vp8"],ht=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],Ys=["aac","opus","mp3","vorbis","flac","ac3","eac3"],Jt=[...Ys,...ht],vn=["webvtt"],np=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],Nz=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],No=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],Az=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],Fz=".01.01.01.01.00",Lz=".0.110.01.01.01.0",zz=o((t,e,r,n)=>{if(t==="avc"){let s=Math.ceil(e/16)*Math.ceil(r/16),a=np.find(d=>s<=d.maxMacroblocks&&n<=d.maxBitrate)??Ze(np),c=a?a.level:0,l="64".padStart(2,"0"),u="00",f=c.toString(16).padStart(2,"0");return`avc1.${l}${u}${f}`}else if(t==="hevc"){let c=e*r,l=Nz.find(f=>c<=f.maxPictureSize&&n<=f.maxBitrate)??Ze(Nz);return`hev1.1.6.${l.tier}${l.level}.B0`}else{if(t==="vp8")return"vp8";if(t==="vp9"){let s=e*r;return`vp09.00.${(No.find(l=>s<=l.maxPictureSize&&n<=l.maxBitrate)??Ze(No)).level.toString().padStart(2,"0")}.08`}else if(t==="av1"){let s=e*r,a=Az.find(u=>s<=u.maxPictureSize&&n<=u.maxBitrate)??Ze(Az);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}}throw new TypeError(`Unhandled codec '${t}'.`)},"buildVideoCodecString"),Uz=o(t=>{let e=t.split("."),r=Number(e[1]),n=Number(e[2]),i=Number(e[3]),s=e[4]?Number(e[4]):1;return[1,1,r,2,1,n,3,1,i,4,1,s]},"generateVp9CodecConfigurationFromCodecString"),Px=o(t=>{let e=t.split("."),i=(1<<7)+1,s=Number(e[1]),a=e[2],c=Number(a.slice(0,-1)),l=(s<<5)+c,u=a.slice(-1)==="H"?1:0,d=Number(e[3])===8?0:1,h=0,m=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,g=e[5]?Number(e[5][1]):1,y=e[5]?Number(e[5][2]):0,b=(u<<7)+(d<<6)+(h<<5)+(m<<4)+(p<<3)+(g<<2)+y;return[i,l,b,0]},"generateAv1CodecConfigurationFromCodecString"),Gf=o(t=>{let{codec:e,codecDescription:r,colorSpace:n,avcCodecInfo:i,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:c}=t;if(e==="avc"){if(x(t.avcType!==null),i){let l=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${t.avcType}.${AP(l)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${AP(r.subarray(1,4))}`}else if(e==="hevc"){let l,u,f,d,h,m;if(s)l=s.generalProfileSpace,u=s.generalProfileIdc,f=FP(s.generalProfileCompatibilityFlags),d=s.generalTierFlag,h=s.generalLevelIdc,m=[...s.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let g=ge(r),y=g.getUint8(1);l=y>>6&3,u=y&31,f=FP(g.getUint32(2)),d=y>>5&1,h=g.getUint8(12),m=[];for(let b=0;b<6;b++)m.push(g.getUint8(6+b))}let p="hev1.";for(p+=["","A","B","C"][l]+u,p+=".",p+=f.toString(16).toUpperCase(),p+=".",p+=d===0?"L":"H",p+=h;m.length>0&&m[m.length-1]===0;)m.pop();return m.length>0&&(p+=".",p+=m.map(g=>g.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){let b=t.width*t.height,w=Ze(No).level;for(let k of No)if(b<=k.maxPictureSize){w=k.level;break}return`vp09.00.${w.toString().padStart(2,"0")}.08`}let l=a.profile.toString().padStart(2,"0"),u=a.level.toString().padStart(2,"0"),f=a.bitDepth.toString().padStart(2,"0"),d=a.chromaSubsampling.toString().padStart(2,"0"),h=a.colourPrimaries.toString().padStart(2,"0"),m=a.transferCharacteristics.toString().padStart(2,"0"),p=a.matrixCoefficients.toString().padStart(2,"0"),g=a.videoFullRangeFlag.toString().padStart(2,"0"),y=`vp09.${l}.${u}.${f}.${d}`;return y+=`.${h}.${m}.${p}.${g}`,y.endsWith(Fz)&&(y=y.slice(0,-Fz.length)),y}else if(e==="av1"){if(!c){let k=t.width*t.height,T=Ze(No).level;for(let v of No)if(k<=v.maxPictureSize){T=v.level;break}return`av01.0.${T.toString().padStart(2,"0")}M.08`}let l=c.profile,u=c.level.toString().padStart(2,"0"),f=c.tier?"H":"M",d=c.bitDepth.toString().padStart(2,"0"),h=c.monochrome?"1":"0",m=100*c.chromaSubsamplingX+10*c.chromaSubsamplingY+1*(c.chromaSubsamplingX&&c.chromaSubsamplingY?c.chromaSamplePosition:0),p=n?.primaries?ji[n.primaries]:1,g=n?.transfer?qi[n.transfer]:1,y=n?.matrix?Yi[n.matrix]:1,b=n?.fullRange?1:0,w=`av01.${l}.${u}${f}.${d}`;return w+=`.${h}.${m.toString().padStart(3,"0")}`,w+=`.${p.toString().padStart(2,"0")}`,w+=`.${g.toString().padStart(2,"0")}`,w+=`.${y.toString().padStart(2,"0")}`,w+=`.${b}`,w.endsWith(Lz)&&(w=w.slice(0,-Lz.length)),w}}throw new TypeError(`Unhandled codec '${e}'.`)},"extractVideoCodecString"),$z=o((t,e,r)=>{if(t==="aac")return e>=2&&r<=24e3?"mp4a.40.29":r<=24e3?"mp4a.40.5":"mp4a.40.2";if(t==="mp3")return"mp3";if(t==="opus")return"opus";if(t==="vorbis")return"vorbis";if(t==="flac")return"flac";if(t==="ac3")return"ac-3";if(t==="eac3")return"ec-3";if(ht.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},"buildAudioCodecString"),Qf=o(t=>{let{codec:e,codecDescription:r,aacCodecInfo:n}=t;if(e==="aac"){if(!n)throw new TypeError("AAC codec info must be provided.");if(n.isMpeg2)return"mp4a.67";{let i;return n.objectType!==null?i=n.objectType:i=js(r).objectType,`mp4a.40.${i}`}}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e==="ac3")return"ac-3";if(e==="eac3")return"ec-3";if(e&&ht.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},"extractAudioCodecString"),Qi=48e3,Bz=/^pcm-([usf])(\d+)+(be)?$/,_r=o(t=>{if(x(ht.includes(t)),t==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(t==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=Bz.exec(t);x(e);let r;e[1]==="u"?r="unsigned":e[1]==="s"?r="signed":r="float";let n=Number(e[2])/8,i=e[3]!=="be",s=t==="pcm-u8"?2**7:0;return{dataType:r,sampleSize:n,littleEndian:i,silentValue:s}},"parsePcmCodec"),HP=o(t=>t.startsWith("avc1")||t.startsWith("avc3")?"avc":t.startsWith("hev1")||t.startsWith("hvc1")?"hevc":t==="vp8"?"vp8":t.startsWith("vp09")?"vp9":t.startsWith("av01")?"av1":t.startsWith("mp4a.40")||t==="mp4a.67"?"aac":t==="mp3"||t==="mp4a.69"||t==="mp4a.6B"||t==="mp4a.6b"?"mp3":t==="opus"?"opus":t==="vorbis"?"vorbis":t==="flac"?"flac":t==="ac-3"||t==="ac3"?"ac3":t==="ec-3"||t==="eac3"?"eac3":t==="ulaw"?"ulaw":t==="alaw"?"alaw":Bz.test(t)?t:t==="webvtt"?"webvtt":null,"inferCodecFromCodecString"),Hz=o(t=>t==="avc"?{avc:{format:"avc"}}:t==="hevc"?{hevc:{format:"hevc"}}:{},"getVideoEncoderConfigExtension"),Vz=o(t=>t==="aac"?{aac:{format:"aac"}}:t==="opus"?{opus:{format:"opus"}}:{},"getAudioEncoderConfigExtension"),dee=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],hee=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,mee=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,pee=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,gee=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Kf=o(t=>{if(!t)throw new TypeError("Video chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Video chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!dee.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(t.decoderConfig.codedWidth)||t.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(t.decoderConfig.codedHeight)||t.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(t.decoderConfig.description!==void 0&&!jf(t.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.colorSpace!==void 0){let{colorSpace:e}=t.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let r=Object.keys(ji);if(e.primaries!=null&&!r.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);let n=Object.keys(qi);if(e.transfer!=null&&!n.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${n.join(", ")}.`);let i=Object.keys(Yi);if(e.matrix!=null&&!i.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(t.decoderConfig.codec.startsWith("avc1")||t.decoderConfig.codec.startsWith("avc3")){if(!hee.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(t.decoderConfig.codec.startsWith("hev1")||t.decoderConfig.codec.startsWith("hvc1")){if(!mee.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(t.decoderConfig.codec.startsWith("vp8")){if(t.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(t.decoderConfig.codec.startsWith("vp09")){if(!pee.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(t.decoderConfig.codec.startsWith("av01")&&!gee.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},"validateVideoChunkMetadata"),yee=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],En=o(t=>{if(!t)throw new TypeError("Audio chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!yee.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(t.decoderConfig.sampleRate)||t.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(t.decoderConfig.numberOfChannels)||t.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(t.decoderConfig.description!==void 0&&!jf(t.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.codec.startsWith("mp4a")&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(t.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("mp3")||t.decoderConfig.codec.startsWith("mp4a")){if(t.decoderConfig.codec!=="mp3"&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(t.decoderConfig.codec.startsWith("opus")){if(t.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(t.decoderConfig.description&&t.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(t.decoderConfig.codec.startsWith("vorbis")){if(t.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("flac")){if(t.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("ac-3")||t.decoderConfig.codec.startsWith("ac3")){if(t.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(t.decoderConfig.codec.startsWith("ec-3")||t.decoderConfig.codec.startsWith("eac3")){if(t.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!ht.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${ht.join(", ")}).`)},"validateAudioChunkMetadata"),Ix=o(t=>{if(!t)throw new TypeError("Subtitle metadata must be provided.");if(typeof t!="object")throw new TypeError("Subtitle metadata must be an object.");if(!t.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof t.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof t.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")},"validateSubtitleMetadata")});var Ya,bee,_x,Ga,Xf,Dx,Qa,Ol,Wz,Mx,Ka=he(()=>{Ya=4,bee=[44100,48e3,32e3],_x=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],Ga=1483304551,Xf=1231971951,Dx=o((t,e,r,n,i)=>e===0?0:e===1?Math.floor(144*r/(n<<t))+i:e===2?Math.floor(144*r/n)+i:(Math.floor(12*r/n)+i)*4,"computeMp3FrameSize"),Qa=o((t,e)=>t===3?e===3?21:36:e===3?13:21,"getXingOffset"),Ol=o((t,e)=>{let r=t>>>24,n=t>>>16&255,i=t>>>8&255,s=t&255;if(r!==255&&n!==255&&i!==255&&s!==255)return{header:null,bytesAdvanced:4};if(r!==255)return{header:null,bytesAdvanced:1};if((n&224)!==224)return{header:null,bytesAdvanced:1};let a=0,c=0;n&16?a=n&8?0:1:(a=1,c=1);let l=n>>3&3,u=n>>1&3,f=i>>4&15,d=(i>>2&3)%3,h=i>>1&1,m=s>>6&3,p=s>>4&3,g=s>>3&1,y=s>>2&1,b=s&3,w=_x[a*16*4+u*16+f];if(w===-1)return{header:null,bytesAdvanced:1};let k=w*1e3,T=bee[d]>>a+c,v=Dx(a,u,k,T,h);if(e!==null&&e<v)return{header:null,bytesAdvanced:1};let S;return l===3?S=u===3?384:1152:u===3?S=384:u===2?S=1152:S=576,{header:{totalSize:v,mpegVersionId:l,layer:u,bitrate:k,frequencyIndex:d,sampleRate:T,channel:m,modeExtension:p,copyright:g,original:y,emphasis:b,audioSamplesInFrame:S},bytesAdvanced:1}},"readMp3FrameHeader"),Wz=o(t=>{let e=127,r=0,n=t;for(;(e^2147483647)!==0;)r=n&~e,r<<=1,r|=n&e,e=(e+1<<8)-1,n=r;return r},"encodeSynchsafe"),Mx=o(t=>{let e=2130706432,r=0;for(;e!==0;)r>>=1,r|=t&e,e>>=8;return r},"decodeSynchsafe")});var Rl,VP,Ox=he(()=>{Rl=[48e3,44100,32e3],VP=[24e3,22050,16e3]});var Cn,vt,Xa,Nx,jP,Ao,Rx,WP,Ax,qP,Qz,Jf,Kz,Fx,jz,ip,qz,YP,Gs,GP,Zf,wee,xee,kee,See,Tee,vee,Yz,Xz,Jz,Lx,Gz,Bx,Ja,Eee,Zz,zx,Ux,Ei,sp,op,ap,$x,eU,tU,cp,lp,QP,Hx,rU,Vx,Wx,sn=he(()=>{Zt();Ue();Ox();Ti();(function(t){t[t.NON_IDR_SLICE=1]="NON_IDR_SLICE",t[t.SLICE_DPA=2]="SLICE_DPA",t[t.SLICE_DPB=3]="SLICE_DPB",t[t.SLICE_DPC=4]="SLICE_DPC",t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.AUD=9]="AUD",t[t.SPS_EXT=13]="SPS_EXT"})(Cn||(Cn={}));(function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.AUD_NUT=35]="AUD_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(vt||(vt={}));Xa=o(function*(t){let e=0,r=-1;for(;e<t.length-2;){let n=t.indexOf(0,e);if(n===-1||n>=t.length-2)break;e=n;let i=0;if(e+3<t.length&&t[e+1]===0&&t[e+2]===0&&t[e+3]===1?i=4:t[e+1]===0&&t[e+2]===1&&(i=3),i===0){e++;continue}r!==-1&&e>r&&(yield{offset:r,length:e-r}),r=e+i,e=r}r!==-1&&r<t.length&&(yield{offset:r,length:t.length-r})},"iterateNalUnitsInAnnexB"),Nx=o(function*(t,e){let r=0,n=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;r+e<=t.length;){let i;e===1?i=n.getUint8(r):e===2?i=n.getUint16(r,!1):e===3?i=_l(n,r,!1):(x(e===4),i=n.getUint32(r,!1)),r+=e,yield{offset:r,length:i},r+=i}},"iterateNalUnitsInLengthPrefixed"),jP=o((t,e)=>{if(e.description){let i=(qe(e.description)[4]&3)+1;return Nx(t,i)}else return Xa(t)},"iterateAvcNalUnits"),Ao=o(t=>t&31,"extractNalUnitTypeForAvc"),Rx=o(t=>{let e=[],r=t.length;for(let n=0;n<r;n++)n+2<r&&t[n]===0&&t[n+1]===0&&t[n+2]===3?(e.push(0,0),n+=2):e.push(t[n]);return new Uint8Array(e)},"removeEmulationPreventionBytes"),WP=new Uint8Array([0,0,0,1]),Ax=o(t=>{let e=t.reduce((i,s)=>i+WP.byteLength+s.byteLength,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(WP,n),n+=WP.byteLength,r.set(i,n),n+=i.byteLength;return r},"concatNalUnitsInAnnexB"),qP=o((t,e)=>{let r=t.reduce((s,a)=>s+e+a.byteLength,0),n=new Uint8Array(r),i=0;for(let s of t){let a=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(e){case 1:a.setUint8(i,s.byteLength);break;case 2:a.setUint16(i,s.byteLength,!1);break;case 3:Dl(a,i,s.byteLength,!1);break;case 4:a.setUint32(i,s.byteLength,!1);break}i+=e,n.set(s,i),i+=s.byteLength}return n},"concatNalUnitsInLengthPrefixed"),Qz=o((t,e)=>{if(e.description){let i=(qe(e.description)[4]&3)+1;return qP(t,i)}else return Ax(t)},"concatAvcNalUnits"),Jf=o(t=>{try{let e=[],r=[],n=[];for(let c of Xa(t)){let l=t.subarray(c.offset,c.offset+c.length),u=Ao(l[0]);u===Cn.SPS?e.push(l):u===Cn.PPS?r.push(l):u===Cn.SPS_EXT&&n.push(l)}if(e.length===0||r.length===0)return null;let i=e[0],s=ip(i);x(s!==null);let a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:r,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?n:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},"extractAvcDecoderConfigurationRecord"),Kz=o(t=>{let e=[];e.push(t.configurationVersion),e.push(t.avcProfileIndication),e.push(t.profileCompatibility),e.push(t.avcLevelIndication),e.push(252|t.lengthSizeMinusOne&3),e.push(224|t.sequenceParameterSets.length&31);for(let r of t.sequenceParameterSets){let n=r.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(r[i])}e.push(t.pictureParameterSets.length);for(let r of t.pictureParameterSets){let n=r.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(r[i])}if(t.avcProfileIndication===100||t.avcProfileIndication===110||t.avcProfileIndication===122||t.avcProfileIndication===144){x(t.chromaFormat!==null),x(t.bitDepthLumaMinus8!==null),x(t.bitDepthChromaMinus8!==null),x(t.sequenceParameterSetExt!==null),e.push(252|t.chromaFormat&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.sequenceParameterSetExt.length);for(let r of t.sequenceParameterSetExt){let n=r.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(r[i])}}return new Uint8Array(e)},"serializeAvcDecoderConfigurationRecord"),Fx=o(t=>{try{let e=ge(t),r=0,n=e.getUint8(r++),i=e.getUint8(r++),s=e.getUint8(r++),a=e.getUint8(r++),c=e.getUint8(r++)&3,l=e.getUint8(r++)&31,u=[];for(let m=0;m<l;m++){let p=e.getUint16(r,!1);r+=2,u.push(t.subarray(r,r+p)),r+=p}let f=e.getUint8(r++),d=[];for(let m=0;m<f;m++){let p=e.getUint16(r,!1);r+=2,d.push(t.subarray(r,r+p)),r+=p}let h={configurationVersion:n,avcProfileIndication:i,profileCompatibility:s,avcLevelIndication:a,lengthSizeMinusOne:c,sequenceParameterSets:u,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&r+4<=t.length){let m=e.getUint8(r++)&3,p=e.getUint8(r++)&7,g=e.getUint8(r++)&7,y=e.getUint8(r++);h.chromaFormat=m,h.bitDepthLumaMinus8=p,h.bitDepthChromaMinus8=g;let b=[];for(let w=0;w<y;w++){let k=e.getUint16(r,!1);r+=2,b.push(t.subarray(r,r+k)),r+=k}h.sequenceParameterSetExt=b}return h}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},"deserializeAvcDecoderConfigurationRecord"),jz={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},ip=o(t=>{try{let e=new Te(Rx(t));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let n=e.readAlignedByte(),i=e.readAlignedByte(),s=e.readAlignedByte();Z(e);let a=1,c=0,l=0,u=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(a=Z(e),a===3&&(u=e.readBits(1)),c=Z(e),l=Z(e),e.skipBits(1),e.readBits(1))){for(let A=0;A<(a!==3?8:12);A++)if(e.readBits(1)){let F=A<6?16:64,$=8,W=8;for(let Q=0;Q<F;Q++){if(W!==0){let re=$s(e);W=($+re+256)%256}$=W===0?$:W}}}Z(e);let f=Z(e);if(f===0)Z(e);else if(f===1){e.skipBits(1),$s(e),$s(e);let Y=Z(e);for(let A=0;A<Y;A++)$s(e)}Z(e),e.skipBits(1);let d=Z(e),h=Z(e),m=16*(d+1),p=16*(h+1),g=m,y=p,b=e.readBits(1);if(b||e.skipBits(1),e.skipBits(1),e.readBits(1)){let Y=Z(e),A=Z(e),R=Z(e),F=Z(e),$,W;if((u===0?a:0)===0)$=1,W=2-b;else{let re=a===3?1:2,fe=a===1?2:1;$=re,W=fe*(2-b)}g-=$*(Y+A),y-=W*(R+F)}let k=2,T=2,v=2,S=0,M={num:1,den:1},P=null,N=null;if(e.readBits(1)){if(e.readBits(1)){let fe=e.readBits(8);if(fe===255)M={num:e.readBits(16),den:e.readBits(16)};else{let E=jz[fe];E&&(M=E)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),S=e.readBits(1),e.readBits(1)&&(k=e.readBits(8),T=e.readBits(8),v=e.readBits(8))),e.readBits(1)&&(Z(e),Z(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));let W=e.readBits(1);W&&qz(e);let Q=e.readBits(1);Q&&qz(e),(W||Q)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),Z(e),Z(e),Z(e),Z(e),P=Z(e),N=Z(e))}if(P===null){x(N===null);let Y=i&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&Y)P=0,N=0;else{let A=d+1,R=h+1,F=(2-b)*R,$=np.find(Q=>Q.level>=s)??Ze(np),W=Math.min(Math.floor($.maxDpbMbs/(A*F)),16);P=W,N=W}}return x(N!==null),{profileIdc:n,constraintFlags:i,levelIdc:s,frameMbsOnlyFlag:b,chromaFormatIdc:a,bitDepthLumaMinus8:c,bitDepthChromaMinus8:l,codedWidth:m,codedHeight:p,displayWidth:g,displayHeight:y,pixelAspectRatio:M,colourPrimaries:k,matrixCoefficients:v,transferCharacteristics:T,fullRangeFlag:S,numReorderFrames:P,maxDecFrameBuffering:N}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},"parseAvcSps"),qz=o(t=>{let e=Z(t);t.skipBits(4),t.skipBits(4);for(let r=0;r<=e;r++)Z(t),Z(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},"skipAvcHrdParameters"),YP=o((t,e)=>{if(e.description){let i=(qe(e.description)[21]&3)+1;return Nx(t,i)}else return Xa(t)},"iterateHevcNalUnits"),Gs=o(t=>t>>1&63,"extractNalUnitTypeForHevc"),GP=o(t=>{try{let e=new Te(Rx(t));e.skipBits(16),e.readBits(4);let r=e.readBits(3),n=e.readBits(1),{general_profile_space:i,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:c,general_constraint_indicator_flags:l,general_level_idc:u}=wee(e,r);Z(e);let f=Z(e),d=0;f===3&&(d=e.readBits(1));let h=Z(e),m=Z(e),p=h,g=m;if(e.readBits(1)){let A=Z(e),R=Z(e),F=Z(e),$=Z(e),W=1,Q=1,re=d===0?f:0;re===1?(W=2,Q=2):re===2&&(W=2,Q=1),p-=(A+R)*W,g-=(F+$)*Q}let y=Z(e),b=Z(e);Z(e);let k=e.readBits(1)?0:r,T=0;for(let A=k;A<=r;A++)Z(e),T=Z(e),Z(e);Z(e),Z(e),Z(e),Z(e),Z(e),Z(e),e.readBits(1)&&e.readBits(1)&&xee(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),Z(e),Z(e),e.skipBits(1));let v=Z(e);if(kee(e,v),e.readBits(1)){let A=Z(e);for(let R=0;R<A;R++)Z(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let S=2,M=2,P=2,N=0,O=0,Y={num:1,den:1};if(e.readBits(1)){let A=Tee(e,r);Y=A.pixelAspectRatio,S=A.colourPrimaries,M=A.transferCharacteristics,P=A.matrixCoefficients,N=A.fullRangeFlag,O=A.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:g,pixelAspectRatio:Y,colourPrimaries:S,transferCharacteristics:M,matrixCoefficients:P,fullRangeFlag:N,maxDecFrameBuffering:T+1,spsMaxSubLayersMinus1:r,spsTemporalIdNestingFlag:n,generalProfileSpace:i,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:u,chromaFormatIdc:f,bitDepthLumaMinus8:y,bitDepthChromaMinus8:b,minSpatialSegmentationIdc:O}}catch(e){return console.error("Error parsing HEVC SPS:",e),null}},"parseHevcSps"),Zf=o(t=>{try{let e=[],r=[],n=[],i=[];for(let u of Xa(t)){let f=t.subarray(u.offset,u.offset+u.length),d=Gs(f[0]);d===vt.VPS_NUT?e.push(f):d===vt.SPS_NUT?r.push(f):d===vt.PPS_NUT?n.push(f):(d===vt.PREFIX_SEI_NUT||d===vt.SUFFIX_SEI_NUT)&&i.push(f)}if(r.length===0||n.length===0)return null;let s=GP(r[0]);if(!s)return null;let a=0;if(n.length>0){let u=n[0],f=new Te(Rx(u));f.skipBits(16),Z(f),Z(f),f.skipBits(1),f.skipBits(1),f.skipBits(3),f.skipBits(1),f.skipBits(1),Z(f),Z(f),$s(f),f.skipBits(1),f.skipBits(1),f.readBits(1)&&Z(f),$s(f),$s(f),f.skipBits(1),f.skipBits(1),f.skipBits(1),f.skipBits(1);let d=f.readBits(1),h=f.readBits(1);!d&&!h?a=0:d&&!h?a=2:!d&&h?a=3:a=0}let c=[...e.length?[{arrayCompleteness:1,nalUnitType:vt.VPS_NUT,nalUnits:e}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:vt.SPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:vt.PPS_NUT,nalUnits:n}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Gs(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:c}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},"extractHevcDecoderConfigurationRecord"),wee=o((t,e)=>{let r=t.readBits(2),n=t.readBits(1),i=t.readBits(5),s=0;for(let f=0;f<32;f++)s=s<<1|t.readBits(1);let a=new Uint8Array(6);for(let f=0;f<6;f++)a[f]=t.readBits(8);let c=t.readBits(8),l=[],u=[];for(let f=0;f<e;f++)l.push(t.readBits(1)),u.push(t.readBits(1));if(e>0)for(let f=e;f<8;f++)t.skipBits(2);for(let f=0;f<e;f++)l[f]&&t.skipBits(88),u[f]&&t.skipBits(8);return{general_profile_space:r,general_tier_flag:n,general_profile_idc:i,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:c}},"parseProfileTierLevel"),xee=o(t=>{for(let e=0;e<4;e++)for(let r=0;r<(e===3?2:6);r++)if(!t.readBits(1))Z(t);else{let i=Math.min(64,1<<4+(e<<1));e>1&&$s(t);for(let s=0;s<i;s++)$s(t)}},"skipScalingListData"),kee=o((t,e)=>{let r=[];for(let n=0;n<e;n++)r[n]=See(t,n,e,r)},"skipAllStRefPicSets"),See=o((t,e,r,n)=>{let i=0,s=0,a=0;if(e!==0&&(s=t.readBits(1)),s){if(e===r){let l=Z(t);a=e-(l+1)}else a=e-1;t.readBits(1),Z(t);let c=n[a]??0;for(let l=0;l<=c;l++)t.readBits(1)||t.readBits(1);i=n[a]}else{let c=Z(t),l=Z(t);for(let u=0;u<c;u++)Z(t),t.readBits(1);for(let u=0;u<l;u++)Z(t),t.readBits(1);i=c+l}return i},"skipStRefPicSet"),Tee=o((t,e)=>{let r=2,n=2,i=2,s=0,a=0,c={num:1,den:1};if(t.readBits(1)){let l=t.readBits(8);if(l===255)c={num:t.readBits(16),den:t.readBits(16)};else{let u=jz[l];u&&(c=u)}}return t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),s=t.readBits(1),t.readBits(1)&&(r=t.readBits(8),n=t.readBits(8),i=t.readBits(8))),t.readBits(1)&&(Z(t),Z(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(Z(t),Z(t),Z(t),Z(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&Z(t),t.readBits(1)&&vee(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),a=Z(t),Z(t),Z(t),Z(t),Z(t)),{pixelAspectRatio:c,colourPrimaries:r,transferCharacteristics:n,matrixCoefficients:i,fullRangeFlag:s,minSpatialSegmentationIdc:a}},"parseHevcVui"),vee=o((t,e,r)=>{let n=!1,i=!1,s=!1;e&&(n=t.readBits(1)===1,i=t.readBits(1)===1,(n||i)&&(s=t.readBits(1)===1,s&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5)));for(let a=0;a<=r;a++){let c=t.readBits(1)===1,l=!0;c||(l=t.readBits(1)===1);let u=!1;l?Z(t):u=t.readBits(1)===1;let f=1;u||(f=Z(t)+1),n&&Yz(t,f,s),i&&Yz(t,f,s)}},"skipHevcHrdParameters"),Yz=o((t,e,r)=>{for(let n=0;n<e;n++)Z(t),Z(t),r&&(Z(t),Z(t)),t.readBits(1)},"skipSubLayerHrdParameters"),Xz=o(t=>{let e=[];e.push(t.configurationVersion),e.push((t.generalProfileSpace&3)<<6|(t.generalTierFlag&1)<<5|t.generalProfileIdc&31),e.push(t.generalProfileCompatibilityFlags>>>24&255),e.push(t.generalProfileCompatibilityFlags>>>16&255),e.push(t.generalProfileCompatibilityFlags>>>8&255),e.push(t.generalProfileCompatibilityFlags&255),e.push(...t.generalConstraintIndicatorFlags),e.push(t.generalLevelIdc&255),e.push(240|t.minSpatialSegmentationIdc>>8&15),e.push(t.minSpatialSegmentationIdc&255),e.push(252|t.parallelismType&3),e.push(252|t.chromaFormatIdc&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.avgFrameRate>>8&255),e.push(t.avgFrameRate&255),e.push((t.constantFrameRate&3)<<6|(t.numTemporalLayers&7)<<3|(t.temporalIdNested&1)<<2|t.lengthSizeMinusOne&3),e.push(t.arrays.length&255);for(let r of t.arrays){e.push((r.arrayCompleteness&1)<<7|0|r.nalUnitType&63),e.push(r.nalUnits.length>>8&255),e.push(r.nalUnits.length&255);for(let n of r.nalUnits){e.push(n.length>>8&255),e.push(n.length&255);for(let i=0;i<n.length;i++)e.push(n[i])}}return new Uint8Array(e)},"serializeHevcDecoderConfigurationRecord"),Jz=o(t=>{try{let e=ge(t),r=0,n=e.getUint8(r++),i=e.getUint8(r++),s=i>>6&3,a=i>>5&1,c=i&31,l=e.getUint32(r,!1);r+=4;let u=t.subarray(r,r+6);r+=6;let f=e.getUint8(r++),d=(e.getUint8(r++)&15)<<8|e.getUint8(r++),h=e.getUint8(r++)&3,m=e.getUint8(r++)&3,p=e.getUint8(r++)&7,g=e.getUint8(r++)&7,y=e.getUint16(r,!1);r+=2;let b=e.getUint8(r++),w=b>>6&3,k=b>>3&7,T=b>>2&1,v=b&3,S=e.getUint8(r++),M=[];for(let P=0;P<S;P++){let N=e.getUint8(r++),O=N>>7&1,Y=N&63,A=e.getUint16(r,!1);r+=2;let R=[];for(let F=0;F<A;F++){let $=e.getUint16(r,!1);r+=2,R.push(t.subarray(r,r+$)),r+=$}M.push({arrayCompleteness:O,nalUnitType:Y,nalUnits:R})}return{configurationVersion:n,generalProfileSpace:s,generalTierFlag:a,generalProfileIdc:c,generalProfileCompatibilityFlags:l,generalConstraintIndicatorFlags:u,generalLevelIdc:f,minSpatialSegmentationIdc:d,parallelismType:h,chromaFormatIdc:m,bitDepthLumaMinus8:p,bitDepthChromaMinus8:g,avgFrameRate:y,constantFrameRate:w,numTemporalLayers:k,temporalIdNested:T,lengthSizeMinusOne:v,arrays:M}}catch(e){return console.error("Error deserializing HEVC Decoder Configuration Record:",e),null}},"deserializeHevcDecoderConfigurationRecord"),Lx=o(t=>{let e=new Te(t);if(e.readBits(2)!==2)return null;let n=e.readBits(1),s=(e.readBits(1)<<1)+n;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let u=8;s>=2&&(u=e.readBits(1)?12:10);let f=e.readBits(3),d=0,h=0;if(f!==7)if(h=e.readBits(1),s===1||s===3){let M=e.readBits(1),P=e.readBits(1);d=!M&&!P?3:M&&!P?2:1,e.skipBits(1)}else d=1;else d=3,h=1;let m=e.readBits(16),p=e.readBits(16),g=m+1,y=p+1,b=g*y,w=Ze(No).level;for(let S of No)if(b<=S.maxPictureSize){w=S.level;break}return{profile:s,level:w,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:h,colourPrimaries:f===2?1:f===1?6:2,transferCharacteristics:f===2?1:f===1?6:2,matrixCoefficients:f===7?0:f===2?1:f===1?6:2}},"extractVp9CodecInfoFromPacket"),Gz=o(function*(t){let e=new Te(t),r=o(()=>{let n=0;for(let i=0;i<8;i++){let s=e.readAlignedByte();if(n|=(s&127)<<i*7,!(s&128))break;if(i===7&&s&128)return null}return n>=2**32-1?null:n},"readLeb128");for(;e.getBitsLeft()>=8;){e.skipBits(1);let n=e.readBits(4),i=e.readBits(1),s=e.readBits(1);e.skipBits(1),i&&e.skipBits(8);let a;if(s){let c=r();if(c===null)return;a=c}else a=Math.floor(e.getBitsLeft()/8);x(e.pos%8===0),yield{type:n,data:t.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},"iterateAv1PacketObus"),Bx=o(t=>{for(let{type:e,data:r}of Gz(t)){if(e!==1)continue;let n=new Te(r),i=n.readBits(3),s=n.readBits(1),a=n.readBits(1),c=0,l=0,u=0;if(a)c=n.readBits(5);else{if(n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.readBits(1)))return null;let S=n.readBits(1);S&&(u=n.readBits(5),n.skipBits(32),n.skipBits(5),n.skipBits(5));let M=n.readBits(5);for(let P=0;P<=M;P++){n.skipBits(12);let N=n.readBits(5);if(P===0&&(c=N),N>7){let Y=n.readBits(1);P===0&&(l=Y)}if(S&&n.readBits(1)){let A=u+1;n.skipBits(A),n.skipBits(A),n.skipBits(1)}n.readBits(1)&&n.skipBits(4)}}let f=n.readBits(4),d=n.readBits(4),h=f+1;n.skipBits(h);let m=d+1;n.skipBits(m);let p=0;if(a?p=0:p=n.readBits(1),p&&(n.skipBits(4),n.skipBits(3)),n.skipBits(1),n.skipBits(1),n.skipBits(1),!a){n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let v=n.readBits(1);v&&(n.skipBits(1),n.skipBits(1));let S=n.readBits(1),M=0;S?M=2:M=n.readBits(1),M>0&&(n.readBits(1)||n.skipBits(1)),v&&n.skipBits(3)}n.skipBits(1),n.skipBits(1),n.skipBits(1);let g=n.readBits(1),y=8;i===2&&g?y=n.readBits(1)?12:10:i<=2&&(y=g?10:8);let b=0;i!==1&&(b=n.readBits(1));let w=1,k=1,T=0;return b||(i===0?(w=1,k=1):i===1?(w=0,k=0):y===12&&(w=n.readBits(1),w&&(k=n.readBits(1))),w&&k&&(T=n.readBits(2))),{profile:i,level:c,tier:l,bitDepth:y,monochrome:b,chromaSubsamplingX:w,chromaSubsamplingY:k,chromaSamplePosition:T}}return null},"extractAv1CodecInfoFromPacket"),Ja=o(t=>{let e=ge(t),r=e.getUint8(9),n=e.getUint16(10,!0),i=e.getUint32(12,!0),s=e.getInt16(16,!0),a=e.getUint8(18),c=null;return a&&(c=t.subarray(19,21+r)),{outputChannelCount:r,preSkip:n,inputSampleRate:i,outputGain:s,channelMappingFamily:a,channelMappingTable:c}},"parseOpusIdentificationHeader"),Eee=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],Zz=o(t=>{let e=t[0]>>3;return{durationInSamples:Eee[e]}},"parseOpusTocByte"),zx=o(t=>{if(t.length<7)throw new Error("Setup header is too short.");if(t[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...t.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let r=t.length,n=new Uint8Array(r);for(let d=0;d<r;d++)n[d]=t[r-1-d];let i=new Te(n),s=0;for(;i.getBitsLeft()>97;)if(i.readBits(1)===1){s=i.pos;break}if(s===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,c=!1,l=0;for(;i.getBitsLeft()>=97;){let d=i.pos,h=i.readBits(8),m=i.readBits(16),p=i.readBits(16);if(h>63||m!==0||p!==0){i.pos=d;break}if(i.skipBits(1),a++,a>64)break;i.clone().readBits(6)+1===a&&(c=!0,l=a)}if(!c)throw new Error("Invalid Setup header: mode header not found.");if(l>63)throw new Error(`Unsupported mode count: ${l}.`);let u=l;i.pos=0,i.skipBits(s);let f=Array(u).fill(0);for(let d=u-1;d>=0;d--)i.skipBits(40),f[d]=i.readBits(1);return{modeBlockflags:f}},"parseModesFromVorbisSetupPacket"),Ux=o((t,e,r)=>{switch(t){case"avc":{for(let n of jP(r,e)){let i=r[n.offset],s=Ao(i);if(s>=Cn.NON_IDR_SLICE&&s<=Cn.SLICE_DPC)return"delta";if(s===Cn.IDR)return"key";if(s===Cn.SEI&&(!tp()||Cz()>=144)){let a=r.subarray(n.offset,n.offset+n.length),c=Rx(a),l=1;do{let u=0;for(;;){let h=c[l++];if(h===void 0||(u+=h,h<255))break}let f=0;for(;;){let h=c[l++];if(h===void 0||(f+=h,h<255))break}if(u===6){let h=new Te(c);h.pos=8*l;let m=Z(h),p=h.readBits(1);if(m===0&&p===1)return"key"}l+=f}while(l<c.length-1)}}return"delta"}case"hevc":{for(let n of YP(r,e)){let i=Gs(r[n.offset]);if(i<vt.BLA_W_LP)return"delta";if(i<=vt.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(r[0]&1)===0?"key":"delta";case"vp9":{let n=new Te(r);if(n.readBits(2)!==2)return null;let i=n.readBits(1);return(n.readBits(1)<<1)+i===3&&n.skipBits(1),n.readBits(1)?null:n.readBits(1)===0?"key":"delta"}case"av1":{let n=!1;for(let{type:i,data:s}of Gz(r))if(i===1){let a=new Te(s);a.skipBits(4),n=!!a.readBits(1)}else if(i===3||i===6||i===7){if(n)return"key";let a=new Te(s);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}default:kt(t),x(!1)}},"determineVideoPacketType");(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(Ei||(Ei={}));sp=o((t,e)=>{let r=ge(t),n=0,i=r.getUint32(n,!0);n+=4;let s=br.decode(t.subarray(n,n+i));n+=i,i>0&&(e.raw??={},e.raw.vendor??=s);let a=r.getUint32(n,!0);n+=4;for(let c=0;c<a;c++){let l=r.getUint32(n,!0);n+=4;let u=br.decode(t.subarray(n,n+l));n+=l;let f=u.indexOf("=");if(f===-1)continue;let d=u.slice(0,f).toUpperCase(),h=u.slice(f+1);switch(e.raw??={},e.raw[d]??=h,d){case"TITLE":e.title??=h;break;case"DESCRIPTION":e.description??=h;break;case"ARTIST":e.artist??=h;break;case"ALBUM":e.album??=h;break;case"ALBUMARTIST":e.albumArtist??=h;break;case"COMMENT":e.comment??=h;break;case"LYRICS":e.lyrics??=h;break;case"TRACKNUMBER":{let m=h.split("/"),p=Number.parseInt(m[0],10),g=m[1]&&Number.parseInt(m[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.tracksTotal??=g)}break;case"TRACKTOTAL":{let m=Number.parseInt(h,10);Number.isInteger(m)&&m>0&&(e.tracksTotal??=m)}break;case"DISCNUMBER":{let m=h.split("/"),p=Number.parseInt(m[0],10),g=m[1]&&Number.parseInt(m[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.discsTotal??=g)}break;case"DISCTOTAL":{let m=Number.parseInt(h,10);Number.isInteger(m)&&m>0&&(e.discsTotal??=m)}break;case"DATE":{let m=new Date(h);Number.isNaN(m.getTime())||(e.date??=m)}break;case"GENRE":e.genre??=h;break;case"METADATA_BLOCK_PICTURE":{let m=Iz(h),p=ge(m),g=p.getUint32(0,!1),y=p.getUint32(4,!1),b=String.fromCharCode(...m.subarray(8,8+y)),w=p.getUint32(8+y,!1),k=br.decode(m.subarray(12+y,12+y+w)),T=p.getUint32(y+w+28),v=m.subarray(y+w+32,y+w+32+T);e.images??=[],e.images.push({data:v,mimeType:b,kind:g===3?"coverFront":g===4?"coverBack":"unknown",name:void 0,description:k||void 0})}break}}},"readVorbisComments"),op=o((t,e,r)=>{let n=[t],s=lt.encode("Mediabunny"),a=new Uint8Array(4+s.length),c=new DataView(a.buffer);c.setUint32(0,s.length,!0),a.set(s,4),n.push(a);let l=new Set,u=o((p,g)=>{let y=`${p}=${g}`,b=lt.encode(y);a=new Uint8Array(4+b.length),c=new DataView(a.buffer),c.setUint32(0,b.length,!0),a.set(b,4),n.push(a),l.add(p)},"addCommentTag");for(let{key:p,value:g}of Gi(e))switch(p){case"title":u("TITLE",g);break;case"description":u("DESCRIPTION",g);break;case"artist":u("ARTIST",g);break;case"album":u("ALBUM",g);break;case"albumArtist":u("ALBUMARTIST",g);break;case"genre":u("GENRE",g);break;case"date":{let y=e.raw?.DATE??e.raw?.date;y&&typeof y=="string"?u("DATE",y):u("DATE",g.toISOString().slice(0,10))}break;case"comment":u("COMMENT",g);break;case"lyrics":u("LYRICS",g);break;case"trackNumber":u("TRACKNUMBER",g.toString());break;case"tracksTotal":u("TRACKTOTAL",g.toString());break;case"discNumber":u("DISCNUMBER",g.toString());break;case"discsTotal":u("DISCTOTAL",g.toString());break;case"images":{if(!r)break;for(let y of g){let b=y.kind==="coverFront"?3:y.kind==="coverBack"?4:0,w=new Uint8Array(y.mimeType.length);for(let M=0;M<y.mimeType.length;M++)w[M]=y.mimeType.charCodeAt(M);let k=lt.encode(y.description??""),T=new Uint8Array(8+w.length+4+k.length+16+4+y.data.length),v=ge(T);v.setUint32(0,b,!1),v.setUint32(4,w.length,!1),T.set(w,8),v.setUint32(8+w.length,k.length,!1),T.set(k,12+w.length),v.setUint32(28+w.length+k.length,y.data.length,!1),T.set(y.data,32+w.length+k.length);let S=_z(T);u("METADATA_BLOCK_PICTURE",S)}}break;case"raw":break;default:kt(p)}if(e.raw)for(let p in e.raw){let g=e.raw[p]??e.raw[p.toLowerCase()];p==="vendor"||g==null||l.has(p)||typeof g=="string"&&u(p,g)}let f=new Uint8Array(4);ge(f).setUint32(0,l.size,!0),n.splice(2,0,f);let d=n.reduce((p,g)=>p+g.length,0),h=new Uint8Array(d),m=0;for(let p of n)h.set(p,m),m+=p.length;return h},"createVorbisComments"),ap=[2,1,2,3,3,4,4,5],$x=o(t=>{if(t.length<7||t[0]!==11||t[1]!==119)return null;let e=new Te(t);e.skipBits(16),e.skipBits(16);let r=e.readBits(2);if(r===3)return null;let n=e.readBits(6),i=e.readBits(5);if(i>8)return null;let s=e.readBits(3),a=e.readBits(3);(a&1)!==0&&a!==1&&e.skipBits(2),(a&4)!==0&&e.skipBits(2),a===2&&e.skipBits(2);let c=e.readBits(1),l=Math.floor(n/2);return{fscod:r,bsid:i,bsmod:s,acmod:a,lfeon:c,bitRateCode:l}},"parseAc3SyncFrame"),eU=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],tU=1536,cp=new Uint8Array([5,4,65,67,45,51]),lp=new Uint8Array([5,4,69,65,67,51]),QP=[1,2,3,6],Hx=o(t=>{if(t.length<6||t[0]!==11||t[1]!==119)return null;let e=new Te(t);e.skipBits(16);let r=e.readBits(2);if(e.skipBits(3),r!==0&&r!==2)return null;let n=e.readBits(11),i=e.readBits(2),s=0,a;i===3?(s=e.readBits(2),a=3):a=e.readBits(2);let c=e.readBits(3),l=e.readBits(1),u=e.readBits(5);if(u<11||u>16)return null;let f=QP[a],d;return i<3?d=Rl[i]/1e3:d=VP[s]/1e3,{dataRate:Math.round((n+1)*d/(f*16)),substreams:[{fscod:i,fscod2:s,bsid:u,bsmod:0,acmod:c,lfeon:l,numDepSub:0,chanLoc:0}]}},"parseEac3SyncFrame"),rU=o(t=>{if(t.length<2)return null;let e=new Te(t),r=e.readBits(13),n=e.readBits(3),i=[];for(let s=0;s<=n&&!(Math.ceil(e.pos/8)+3>t.length);s++){let a=e.readBits(2),c=e.readBits(5);e.skipBits(1),e.skipBits(1);let l=e.readBits(3),u=e.readBits(3),f=e.readBits(1);e.skipBits(3);let d=e.readBits(4),h=0;d>0?h=e.readBits(9):e.skipBits(1),i.push({fscod:a,fscod2:null,bsid:c,bsmod:l,acmod:u,lfeon:f,numDepSub:d,chanLoc:h})}return i.length===0?null:{dataRate:r,substreams:i}},"parseEac3Config"),Vx=o(t=>{let e=t.substreams[0];return x(e),e.fscod<3?Rl[e.fscod]:e.fscod2!==null&&e.fscod2<3?VP[e.fscod2]:null},"getEac3SampleRate"),Wx=o(t=>{let e=t.substreams[0];x(e);let r=ap[e.acmod]+e.lfeon;if(e.numDepSub>0){let n=[2,2,1,1,2,2,2,1,1];for(let i=0;i<9;i++)e.chanLoc&1<<8-i&&(r+=n[i])}return r},"getEac3ChannelCount")});var wr,Fo=he(()=>{wr=class{static{o(this,"Demuxer")}constructor(e){this.input=e}}});var up,fp,dp,hp,ed,td,Nl,Al,nU,iU,rd=he(()=>{up=class{static{o(this,"CustomVideoDecoder")}static supports(e,r){return!1}},fp=class{static{o(this,"CustomAudioDecoder")}static supports(e,r){return!1}},dp=class{static{o(this,"CustomVideoEncoder")}static supports(e,r){return!1}},hp=class{static{o(this,"CustomAudioEncoder")}static supports(e,r){return!1}},ed=[],td=[],Nl=[],Al=[],nU=o(t=>{if(t.prototype instanceof up){let e=t;if(ed.includes(e)){console.warn("Video decoder already registered.");return}ed.push(e)}else if(t.prototype instanceof fp){let e=t;if(td.includes(e)){console.warn("Audio decoder already registered.");return}td.push(e)}else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},"registerDecoder"),iU=o(t=>{if(t.prototype instanceof dp){let e=t;if(Nl.includes(e)){console.warn("Video encoder already registered.");return}Nl.push(e)}else if(t.prototype instanceof hp){let e=t;if(Al.includes(e)){console.warn("Audio encoder already registered.");return}Al.push(e)}else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")},"registerEncoder")});var Wt,je,Qn=he(()=>{Ue();Wt=new Uint8Array(0),je=class t{static{o(this,"EncodedPacket")}constructor(e,r,n,i,s=-1,a,c){if(this.data=e,this.type=r,this.timestamp=n,this.duration=i,this.sequenceNumber=s,e===Wt&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!=="key"&&r!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(n))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(i)||i<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(c!==void 0&&(typeof c!="object"||!c))throw new TypeError("sideData, when provided, must be an object.");if(c?.alpha!==void 0&&!(c.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(c?.alphaByteLength!==void 0&&(!Number.isInteger(c.alphaByteLength)||c.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=c??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Wt}get microsecondTimestamp(){return Math.trunc(Hs*this.timestamp)}get microsecondDuration(){return Math.trunc(Hs*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,r){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let n=new Uint8Array(e.byteLength);return e.copyTo(n),new t(n,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,r)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new t(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}}});var sU,oU,aU,cU,KP=he(()=>{sU=o(t=>{let n=t,i=4096,s=0,a=12,c=0;for(n<0&&(n=-n,s=128),n+=33,n>8191&&(n=8191);(n&i)!==i&&a>=5;)i>>=1,a--;return c=n>>a-4&15,~(s|a-5<<4|c)&255},"toUlaw"),oU=o(t=>{let r=0,n=0,i=~t;i&128&&(i&=-129,r=-1),n=((i&240)>>4)+5;let s=(1<<n|(i&15)<<n-4|1<<n-5)-33;return r===0?s:-s},"fromUlaw"),aU=o(t=>{let r=2048,n=0,i=11,s=0,a=t;for(a<0&&(a=-a,n=128),a>4095&&(a=4095);(a&r)!==r&&i>=5;)r>>=1,i--;return s=a>>(i===4?1:i-4)&15,(n|i-4<<4|s)^85},"toAlaw"),cU=o(t=>{let e=0,r=0,n=t^85;n&128&&(n&=-129,e=-1),r=((n&240)>>4)+4;let i=0;return r!==4?i=1<<r|(n&15)<<r-4|1<<r-5:i=n<<1|1,e===0?i:-i},"fromAlaw")});var lU,uU,mp,jx,Cee,ur,Bl,Fl,gp,yp,fU,Pee,Iee,XP,Dr,Ll,nd,dU,hU,pp,_ee,bp=he(()=>{Ue();vx();lU=-1/0,uU=-1/0,mp=null;typeof FinalizationRegistry<"u"&&(mp=new FinalizationRegistry(t=>{let e=Date.now();t.type==="video"?(e-lU>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),lU=e),typeof VideoFrame<"u"&&t.data instanceof VideoFrame&&t.data.close()):(e-uU>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),uU=e),typeof AudioData<"u"&&t.data instanceof AudioData&&t.data.close())}));jx=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Cee=new Set(jx),ur=class t{static{o(this,"VideoSample")}get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(Hs*this.timestamp)}get microsecondDuration(){return Math.trunc(Hs*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,r){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.format===void 0||!Cee.has(r.format))throw new TypeError("init.format must be one of: "+jx.join(", "));if(!Number.isInteger(r.codedWidth)||r.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(r.codedHeight)||r.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("init.layout, when provided, must be an array.");for(let n of r.layout){if(!n||typeof n!="object"||Array.isArray(n))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(n.offset)||n.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(n.stride)||n.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.visibleRect!==void 0&&$P(r.visibleRect,"init.visibleRect"),r.displayWidth!==void 0&&(!Number.isInteger(r.displayWidth)||r.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(r.displayHeight!==void 0&&(!Number.isInteger(r.displayHeight)||r.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(r.displayWidth!==void 0!=(r.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this._data=qe(e).slice(),this._layout=r.layout??Pee(r.format,r.codedWidth,r.codedHeight),this.format=r.format,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Bl(r.colorSpace),this.visibleRect={left:r.visibleRect?.left??0,top:r.visibleRect?.top??0,width:r.visibleRect?.width??r.codedWidth,height:r.visibleRect?.height??r.codedHeight},r.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?r.displayWidth:r.displayHeight,this.squarePixelHeight=this.rotation%180===0?r.displayHeight:r.displayWidth):(this.squarePixelWidth=this.codedWidth,this.squarePixelHeight=this.codedHeight)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(r?.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(r?.timestamp!==void 0&&!Number.isFinite(r?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(r?.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");r?.visibleRect!==void 0&&$P(r.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=r?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=r?.timestamp??e.timestamp/1e6,this.duration=r?.duration??(e.duration??0)/1e6,this.colorSpace=new Bl(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new t(new VideoFrame(e,{timestamp:Math.trunc(r.timestamp*Hs),duration:Math.trunc((r.duration??0)*Hs)||void 0}),r);let n=0,i=0;if("naturalWidth"in e?(n=e.naturalWidth,i=e.naturalHeight):"videoWidth"in e?(n=e.videoWidth,i=e.videoHeight):"width"in e&&(n=Number(e.width),i=Number(e.height)),!n||!i)throw new TypeError("Could not determine dimensions.");let s=new OffscreenCanvas(n,i),a=s.getContext("2d",{alpha:Vs(),willReadFrequently:!0});x(a),a.drawImage(e,0,0),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:n,height:i},this.squarePixelWidth=n,this.squarePixelHeight=i,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Bl({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");this.pixelAspectRatio=qa({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),mp?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return x(this._data!==null),Fl(this._data)?new t(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(x(this._layout),new t(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})):new t(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})}close(){this._closed||(mp?.unregister(this),Fl(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(fU(e),this._closed)throw new Error("VideoSample is closed.");if(this.format===null)throw new Error("Cannot get allocation size when format is null. Sorry!");if(x(this._data!==null),!Fl(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let r=this.toVideoFrame(),n=r.allocationSize(e);return r.close(),n}return Fl(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,r={}){if(!jf(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(fU(r),this._closed)throw new Error("VideoSample is closed.");if(this.format===null)throw new Error("Cannot copy video sample data when format is null. Sorry!");if(x(this._data!==null),!Fl(this._data)&&(r.colorSpace||r.format&&r.format!==this.format||r.layout||r.rect)){let n=this.toVideoFrame(),i=await n.copyTo(e,r);return n.close(),i}if(Fl(this._data))return this._data.copyTo(e,r);if(this._data instanceof Uint8Array)return x(this._layout),qe(e).set(this._data),this._layout;{let i=this._data.getContext("2d");x(i);let s=i.getImageData(0,0,this.codedWidth,this.codedHeight);return qe(e).set(s.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return x(this._data!==null),Fl(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,r,n,i,s,a,c,l,u){let f=0,d=0,h=this.displayWidth,m=this.displayHeight,p=0,g=0,y=this.displayWidth,b=this.displayHeight;if(a!==void 0?(f=r,d=n,h=i,m=s,p=a,g=c,l!==void 0?(y=l,b=u):(y=h,b=m)):(p=r,g=n,i!==void 0&&(y=i,b=s)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(f))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(m)||m<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(g))throw new TypeError("dy must be a number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(b)||b<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:f,sy:d,sWidth:h,sHeight:m}=this._rotateSourceRegion(f,d,h,m,this.rotation));let w=this.toCanvasImageSource();e.save();let k=p+y/2,T=g+b/2;e.translate(k,T),e.rotate(this.rotation*Math.PI/180);let v=this.rotation%180===0?1:y/b;e.scale(1/v,v),e.drawImage(w,f,d,h,m,-y/2,-b/2,y,b),e.restore()}drawWithFit(e,r){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(r.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");r.crop!==void 0&&yp(r.crop,"options.");let n=e.canvas.width,i=e.canvas.height,s=r.rotation??this.rotation,[a,c]=s%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];r.crop&&gp(r.crop,a,c);let l,u,f,d,{sx:h,sy:m,sWidth:p,sHeight:g}=this._rotateSourceRegion(r.crop?.left??0,r.crop?.top??0,r.crop?.width??a,r.crop?.height??c,s);if(r.fit==="fill")l=0,u=0,f=n,d=i;else{let[b,w]=r.crop?[r.crop.width,r.crop.height]:[a,c],k=r.fit==="contain"?Math.min(n/b,i/w):Math.max(n/b,i/w);f=b*k,d=w*k,l=(n-f)/2,u=(i-d)/2}e.save();let y=s%180===0?1:f/d;e.translate(n/2,i/2),e.rotate(s*Math.PI/180),e.scale(1/y,y),e.translate(-n/2,-i/2),e.drawImage(this.toCanvasImageSource(),h,m,p,g,l,u,f,d),e.restore()}_rotateSourceRegion(e,r,n,i,s){return s===90?[e,r,n,i]=[r,this.squarePixelHeight-e-n,i,n]:s===180?[e,r]=[this.squarePixelWidth-e-n,this.squarePixelHeight-r-i]:s===270&&([e,r,n,i]=[this.squarePixelWidth-r-i,e,i,n]),{sx:e,sy:r,sWidth:n,sHeight:i}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(x(this._data!==null),this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}},Bl=class{static{o(this,"VideoSampleColorSpace")}constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");let r=Object.keys(ji);if(e.primaries!=null&&!r.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${r.join(", ")}.`);let n=Object.keys(qi);if(e.transfer!=null&&!n.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${n.join(", ")}.`);let i=Object.keys(Yi);if(e.matrix!=null&&!i.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${i.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},Fl=o(t=>typeof VideoFrame<"u"&&t instanceof VideoFrame,"isVideoFrame"),gp=o((t,e,r)=>{t.left=Math.min(t.left,e),t.top=Math.min(t.top,r),t.width=Math.min(t.width,e-t.left),t.height=Math.min(t.height,r-t.top),x(t.width>=0),x(t.height>=0)},"clampCropRectangle"),yp=o((t,e)=>{if(!t||typeof t!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},"validateCropRectangle"),fU=o(t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.colorSpace!==void 0&&!["display-p3","srgb"].includes(t.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(t.format!==void 0&&typeof t.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of t.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.rect!==void 0){if(!t.rect||typeof t.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(t.rect.x!==void 0&&(!Number.isInteger(t.rect.x)||t.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(t.rect.y!==void 0&&(!Number.isInteger(t.rect.y)||t.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(t.rect.width!==void 0&&(!Number.isInteger(t.rect.width)||t.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(t.rect.height!==void 0&&(!Number.isInteger(t.rect.height)||t.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},"validateVideoFrameCopyToOptions"),Pee=o((t,e,r)=>{let n=Iee(t),i=[],s=0;for(let a of n){let c=Math.ceil(e/a.widthDivisor),l=Math.ceil(r/a.heightDivisor),u=c*a.sampleBytes,f=u*l;i.push({offset:s,stride:u}),s+=f}return i},"createDefaultPlaneLayout"),Iee=o(t=>{let e=o((r,n,i,s,a)=>{let c=[{sampleBytes:r,widthDivisor:1,heightDivisor:1},{sampleBytes:n,widthDivisor:i,heightDivisor:s},{sampleBytes:n,widthDivisor:i,heightDivisor:s}];return a&&c.push({sampleBytes:r,widthDivisor:1,heightDivisor:1}),c},"yuv");switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:kt(t),x(!1)}},"getPlaneConfigs"),XP=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),Dr=class t{static{o(this,"AudioSample")}get microsecondTimestamp(){return Math.trunc(Hs*this.timestamp)}get microsecondDuration(){return Math.trunc(Hs*this.duration)}constructor(e){if(this._closed=!1,pp(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!XP.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");let r=e.data.byteLength/(Ll(e.format)*e.numberOfChannels);if(!Number.isInteger(r))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=r,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=r/e.sampleRate;let n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let i=this.numberOfFrames*this.numberOfChannels*Ll(this.format);if(n.byteLength<i)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=n}mp?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!XP.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let r=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let i=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-n;if(i>this.numberOfFrames-n)throw new RangeError("frameCount out of range");let s=Ll(r),a=nd(r);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?i:i*this.numberOfChannels)*s}copyTo(e,r){if(!jf(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(r.planeIndex)||r.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(r.format!==void 0&&!XP.has(r.format))throw new TypeError("Invalid format.");if(r.frameOffset!==void 0&&(!Number.isInteger(r.frameOffset)||r.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(r.frameCount!==void 0&&(!Number.isInteger(r.frameCount)||r.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{planeIndex:n,format:i,frameCount:s,frameOffset:a}=r,c=this.format,l=i??this.format;if(!l)throw new Error("Destination format not determined");let u=this.numberOfFrames,f=this.numberOfChannels,d=a??0;if(d>=u)throw new RangeError("frameOffset out of range");let h=s!==void 0?s:u-d;if(h>u-d)throw new RangeError("frameCount out of range");let m=Ll(l),p=nd(l);if(p&&n>=f)throw new RangeError("planeIndex out of range");if(!p&&n!==0)throw new RangeError("planeIndex out of range");let y=(p?h:h*f)*m;if(e.byteLength<y)throw new RangeError("Destination buffer is too small");let b=ge(e),w=hU(l);if(pp(this._data))Wa()&&f>2&&l!==c?_ee(this._data,b,c,l,f,n,d,h):this._data.copyTo(e,{planeIndex:n,frameOffset:d,frameCount:h,format:l});else{let k=this._data,T=ge(k),v=dU(c),S=Ll(c),M=nd(c);for(let P=0;P<h;P++)if(p){let N=P*m,O;M?O=(n*u+(P+d))*S:O=((P+d)*f+n)*S;let Y=v(T,O);w(b,N,Y)}else for(let N=0;N<f;N++){let Y=(P*f+N)*m,A;M?A=(N*u+(P+d))*S:A=((P+d)*f+N)*S;let R=v(T,A);w(b,Y,R)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(pp(this._data)){let e=new t(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new t({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(mp?.unregister(this),pp(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(pp(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(nd(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),r=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(r,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:r})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),r=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(r,{planeIndex:n,format:"f32-planar"}),e.copyToChannel(r,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,i=e.numberOfChannels,s=e.sampleRate,a=e.length,c=Math.floor(n/i),l=0,u=a;for(;u>0;){let f=Math.min(c,u),d=new Float32Array(i*f);for(let h=0;h<i;h++)e.copyFromChannel(d.subarray(h*f,(h+1)*f),h,l);yield new t({format:"f32-planar",sampleRate:s,numberOfFrames:f,numberOfChannels:i,timestamp:r+l/s,data:d}),l+=f,u-=f}}static fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,i=e.numberOfChannels,s=e.sampleRate,a=e.length,c=Math.floor(n/i),l=0,u=a,f=[];for(;u>0;){let d=Math.min(c,u),h=new Float32Array(i*d);for(let p=0;p<i;p++)e.copyFromChannel(h.subarray(p*d,(p+1)*d),p,l);let m=new t({format:"f32-planar",sampleRate:s,numberOfFrames:d,numberOfChannels:i,timestamp:r+l/s,data:h});f.push(m),l+=d,u-=d}return f}},Ll=o(t=>{switch(t){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},"getBytesPerSample"),nd=o(t=>{switch(t){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},"formatIsPlanar"),dU=o(t=>{switch(t){case"u8":case"u8-planar":return(e,r)=>(e.getUint8(r)-128)/128;case"s16":case"s16-planar":return(e,r)=>e.getInt16(r,!0)/32768;case"s32":case"s32-planar":return(e,r)=>e.getInt32(r,!0)/2147483648;case"f32":case"f32-planar":return(e,r)=>e.getFloat32(r,!0)}},"getReadFunction"),hU=o(t=>{switch(t){case"u8":case"u8-planar":return(e,r,n)=>e.setUint8(r,Ht((n+1)*127.5,0,255));case"s16":case"s16-planar":return(e,r,n)=>e.setInt16(r,Ht(Math.round(n*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,r,n)=>e.setInt32(r,Ht(Math.round(n*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,r,n)=>e.setFloat32(r,n,!0)}},"getWriteFunction"),pp=o(t=>typeof AudioData<"u"&&t instanceof AudioData,"isAudioData"),_ee=o((t,e,r,n,i,s,a,c)=>{let l=dU(r),u=hU(n),f=Ll(r),d=Ll(n),h=nd(r);if(nd(n))if(h){let p=new ArrayBuffer(c*f),g=ge(p);t.copyTo(p,{planeIndex:s,frameOffset:a,frameCount:c,format:r});for(let y=0;y<c;y++){let b=y*f,w=y*d,k=l(g,b);u(e,w,k)}}else{let p=new ArrayBuffer(c*i*f),g=ge(p);t.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:c,format:r});for(let y=0;y<c;y++){let b=(y*i+s)*f,w=y*d,k=l(g,b);u(e,w,k)}}else if(h){let p=c*f,g=new ArrayBuffer(p),y=ge(g);for(let b=0;b<i;b++){t.copyTo(g,{planeIndex:b,frameOffset:a,frameCount:c,format:r});for(let w=0;w<c;w++){let k=w*f,T=(w*i+b)*d,v=l(y,k);u(e,T,v)}}}else{let p=new ArrayBuffer(c*i*f),g=ge(p);t.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:c,format:r});for(let y=0;y<c;y++)for(let b=0;b<i;b++){let w=y*i+b,k=w*f,T=w*d,v=l(g,k);u(e,T,v)}}},"doAudioDataCopyToWebKitWorkaround")});var zl,Lo,JP,Ki,wp,id,mU,ZP,eI,Za,sd,tI,rI,ec,qx,Yx=he(()=>{Zt();sn();rd();od();Xi();Ue();Qn();KP();bp();zl=o(t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.metadataOnly!==void 0&&typeof t.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(t.verifyKeyPackets!==void 0&&typeof t.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(t.verifyKeyPackets&&t.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},"validatePacketRetrievalOptions"),Lo=o(t=>{if(!ja(t))throw new TypeError("timestamp must be a number.")},"validateTimestamp"),JP=o((t,e,r)=>r.verifyKeyPackets?e.then(async n=>{if(!n||n.type==="delta")return n;let i=await t.determinePacketType(n);return i&&(n.type=i),n}):e,"maybeFixPacketType"),Ki=class{static{o(this,"EncodedPacketSink")}constructor(e){if(!(e instanceof tc))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(zl(e),this._track.input._disposed)throw new er;return JP(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){zl(e);let r=await this.getFirstPacket(e);return r?r.type==="key"?r:this.getNextKeyPacket(r,e):null}getPacket(e,r={}){if(Lo(e),zl(r),this._track.input._disposed)throw new er;return JP(this._track,this._track._backing.getPacket(e,r),r)}getNextPacket(e,r={}){if(!(e instanceof je))throw new TypeError("packet must be an EncodedPacket.");if(zl(r),this._track.input._disposed)throw new er;return JP(this._track,this._track._backing.getNextPacket(e,r),r)}async getKeyPacket(e,r={}){if(Lo(e),zl(r),this._track.input._disposed)throw new er;if(!r.verifyKeyPackets)return this._track._backing.getKeyPacket(e,r);let n=await this._track._backing.getKeyPacket(e,r);return n&&(x(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getKeyPacket(n.timestamp-1/this._track.timeResolution,r):n)}async getNextKeyPacket(e,r={}){if(!(e instanceof je))throw new TypeError("packet must be an EncodedPacket.");if(zl(r),this._track.input._disposed)throw new er;if(!r.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,r);let n=await this._track._backing.getNextKeyPacket(e,r);return n&&(x(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getNextKeyPacket(n,r):n)}packets(e,r,n={}){if(e!==void 0&&!(e instanceof je))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(r!==void 0&&!(r instanceof je))throw new TypeError("endPacket must be an EncodedPacket.");if(zl(n),this._track.input._disposed)throw new er;let i=[],{promise:s,resolve:a}=ut(),{promise:c,resolve:l}=ut(),u=!1,f=!1,d=null,h=[],m=o(()=>Math.max(2,h.length),"maxQueueSize");(async()=>{let g=e??await this.getFirstPacket(n);for(;g&&!f&&!this._track.input._disposed&&!(r&&g.sequenceNumber>=r?.sequenceNumber);){if(i.length>m()){({promise:c,resolve:l}=ut()),await c;continue}i.push(g),a(),{promise:s,resolve:a}=ut(),g=await this.getNextPacket(g,n)}u=!0,a()})().catch(g=>{d||(d=g,a())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new er;if(f)return{value:void 0,done:!0};if(d)throw d;if(i.length>0){let g=i.shift(),y=performance.now();for(h.push(y);h.length>0&&y-h[0]>=1e3;)h.shift();return l(),{value:g,done:!1}}else{if(u)return{value:void 0,done:!0};await s}}},async return(){return f=!0,l(),a(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},wp=class{static{o(this,"DecoderWrapper")}constructor(e,r){this.onSample=e,this.onError=r}},id=class{static{o(this,"BaseMediaSampleSink")}mediaSamplesInRange(e=0,r=1/0){Lo(e),Lo(r);let n=[],i=!1,s=null,{promise:a,resolve:c}=ut(),{promise:l,resolve:u}=ut(),f=!1,d=!1,h=!1,m=null;(async()=>{let y=await this._createDecoder(S=>{if(u(),S.timestamp>=r&&(d=!0),d){S.close();return}s&&(S.timestamp>e?(n.push(s),i=!0):s.close()),S.timestamp>=e&&(n.push(S),i=!0),s=i?null:S,n.length>0&&(c(),{promise:a,resolve:c}=ut())},S=>{m||(m=S,c())}),b=this._createPacketSink(),w=await b.getKeyPacket(e,{verifyKeyPackets:!0})??await b.getFirstKeyPacket({verifyKeyPackets:!0}),k=w,v=b.packets(w??void 0,void 0);for(await v.next();k&&!d&&!this._track.input._disposed;){let S=mU(n.length);if(n.length+y.getDecodeQueueSize()>S){({promise:l,resolve:u}=ut()),await l;continue}y.decode(k);let M=await v.next();if(M.done)break;k=M.value}await v.return(),!h&&!this._track.input._disposed&&await y.flush(),y.close(),!i&&s&&n.push(s),f=!0,c()})().catch(y=>{m||(m=y,c())});let p=this._track,g=o(()=>{s?.close();for(let y of n)y.close()},"closeSamples");return{async next(){for(;;){if(p.input._disposed)throw g(),new er;if(h)return{value:void 0,done:!0};if(m)throw g(),m;if(n.length>0){let y=n.shift();return u(),{value:y,done:!1}}else if(!f)await a;else return{value:void 0,done:!0}}},async return(){return h=!0,d=!0,u(),c(),g(),{value:void 0,done:!0}},async throw(y){throw y},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){xz(e);let r=wz(e),n=[],i=[],{promise:s,resolve:a}=ut(),{promise:c,resolve:l}=ut(),u=!1,f=!1,d=null,h=o(g=>{i.push(g),a(),{promise:s,resolve:a}=ut()},"pushToQueue");(async()=>{let g=await this._createDecoder(S=>{if(l(),f){S.close();return}let M=0;for(;n.length>0&&S.timestamp-n[0]>-1e-10;)M++,n.shift();if(M>0)for(let P=0;P<M;P++)h(P<M-1?S.clone():S);else S.close()},S=>{d||(d=S,a())}),y=this._createPacketSink(),b=null,w=null,k=-1,T=o(async()=>{x(w);let S=w;for(g.decode(S);S.sequenceNumber<k;){let M=mU(i.length);for(;i.length+g.getDecodeQueueSize()>M&&!f;)({promise:c,resolve:l}=ut()),await c;if(f)break;let P=await y.getNextPacket(S);x(P),g.decode(P),S=P}k=-1},"decodePackets"),v=o(async()=>{await g.flush();for(let S=0;S<n.length;S++)h(null);n.length=0},"flushDecoder");for await(let S of r){if(Lo(S),f||this._track.input._disposed)break;let M=await y.getPacket(S),P=M&&await y.getKeyPacket(S,{verifyKeyPackets:!0});if(!P){k!==-1&&(await T(),await v()),h(null),b=null;continue}b&&(P.sequenceNumber!==w.sequenceNumber||M.timestamp<b.timestamp)&&(await T(),await v()),n.push(M.timestamp),k=Math.max(M.sequenceNumber,k),b=M,w=P}!f&&!this._track.input._disposed&&(k!==-1&&await T(),await v()),g.close(),u=!0,a()})().catch(g=>{d||(d=g,a())});let m=this._track,p=o(()=>{for(let g of i)g?.close()},"closeSamples");return{async next(){for(;;){if(m.input._disposed)throw p(),new er;if(f)return{value:void 0,done:!0};if(d)throw p(),d;if(i.length>0){let g=i.shift();return x(g!==void 0),l(),{value:g,done:!1}}else if(!u)await s;else return{value:void 0,done:!0}}},async return(){return f=!0,l(),a(),p(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},mU=o(t=>t===0?40:8,"computeMaxQueueSize"),ZP=class extends wp{static{o(this,"VideoDecoderWrapper")}constructor(e,r,n,i,s,a){super(e,r),this.codec=n,this.decoderConfig=i,this.rotation=s,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new $a,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;let c=ed.find(l=>l.supports(n,i));if(c)this.customDecoder=new c,this.customDecoder.codec=n,this.customDecoder.config=i,this.customDecoder.onSample=l=>{if(!(l instanceof ur))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(l)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let l=o(f=>{if(this.alphaQueue.length>0){let d=this.alphaQueue.shift();x(d!==void 0),this.mergeAlpha(f,d)}else this.colorQueue.push(f)},"colorHandler");if(n==="avc"&&this.decoderConfig.description&&tp()){let f=Fx(qe(this.decoderConfig.description));if(f&&f.sequenceParameterSets.length>0){let d=ip(f.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let u=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:o(f=>{try{l(f)}catch(d){this.onError(d)}},"output"),error:o(f=>{f.stack=u,this.onError(f)},"error")}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(x(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(x(this.decoder),Wa()||LP(this.inputTimestamps,e.timestamp,r=>r),tp()&&this.currentPacketIndex===0&&this.codec==="avc"){let r=[];for(let i of jP(e.data,this.decoderConfig)){let s=Ao(e.data[i.offset]);s>=20&&s<=31||r.push(e.data.subarray(i.offset,i.offset+i.length))}let n=Qz(r,this.decoderConfig);e=new je(n,e.type,e.timestamp,e.duration)}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed){this.pushNullAlphaFrame();return}if(!this.merger)try{this.merger=new eI}catch(n){console.error("Due to an error, only color data will be decoded.",n),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let n=o(s=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let a=this.colorQueue.shift();x(a!==void 0),this.mergeAlpha(a,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let a=this.colorQueue.shift();x(a!==void 0),this.mergeAlpha(a,null)}else this.alphaQueue.push(null)},"alphaHandler"),i=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:o(s=>{try{n(s)}catch(a){this.onError(a)}},"output"),error:o(s=>{s.stack=i,this.onError(s)},"error")}),this.alphaDecoder.configure(this.decoderConfig)}let r=Ux(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=r==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(r??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let r of YP(e,this.decoderConfig)){let n=Gs(e[r.offset]);if(n===vt.RASL_N||n===vt.RASL_R)return!0}return!1}sampleHandler(e){if(Wa()){if(this.sampleQueue.length>0&&e.timestamp>=Ze(this.sampleQueue).timestamp){for(let r of this.sampleQueue)this.finalizeAndEmitSample(r);this.sampleQueue.length=0}LP(this.sampleQueue,e,r=>r.timestamp)}else{let r=this.inputTimestamps.shift();x(r!==void 0),e.setTimestamp(r),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,r){if(!r){let s=new ur(e);this.sampleHandler(s);return}x(this.merger),this.merger.update(e,r),e.close(),r.close();let n=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),i=new ur(n);this.sampleHandler(i)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(x(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Wa()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(x(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},eI=class{static{o(this,"ColorAlphaMerger")}constructor(){typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
2
2
|
in vec2 a_position;
|
|
3
3
|
in vec2 a_texCoord;
|
|
4
4
|
out vec2 v_texCoord;
|
|
@@ -20,13 +20,13 @@ var f2=Object.create;var Zl=Object.defineProperty;var d2=Object.getOwnPropertyDe
|
|
|
20
20
|
float alpha = texture(u_alphaTexture, v_texCoord).r;
|
|
21
21
|
fragColor = vec4(color, alpha);
|
|
22
22
|
}
|
|
23
|
-
`),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,r),this.gl.linkProgram(n),n}createShader(e,r){let n=this.gl.createShader(e);return this.gl.shaderSource(n,r),this.gl.compileShader(n),n}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let r=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,r,this.gl.STATIC_DRAW);let i=this.gl.getAttribLocation(this.program,"a_position"),s=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,r){(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}},Za=class extends id{static{o(this,"VideoSampleSink")}constructor(e){if(!(e instanceof Pn))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,r){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=this._track.codec,i=this._track.rotation,s=await this._track.getDecoderConfig(),a=this._track.timeResolution;return x(n&&s),new ZP(e,r,n,s,i,a)}_createPacketSink(){return new Ki(this._track)}async getSample(e){Lo(e);for await(let r of this.mediaSamplesAtTimestamps([e]))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,r=1/0){return this.mediaSamplesInRange(e,r)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},sd=class{static{o(this,"CanvasSink")}constructor(e,r={}){if(this._nextCanvasIndex=0,!(e instanceof Pn))throw new TypeError("videoTrack must be an InputVideoTrack.");if(r&&typeof r!="object")throw new TypeError("options must be an object.");if(r.alpha!==void 0&&typeof r.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(r.width!==void 0&&(!Number.isInteger(r.width)||r.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(r.height!==void 0&&(!Number.isInteger(r.height)||r.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(r.fit!==void 0&&!["fill","contain","cover"].includes(r.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(r.width!==void 0&&r.height!==void 0&&r.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(r.crop!==void 0&&yp(r.crop,"options."),r.poolSize!==void 0&&(typeof r.poolSize!="number"||!Number.isInteger(r.poolSize)||r.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");let n=r.rotation??e.rotation,[i,s]=n%180===0?[e.squarePixelWidth,e.squarePixelHeight]:[e.squarePixelHeight,e.squarePixelWidth],a=r.crop;a&&gp(a,i,s);let[c,l]=a?[a.width,a.height]:[i,s],u=c/l;r.width!==void 0&&r.height===void 0?(c=r.width,l=Math.round(c/u)):r.width===void 0&&r.height!==void 0?(l=r.height,c=Math.round(l*u)):r.width!==void 0&&r.height!==void 0&&(c=r.width,l=r.height),this._videoTrack=e,this._alpha=r.alpha??!1,this._width=c,this._height=l,this._rotation=n,this._crop=a,this._fit=r.fit??"fill",this._videoSampleSink=new Za(e),this._canvasPool=Array.from({length:r.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let r=this._canvasPool[this._nextCanvasIndex],n=!1;r||(typeof document<"u"?(r=document.createElement("canvas"),r.width=this._width,r.height=this._height):r=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=r),n=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let i=r.getContext("2d",{alpha:this._alpha||Vs()});x(i),i.resetTransform(),n||(!this._alpha&&Vs()?(i.fillStyle="black",i.fillRect(0,0,this._width,this._height)):i.clearRect(0,0,this._width,this._height)),e.drawWithFit(i,{fit:this._fit,rotation:this._rotation,crop:this._crop});let s={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),s}async getCanvas(e){Lo(e);let r=await this._videoSampleSink.getSample(e);return r&&this._videoSampleToWrappedCanvas(r)}canvases(e=0,r=1/0){return Zm(this._videoSampleSink.samples(e,r),n=>this._videoSampleToWrappedCanvas(n))}canvasesAtTimestamps(e){return Zm(this._videoSampleSink.samplesAtTimestamps(e),r=>r&&this._videoSampleToWrappedCanvas(r))}},tI=class extends wp{static{o(this,"AudioDecoderWrapper")}constructor(e,r,n,i){super(e,r),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new $a,this.customDecoderQueueSize=0,this.currentTimestamp=null;let s=o(c=>{(this.currentTimestamp===null||Math.abs(c.timestamp-this.currentTimestamp)>=c.duration)&&(this.currentTimestamp=c.timestamp);let l=this.currentTimestamp;if(this.currentTimestamp+=c.duration,c.numberOfFrames===0){c.close();return}let u=i.sampleRate;c.setTimestamp(Math.round(l*u)/u),e(c)},"sampleHandler"),a=td.find(c=>c.supports(n,i));if(a)this.customDecoder=new a,this.customDecoder.codec=n,this.customDecoder.config=i,this.customDecoder.onSample=c=>{if(!(c instanceof Dr))throw new TypeError("The argument passed to onSample must be an AudioSample.");s(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:o(l=>{try{s(new Dr(l))}catch(u){this.onError(u)}},"output"),error:o(l=>{l.stack=c,this.onError(l)},"error")}),this.decoder.configure(i)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(x(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(x(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(x(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(x(this.decoder),this.decoder.close())}},rI=class extends wp{static{o(this,"PcmAudioDecoderWrapper")}constructor(e,r,n){super(e,r),this.decoderConfig=n,this.currentTimestamp=null,x(ht.includes(n.codec)),this.codec=n.codec;let{dataType:i,sampleSize:s,littleEndian:a}=_r(this.codec);switch(this.inputSampleSize=s,s){case 1:i==="unsigned"?this.readInputValue=(c,l)=>c.getUint8(l)-2**7:i==="signed"?this.readInputValue=(c,l)=>c.getInt8(l):i==="ulaw"?this.readInputValue=(c,l)=>oU(c.getUint8(l)):i==="alaw"?this.readInputValue=(c,l)=>cU(c.getUint8(l)):x(!1);break;case 2:i==="unsigned"?this.readInputValue=(c,l)=>c.getUint16(l,a)-2**15:i==="signed"?this.readInputValue=(c,l)=>c.getInt16(l,a):x(!1);break;case 3:i==="unsigned"?this.readInputValue=(c,l)=>_l(c,l,a)-2**23:i==="signed"?this.readInputValue=(c,l)=>kz(c,l,a):x(!1);break;case 4:i==="unsigned"?this.readInputValue=(c,l)=>c.getUint32(l,a)-2**31:i==="signed"?this.readInputValue=(c,l)=>c.getInt32(l,a):i==="float"?this.readInputValue=(c,l)=>c.getFloat32(l,a):x(!1);break;case 8:i==="float"?this.readInputValue=(c,l)=>c.getFloat64(l,a):x(!1);break;default:kt(s),x(!1)}switch(s){case 1:i==="ulaw"||i==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,l,u)=>c.setInt16(l,u,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(c,l,u)=>c.setUint8(l,u+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,l,u)=>c.setInt16(l,u,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(c,l,u)=>c.setInt32(l,u<<8,!0);break;case 4:this.outputSampleSize=4,i==="float"?(this.outputFormat="f32",this.writeOutputValue=(c,l,u)=>c.setFloat32(l,u,!0)):(this.outputFormat="s32",this.writeOutputValue=(c,l,u)=>c.setInt32(l,u,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(c,l,u)=>c.setFloat32(l,u,!0);break;default:kt(s),x(!1)}}getDecodeQueueSize(){return 0}decode(e){let r=ge(e.data),n=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,i=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(i),a=new DataView(s);for(let f=0;f<n*this.decoderConfig.numberOfChannels;f++){let d=f*this.inputSampleSize,h=f*this.outputSampleSize,m=this.readInputValue(r,d);this.writeOutputValue(a,h,m)}let c=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=c)&&(this.currentTimestamp=e.timestamp);let l=this.currentTimestamp;this.currentTimestamp+=c;let u=new Dr({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:l});this.onSample(u)}async flush(){}close(){}},ec=class extends id{static{o(this,"AudioSampleSink")}constructor(e){if(!(e instanceof Et))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,r){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=this._track.codec,i=await this._track.getDecoderConfig();return x(n&&i),ht.includes(i.codec)?new rI(e,r,i):new tI(e,r,n,i)}_createPacketSink(){return new Ki(this._track)}async getSample(e){Lo(e);for await(let r of this.mediaSamplesAtTimestamps([e]))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,r=1/0){return this.mediaSamplesInRange(e,r)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},qx=class{static{o(this,"AudioBufferSink")}constructor(e){if(!(e instanceof Et))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new ec(e)}_audioSampleToWrappedArrayBuffer(e){let r={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),r}async getBuffer(e){Lo(e);let r=await this._audioSampleSink.getSample(e);return r&&this._audioSampleToWrappedArrayBuffer(r)}buffers(e=0,r=1/0){return Zm(this._audioSampleSink.samples(e,r),n=>this._audioSampleToWrappedArrayBuffer(n))}buffersAtTimestamps(e){return Zm(this._audioSampleSink.samplesAtTimestamps(e),r=>r&&this._audioSampleToWrappedArrayBuffer(r))}}});var tc,Pn,Et,Xi=he(()=>{sn();rd();Yx();Ue();Qn();tc=class{static{o(this,"InputTrack")}constructor(e,r){this.input=e,this._backing=r}isVideoTrack(){return this instanceof Pn}isAudioTrack(){return this instanceof Et}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){let r=new Ki(this),n=1/0,i=-1/0,s=0,a=0;for await(let c of r.packets(void 0,void 0,{metadataOnly:!0})){if(s>=e&&c.timestamp>=i)break;n=Math.min(n,c.timestamp),i=Math.max(i,c.timestamp+c.duration),s++,a+=c.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(i-n)).toPrecision(16)):0,averageBitrate:s?Number((8*a/(i-n)).toPrecision(16)):0}}},Pn=class extends tc{static{o(this,"InputVideoTrack")}constructor(e,r){super(e,r),this._backing=r,this.pixelAspectRatio=qa({num:this._backing.getSquarePixelWidth()*this._backing.getCodedHeight(),den:this._backing.getSquarePixelHeight()*this._backing.getCodedWidth()})}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get squarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelHeight(){return this._backing.getSquarePixelHeight()}get displayWidth(){return this._backing.getRotation()%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this._backing.getRotation()%180===0?this.squarePixelHeight:this.squarePixelWidth}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pg"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let r=this._backing.getCodec();return x(r!==null),ed.some(i=>i.supports(r,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof je))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(this.codec===null)return null;let r=await this.getDecoderConfig();return x(r),Ux(this.codec,r,e.data)}},Et=class extends tc{static{o(this,"InputAudioTrack")}constructor(e,r){super(e,r),this._backing=r}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let r=this._backing.getCodec();return x(r!==null),td.some(n=>n.supports(r,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof je))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}}});var Gx,nI=he(()=>{Gx=o(t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");if(t.codecStrings.length>0){let n=[...new Set(t.codecStrings)];r+=`; codecs="${n.join(", ")}"`}return r},"buildIsobmffMimeType")});var Ji,zo,Uo,rc,Qx,Kx,Zi,pU,iI=he(()=>{lr();Ue();qt();Ji=8,zo=16,Uo=o(t=>{let e=X(t),r=It(t,4),n=8;e===1&&(e=Kn(t),n=16);let s=e-n;return s<0?null:{name:r,totalSize:e,headerSize:n,contentSize:s}},"readBoxHeader"),rc=o(t=>Bo(t)/65536,"readFixed_16_16"),Qx=o(t=>Bo(t)/1073741824,"readFixed_2_30"),Kx=o(t=>{let e=0;for(let r=0;r<4;r++){e<<=7;let n=oe(t);if(e|=n&127,(n&128)===0)break}return e},"readIsomVariableInteger"),Zi=o(t=>{let e=jt(t);return t.skip(2),e=Math.min(e,t.remainingLength),br.decode(se(t,e))},"readMetadataStringShort"),pU=o(t=>{let e=Uo(t);if(!e||e.name!=="data"||t.remainingLength<8)return null;let r=X(t);t.skip(4);let n=se(t,e.contentSize-8);switch(r){case 1:return br.decode(n);case 2:return new TextDecoder("utf-16be").decode(n);case 13:return new Gn(n,"image/jpeg");case 14:return new Gn(n,"image/png");case 27:return new Gn(n,"image/bmp");default:return n}},"readDataBox")});var Jx,Xx,sI,oI,aI,Dee,Mee,Oee,cI,Ree,gU,yU=he(()=>{qs();Zt();sn();Fo();Xi();Ue();Qn();nI();iI();qt();lr();Ox();Ti();Jx=class extends wr{static{o(this,"IsobmffDemuxer")}constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...r)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(r=>r.inputTrack.getCodecParameterString()));return Gx({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(r=>r.info?.type==="video"),hasAudio:this.tracks.some(r=>r.info?.type==="audio"),codecStrings:e.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,Ji,zo);if(r instanceof Promise&&(r=await r),!r)break;let n=e,i=Uo(r);if(!i)break;if(i.name==="ftyp"){let s=It(r,4);this.isQuickTime=s==="qt "}else if(i.name==="moov"){let s=this.reader.requestSlice(r.filePos,i.contentSize);if(s instanceof Promise&&(s=await s),!s)break;this.moovSlice=s,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((a,c)=>Number(c.disposition.default)-Number(a.disposition.default));for(let a of this.tracks){let c=a.editListPreviousSegmentDurations/this.movieTimescale;a.editListOffset-=Math.round(c*a.timescale)}break}e=n+i.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let r=this.reader.requestSlice(this.reader.fileSize-4,4);r instanceof Promise&&(r=await r),x(r);let n=X(r),i=this.reader.fileSize-n;if(i>=0&&i<=this.reader.fileSize-zo){let s=this.reader.requestSliceRange(i,Ji,zo);if(s instanceof Promise&&(s=await s),s){let a=Uo(s);if(a&&a.name==="mfra"){let c=this.reader.requestSlice(s.filePos,a.contentSize);c instanceof Promise&&(c=await c),c&&this.readContiguousBoxes(c)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=r,x(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&ht.includes(e.info.codec)&&r.sampleCompositionTimeOffsets.length===0){x(e.info?.type==="audio");let s=_r(e.info.codec),a=[],c=[];for(let l=0;l<r.sampleToChunk.length;l++){let u=r.sampleToChunk[l],f=r.sampleToChunk[l+1],d=(f?f.startChunkIndex:r.chunkOffsets.length)-u.startChunkIndex;for(let h=0;h<d;h++){let m=u.startSampleIndex+h*u.samplesPerChunk,p=m+u.samplesPerChunk,g=ze(r.sampleTimingEntries,m,P=>P.startIndex),y=r.sampleTimingEntries[g],b=ze(r.sampleTimingEntries,p,P=>P.startIndex),w=r.sampleTimingEntries[b],k=y.startDecodeTimestamp+(m-y.startIndex)*y.delta,v=w.startDecodeTimestamp+(p-w.startIndex)*w.delta-k,S=Ze(a);S&&S.delta===v?S.count++:a.push({startIndex:u.startChunkIndex+h,startDecodeTimestamp:k,count:1,delta:v});let M=u.samplesPerChunk*s.sampleSize*e.info.numberOfChannels;c.push(M)}u.startSampleIndex=u.startChunkIndex,u.samplesPerChunk=1}r.sampleTimingEntries=a,r.sampleSizes=c}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(let s of r.sampleTimingEntries)for(let a=0;a<s.count;a++)r.presentationTimestamps.push({presentationTimestamp:s.startDecodeTimestamp+a*s.delta,sampleIndex:s.startIndex+a});for(let s of r.sampleCompositionTimeOffsets)for(let a=0;a<s.count;a++){let c=s.startIndex+a,l=r.presentationTimestamps[c];l&&(l.presentationTimestamp+=s.offset)}r.presentationTimestamps.sort((s,a)=>s.presentationTimestamp-a.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let s=0;s<r.presentationTimestamps.length;s++)r.presentationTimestampIndexMap[r.presentationTimestamps[s].sampleIndex]=s}return r}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let r=this.reader.requestSliceRange(e,Ji,zo);r instanceof Promise&&(r=await r),x(r);let n=Uo(r);x(n?.name==="moof");let i=this.reader.requestSlice(e,n.totalSize);i instanceof Promise&&(i=await i),x(i),this.traverseBox(i);let s=this.lastReadFragment;x(s&&s.moofOffset===e);for(let[,a]of s.trackData){let c=a.track,{fragmentPositionCache:l}=c;if(!a.startTimestampIsFinal){let f=c.fragmentLookupTable.find(d=>d.moofOffset===s.moofOffset);if(f)cI(a,f.timestamp);else{let d=ze(l,s.moofOffset-1,h=>h.moofOffset);if(d!==-1){let h=l[d];cI(a,h.endTimestamp)}}a.startTimestampIsFinal=!0}let u=ze(l,a.startTimestamp,f=>f.startTimestamp);(u===-1||l[u].moofOffset!==s.moofOffset)&&l.splice(u+1,0,{moofOffset:s.moofOffset,startTimestamp:a.startTimestamp,endTimestamp:a.endTimestamp})}return s}readContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-Ji&&this.traverseBox(e););}*iterateContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-Ji;){let n=e.filePos,i=Uo(e);if(!i)break;yield{boxInfo:i,slice:e},e.filePos=n+i.totalSize}}traverseBox(e){let r=e.filePos,n=Uo(e);if(!n)return!1;let i=e.filePos,s=r+n.totalSize;switch(n.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"mvhd":{let a=oe(e);e.skip(3),a===1?(e.skip(16),this.movieTimescale=X(e),this.movieDurationInTimescale=Kn(e)):(e.skip(8),this.movieTimescale=X(e),this.movieDurationInTimescale=X(e))}break;case"trak":{let a={id:-1,demuxer:this,inputTrack:null,disposition:{...jr},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Ft,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=a,this.readContiguousBoxes(e.slice(i,n.contentSize)),a.id!==-1&&a.timescale!==-1&&a.info!==null){if(a.info.type==="video"&&a.info.width!==-1){let c=a;a.inputTrack=new Pn(this.input,new sI(c)),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){let c=a;a.inputTrack=new Et(this.input,new oI(c)),this.tracks.push(a)}}this.currentTrack=null}break;case"tkhd":{let a=this.currentTrack;if(!a)break;let c=oe(e),u=!!(nc(e)&1);if(a.disposition.default=u,c===0)e.skip(8),a.id=X(e),e.skip(4),a.durationInMovieTimescale=X(e);else if(c===1)e.skip(16),a.id=X(e),e.skip(4),a.durationInMovieTimescale=Kn(e);else throw new Error(`Incorrect track header version ${c}.`);e.skip(16);let f=[rc(e),rc(e),Qx(e),rc(e),rc(e),Qx(e),rc(e),rc(e),Qx(e)],d=Ha(ep(Ree(f),90));x(d===0||d===90||d===180||d===270),a.rotation=d}break;case"elst":{let a=this.currentTrack;if(!a)break;let c=oe(e);e.skip(3);let l=!1,u=0,f=X(e);for(let d=0;d<f;d++){let h=c===1?Kn(e):X(e),m=c===1?bU(e):Bo(e),p=rc(e);if(h!==0){if(l){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(m===-1){u+=h;continue}if(p!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}a.editListPreviousSegmentDurations=u,a.editListOffset=m,l=!0}}}break;case"mdhd":{let a=this.currentTrack;if(!a)break;let c=oe(e);e.skip(3),c===0?(e.skip(8),a.timescale=X(e),a.durationInMediaTimescale=X(e)):c===1&&(e.skip(16),a.timescale=X(e),a.durationInMediaTimescale=Kn(e));let l=jt(e);if(l>0){a.languageCode="";for(let u=0;u<3;u++)a.languageCode=String.fromCharCode(96+(l&31))+a.languageCode,l>>=5;Mo(a.languageCode)||(a.languageCode=Ft)}}break;case"hdlr":{let a=this.currentTrack;if(!a)break;e.skip(8);let c=It(e,4);c==="vide"?a.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:c==="soun"&&(a.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=r,this.readContiguousBoxes(e.slice(i,n.contentSize))}break;case"stsd":{let a=this.currentTrack;if(!a||a.info===null||a.sampleTable)break;let c=oe(e);e.skip(3);let l=X(e);for(let u=0;u<l;u++){let f=e.filePos,d=Uo(e);if(!d)break;a.internalCodecId=d.name;let h=d.name.toLowerCase();if(a.info.type==="video")h==="avc1"||h==="avc3"?(a.info.codec="avc",a.info.avcType=h==="avc1"?1:3):h==="hvc1"||h==="hev1"?a.info.codec="hevc":h==="vp08"?a.info.codec="vp8":h==="vp09"?a.info.codec="vp9":h==="av01"?a.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${d.name}').`),e.skip(24),a.info.width=jt(e),a.info.height=jt(e),a.info.squarePixelWidth=a.info.width,a.info.squarePixelHeight=a.info.height,e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,f+d.totalSize-e.filePos));else{h==="mp4a"||(h==="opus"?a.info.codec="opus":h==="flac"?a.info.codec="flac":h==="twos"||h==="sowt"||h==="raw "||h==="in24"||h==="in32"||h==="fl32"||h==="fl64"||h==="lpcm"||h==="ipcm"||h==="fpcm"||(h==="ulaw"?a.info.codec="ulaw":h==="alaw"?a.info.codec="alaw":h==="ac-3"?a.info.codec="ac3":h==="ec-3"?a.info.codec="eac3":console.warn(`Unsupported audio codec (sample entry type '${d.name}').`))),e.skip(8);let m=jt(e);e.skip(6);let p=jt(e),g=jt(e);e.skip(4);let y=X(e)/65536;if(c===0&&m>0){if(m===1)e.skip(4),g=8*X(e),e.skip(8);else if(m===2){e.skip(4),y=Zx(e),p=X(e),e.skip(4),g=X(e);let b=X(e);if(e.skip(8),h==="lpcm"){let w=g+7>>3,k=!!(b&1),T=!!(b&2),v=b&4?-1:0;g>0&&g<=64&&(k?g===32&&(a.info.codec=T?"pcm-f32be":"pcm-f32"):v&1<<w-1?w===1?a.info.codec="pcm-s8":w===2?a.info.codec=T?"pcm-s16be":"pcm-s16":w===3?a.info.codec=T?"pcm-s24be":"pcm-s24":w===4&&(a.info.codec=T?"pcm-s32be":"pcm-s32"):w===1&&(a.info.codec="pcm-u8")),a.info.codec===null&&console.warn("Unsupported PCM format.")}}}a.info.codec==="opus"&&(y=Qi),a.info.numberOfChannels=p,a.info.sampleRate=y,h==="twos"?g===8?a.info.codec="pcm-s8":g===16?a.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${g} for codec 'twos'.`),a.info.codec=null):h==="sowt"?g===8?a.info.codec="pcm-s8":g===16?a.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${g} for codec 'sowt'.`),a.info.codec=null):h==="raw "?a.info.codec="pcm-u8":h==="in24"?a.info.codec="pcm-s24be":h==="in32"?a.info.codec="pcm-s32be":h==="fl32"?a.info.codec="pcm-f32be":h==="fl64"?a.info.codec="pcm-f64be":h==="ipcm"?a.info.codec="pcm-s16be":h==="fpcm"&&(a.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,f+d.totalSize-e.filePos))}}}break;case"avcC":{let a=this.currentTrack;if(!a)break;x(a.info),a.info.codecDescription=se(e,n.contentSize)}break;case"hvcC":{let a=this.currentTrack;if(!a)break;x(a.info),a.info.codecDescription=se(e,n.contentSize)}break;case"vpcC":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="video"),e.skip(4);let c=oe(e),l=oe(e),u=oe(e),f=u>>4,d=u>>1&7,h=u&1,m=oe(e),p=oe(e),g=oe(e);a.info.vp9CodecInfo={profile:c,level:l,bitDepth:f,chromaSubsampling:d,videoFullRangeFlag:h,colourPrimaries:m,transferCharacteristics:p,matrixCoefficients:g}}break;case"av1C":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="video"),e.skip(1);let c=oe(e),l=c>>5,u=c&31,f=oe(e),d=f>>7,h=f>>6&1,m=f>>5&1,p=f>>4&1,g=f>>3&1,y=f>>2&1,b=f&3,w=l===2&&h?m?12:10:h?10:8;a.info.av1CodecInfo={profile:l,level:u,tier:d,bitDepth:w,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:y,chromaSamplePosition:b}}break;case"colr":{let a=this.currentTrack;if(!a||(x(a.info?.type==="video"),It(e,4)!=="nclx"))break;let l=jt(e),u=jt(e),f=jt(e),d=!!(oe(e)&128);a.info.colorSpace={primaries:Cl[l],transfer:Pl[u],matrix:Il[f],fullRange:d}}break;case"pasp":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="video");let c=X(e),l=X(e);c>l?a.info.squarePixelWidth=Math.round(a.info.width*c/l):a.info.squarePixelHeight=Math.round(a.info.height*l/c)}break;case"wave":this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"esds":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="audio"),e.skip(4);let c=oe(e);x(c===3),Kx(e),e.skip(2);let l=oe(e),u=(l&128)!==0,f=(l&64)!==0,d=(l&32)!==0;if(u&&e.skip(2),f){let y=oe(e);e.skip(y)}d&&e.skip(2);let h=oe(e);x(h===4);let m=Kx(e),p=e.filePos,g=oe(e);if(g===64||g===103?(a.info.codec="aac",a.info.aacCodecInfo={isMpeg2:g===103,objectType:null}):g===105||g===107?a.info.codec="mp3":g===221?a.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${g}) - discarding track.`),e.skip(12),m>e.filePos-p){let y=oe(e);x(y===5);let b=Kx(e);if(a.info.codecDescription=se(e,b),a.info.codec==="aac"){let w=js(a.info.codecDescription);w.numberOfChannels!==null&&(a.info.numberOfChannels=w.numberOfChannels),w.sampleRate!==null&&(a.info.sampleRate=w.sampleRate)}}}break;case"enda":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="audio"),jt(e)&255&&(a.info.codec==="pcm-s16be"?a.info.codec="pcm-s16":a.info.codec==="pcm-s24be"?a.info.codec="pcm-s24":a.info.codec==="pcm-s32be"?a.info.codec="pcm-s32":a.info.codec==="pcm-f32be"?a.info.codec="pcm-f32":a.info.codec==="pcm-f64be"&&(a.info.codec="pcm-f64"))}break;case"pcmC":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="audio"),e.skip(4);let l=!!(oe(e)&1),u=oe(e);a.info.codec==="pcm-s16be"?l?u===16?a.info.codec="pcm-s16":u===24?a.info.codec="pcm-s24":u===32?a.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${u}.`),a.info.codec=null):u===16?a.info.codec="pcm-s16be":u===24?a.info.codec="pcm-s24be":u===32?a.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${u}.`),a.info.codec=null):a.info.codec==="pcm-f32be"&&(l?u===32?a.info.codec="pcm-f32":u===64?a.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${u}.`),a.info.codec=null):u===32?a.info.codec="pcm-f32be":u===64?a.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${u}.`),a.info.codec=null));break}case"dOps":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="audio"),e.skip(1);let c=oe(e),l=jt(e),u=X(e),f=xp(e),d=oe(e),h;d!==0?h=se(e,2+c):h=new Uint8Array(0);let m=new Uint8Array(19+h.byteLength),p=new DataView(m.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,c),p.setUint16(10,l,!0),p.setUint32(12,u,!0),p.setInt16(16,f,!0),p.setUint8(18,d),m.set(h,19),a.info.codecDescription=m,a.info.numberOfChannels=c}break;case"dfLa":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="audio"),e.skip(4);let c=127,l=128,u=e.filePos;for(;e.filePos<s;){let p=oe(e),g=nc(e);if((p&c)===Ei.STREAMINFO){e.skip(10);let b=X(e),w=b>>>12,k=(b>>9&7)+1;a.info.sampleRate=w,a.info.numberOfChannels=k,e.skip(20)}else e.skip(g);if(p&l)break}let f=e.filePos;e.filePos=u;let d=se(e,f-u),h=new Uint8Array(4+d.byteLength);new DataView(h.buffer).setUint32(0,1716281667,!1),h.set(d,4),a.info.codecDescription=h}break;case"dac3":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="audio");let c=se(e,3),l=new Te(c),u=l.readBits(2);l.skipBits(8);let f=l.readBits(3),d=l.readBits(1);u<3&&(a.info.sampleRate=Rl[u]),a.info.numberOfChannels=ap[f]+d}break;case"dec3":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="audio");let c=se(e,n.contentSize),l=rU(c);if(!l){console.warn("Invalid dec3 box contents, ignoring.");break}let u=Vx(l);u!==null&&(a.info.sampleRate=u),a.info.numberOfChannels=Wx(l)}break;case"stts":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let c=X(e),l=0,u=0;for(let f=0;f<c;f++){let d=X(e),h=X(e);a.sampleTable.sampleTimingEntries.push({startIndex:l,startDecodeTimestamp:u,count:d,delta:h}),l+=d,u+=d*h}}break;case"ctts":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let c=X(e),l=0;for(let u=0;u<c;u++){let f=X(e),d=Bo(e);a.sampleTable.sampleCompositionTimeOffsets.push({startIndex:l,count:f,offset:d}),l+=f}}break;case"stsz":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let c=X(e),l=X(e);if(c===0)for(let u=0;u<l;u++){let f=X(e);a.sampleTable.sampleSizes.push(f)}else a.sampleTable.sampleSizes.push(c)}break;case"stz2":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),e.skip(3);let c=oe(e),l=X(e),u=se(e,Math.ceil(l*c/8)),f=new Te(u);for(let d=0;d<l;d++){let h=f.readBits(c);a.sampleTable.sampleSizes.push(h)}}break;case"stss":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),a.sampleTable.keySampleIndices=[];let c=X(e);for(let l=0;l<c;l++){let u=X(e)-1;a.sampleTable.keySampleIndices.push(u)}a.sampleTable.keySampleIndices[0]!==0&&a.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let c=X(e);for(let u=0;u<c;u++){let f=X(e)-1,d=X(e),h=X(e);a.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:f,samplesPerChunk:d,sampleDescriptionIndex:h})}let l=0;for(let u=0;u<a.sampleTable.sampleToChunk.length;u++)if(a.sampleTable.sampleToChunk[u].startSampleIndex=l,u<a.sampleTable.sampleToChunk.length-1){let d=a.sampleTable.sampleToChunk[u+1].startChunkIndex-a.sampleTable.sampleToChunk[u].startChunkIndex;l+=d*a.sampleTable.sampleToChunk[u].samplesPerChunk}}break;case"stco":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let c=X(e);for(let l=0;l<c;l++){let u=X(e);a.sampleTable.chunkOffsets.push(u)}}break;case"co64":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let c=X(e);for(let l=0;l<c;l++){let u=Kn(e);a.sampleTable.chunkOffsets.push(u)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"mehd":{let a=oe(e);e.skip(3);let c=a===1?Kn(e):X(e);this.movieDurationInTimescale=c}break;case"trex":{e.skip(4);let a=X(e),c=X(e),l=X(e),u=X(e),f=X(e);this.fragmentTrackDefaults.push({trackId:a,defaultSampleDescriptionIndex:c,defaultSampleDuration:l,defaultSampleSize:u,defaultSampleFlags:f})}break;case"tfra":{let a=oe(e);e.skip(3);let c=X(e),l=this.tracks.find(w=>w.id===c);if(!l)break;let u=X(e),f=(u&48)>>4,d=(u&12)>>2,h=u&3,m=[oe,jt,nc,X],p=m[f],g=m[d],y=m[h],b=X(e);for(let w=0;w<b;w++){let k=a===1?Kn(e):X(e),T=a===1?Kn(e):X(e);p(e),g(e),y(e),l.fragmentLookupTable.push({timestamp:k,moofOffset:T})}l.fragmentLookupTable.sort((w,k)=>w.timestamp-k.timestamp);for(let w=0;w<l.fragmentLookupTable.length-1;w++){let k=l.fragmentLookupTable[w],T=l.fragmentLookupTable[w+1];k.timestamp===T.timestamp&&(l.fragmentLookupTable.splice(w+1,1),w--)}}break;case"moof":this.currentFragment={moofOffset:r,moofSize:n.totalSize,implicitBaseDataOffset:r,trackData:new Map},this.readContiguousBoxes(e.slice(i,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(x(this.currentFragment),this.readContiguousBoxes(e.slice(i,n.contentSize)),this.currentTrack){let a=this.currentFragment.trackData.get(this.currentTrack.id);if(a){let{currentFragmentState:c}=this.currentTrack;x(c),c.startTimestamp!==null&&(cI(a,c.startTimestamp),a.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{x(this.currentFragment),e.skip(1);let a=nc(e),c=!!(a&1),l=!!(a&2),u=!!(a&8),f=!!(a&16),d=!!(a&32),h=!!(a&65536),m=!!(a&131072),p=X(e),g=this.tracks.find(b=>b.id===p);if(!g)break;let y=this.fragmentTrackDefaults.find(b=>b.trackId===p);this.currentTrack=g,g.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:y?.defaultSampleDescriptionIndex??null,defaultSampleDuration:y?.defaultSampleDuration??null,defaultSampleSize:y?.defaultSampleSize??null,defaultSampleFlags:y?.defaultSampleFlags??null,startTimestamp:null},c?g.currentFragmentState.baseDataOffset=Kn(e):m&&(g.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),l&&(g.currentFragmentState.sampleDescriptionIndex=X(e)),u&&(g.currentFragmentState.defaultSampleDuration=X(e)),f&&(g.currentFragmentState.defaultSampleSize=X(e)),d&&(g.currentFragmentState.defaultSampleFlags=X(e)),h&&(g.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let a=this.currentTrack;if(!a)break;x(a.currentFragmentState);let c=oe(e);e.skip(3);let l=c===0?X(e):Kn(e);a.currentFragmentState.startTimestamp=l}break;case"trun":{let a=this.currentTrack;if(!a)break;if(x(this.currentFragment),x(a.currentFragmentState),this.currentFragment.trackData.has(a.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let c=oe(e),l=nc(e),u=!!(l&1),f=!!(l&4),d=!!(l&256),h=!!(l&512),m=!!(l&1024),p=!!(l&2048),g=X(e),y=a.currentFragmentState.baseDataOffset;u&&(y+=Bo(e));let b=null;f&&(b=X(e));let w=y;if(g===0){this.currentFragment.implicitBaseDataOffset=w;break}let k=0,T={track:a,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(a.id,T);for(let M=0;M<g;M++){let P;d?P=X(e):(x(a.currentFragmentState.defaultSampleDuration!==null),P=a.currentFragmentState.defaultSampleDuration);let N;h?N=X(e):(x(a.currentFragmentState.defaultSampleSize!==null),N=a.currentFragmentState.defaultSampleSize);let O;m?O=X(e):(x(a.currentFragmentState.defaultSampleFlags!==null),O=a.currentFragmentState.defaultSampleFlags),M===0&&b!==null&&(O=b);let Y=0;p&&(c===0?Y=X(e):Y=Bo(e));let A=!(O&65536);T.samples.push({presentationTimestamp:k+Y,duration:P,byteOffset:w,byteSize:N,isKeyFrame:A}),w+=N,k+=P}T.presentationTimestamps=T.samples.map((M,P)=>({presentationTimestamp:M.presentationTimestamp,sampleIndex:P})).sort((M,P)=>M.presentationTimestamp-P.presentationTimestamp);for(let M=0;M<T.presentationTimestamps.length;M++){let P=T.presentationTimestamps[M],N=T.samples[P.sampleIndex];if(T.firstKeyFrameTimestamp===null&&N.isKeyFrame&&(T.firstKeyFrameTimestamp=N.presentationTimestamp),M<T.presentationTimestamps.length-1){let O=T.presentationTimestamps[M+1];N.duration=O.presentationTimestamp-P.presentationTimestamp}}let v=T.samples[T.presentationTimestamps[0].sampleIndex],S=T.samples[Ze(T.presentationTimestamps).sampleIndex];T.startTimestamp=v.presentationTimestamp,T.endTimestamp=S.presentationTimestamp+S.duration,this.currentFragment.implicitBaseDataOffset=w}break;case"udta":{let a=this.iterateContiguousBoxes(e.slice(i,n.contentSize));for(let{boxInfo:c,slice:l}of a){if(c.name!=="meta"&&!this.currentTrack){let u=l.filePos;this.metadataTags.raw??={},c.name[0]==="\xA9"?this.metadataTags.raw[c.name]??=Zi(l):this.metadataTags.raw[c.name]??=se(l,c.contentSize),l.filePos=u}switch(c.name){case"meta":l.skip(-c.headerSize),this.traverseBox(l);break;case"\xA9nam":case"name":this.currentTrack?this.currentTrack.name=br.decode(se(l,c.contentSize)):this.metadataTags.title??=Zi(l);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=Zi(l));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=Zi(l));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=Zi(l));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Zi(l));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=Zi(l));break;case"\xA9day":if(!this.currentTrack){let u=new Date(Zi(l));Number.isNaN(u.getTime())||(this.metadataTags.date??=u)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=Zi(l));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=Zi(l));break}}}break;case"meta":{if(this.currentTrack)break;let c=X(e)!==0;this.currentMetadataKeys=new Map,c?this.readContiguousBoxes(e.slice(i,n.contentSize)):this.readContiguousBoxes(e.slice(i+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let a=X(e);for(let c=0;c<a;c++){let l=X(e);e.skip(4);let u=br.decode(se(e,l-8));this.currentMetadataKeys.set(c+1,u)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let a=this.iterateContiguousBoxes(e.slice(i,n.contentSize));for(let{boxInfo:c,slice:l}of a){let u=c.name,f=(u.charCodeAt(0)<<24)+(u.charCodeAt(1)<<16)+(u.charCodeAt(2)<<8)+u.charCodeAt(3);this.currentMetadataKeys.has(f)&&(u=this.currentMetadataKeys.get(f));let d=pU(l);switch(this.metadataTags.raw??={},this.metadataTags.raw[u]??=d,u){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof d=="string"&&(this.metadataTags.title??=d);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof d=="string"&&(this.metadataTags.description??=d);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof d=="string"&&(this.metadataTags.artist??=d);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof d=="string"&&(this.metadataTags.album??=d);break;case"aART":case"album_artist":typeof d=="string"&&(this.metadataTags.albumArtist??=d);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof d=="string"&&(this.metadataTags.comment??=d);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof d=="string"&&(this.metadataTags.genre??=d);break;case"\xA9lyr":case"lyrics":typeof d=="string"&&(this.metadataTags.lyrics??=d);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof d=="string"){let h=new Date(d);Number.isNaN(h.getTime())||(this.metadataTags.date??=h)}break;case"covr":case"com.apple.quicktime.artwork":d instanceof Gn?(this.metadataTags.images??=[],this.metadataTags.images.push({data:d.data,kind:"coverFront",mimeType:d.mimeType})):d instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:d,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof d=="string"){let h=d.split("/"),m=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(m)&&m>0&&(this.metadataTags.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(d instanceof Uint8Array&&d.length>=6){let h=ge(d),m=h.getUint16(2,!1),p=h.getUint16(4,!1);m>0&&(this.metadataTags.trackNumber??=m),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(d instanceof Uint8Array&&d.length>=6){let h=ge(d),m=h.getUint16(2,!1),p=h.getUint16(4,!1);m>0&&(this.metadataTags.discNumber??=m),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=s,!0}},Xx=class{static{o(this,"IsobmffTrackBacking")}constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,n=this.internalTrack.inputTrack.type,i=0;for(let s of e.tracks)if(s.inputTrack.type===n&&i++,s===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){let r=await this.fetchPacketForSampleIndex(0,e);return r||!this.internalTrack.demuxer.isFragmented?r:this.performFragmentedLookup(null,n=>n.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Do(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,r){let n=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=aI(i,n),a=await this.fetchPacketForSampleIndex(s,r);return!gU(i)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,c=>{let l=c.trackData.get(this.internalTrack.id);if(!l)return{sampleIndex:-1,correctSampleFound:!1};let u=ze(l.presentationTimestamps,n,h=>h.presentationTimestamp),f=u!==-1?l.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&n<l.endTimestamp;return{sampleIndex:f,correctSampleFound:d}},n,n,r)}async getNextPacket(e,r){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,r);let i=this.packetToFragmentLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,s=>{if(s===i.fragment){let a=s.trackData.get(this.internalTrack.id);if(i.sampleIndex+1<a.samples.length)return{sampleIndex:i.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,r)}async getKeyPacket(e,r){let n=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Dee(i,n),a=await this.fetchPacketForSampleIndex(s,r);return!gU(i)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,c=>{let l=c.trackData.get(this.internalTrack.id);if(!l)return{sampleIndex:-1,correctSampleFound:!1};let u=qf(l.presentationTimestamps,h=>l.samples[h.sampleIndex].isKeyFrame&&h.presentationTimestamp<=n),f=u!==-1?l.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&n<l.endTimestamp;return{sampleIndex:f,correctSampleFound:d}},n,n,r)}async getNextKeyPacket(e,r){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Oee(s,n);return this.fetchPacketForSampleIndex(a,r)}let i=this.packetToFragmentLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,s=>{if(s===i.fragment){let c=s.trackData.get(this.internalTrack.id).samples.findIndex((l,u)=>l.isKeyFrame&&u>i.sampleIndex);if(c!==-1)return{sampleIndex:c,correctSampleFound:!0}}else{let a=s.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){let c=a.samples.findIndex(l=>l.isKeyFrame);return x(c!==-1),{sampleIndex:c,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,r)}async fetchPacketForSampleIndex(e,r){if(e===-1)return null;let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=Mee(n,e);if(!i)return null;let s;if(r.metadataOnly)s=Wt;else{let u=this.internalTrack.demuxer.reader.requestSlice(i.sampleOffset,i.sampleSize);u instanceof Promise&&(u=await u),x(u),s=se(u,i.sampleSize)}let a=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=i.duration/this.internalTrack.timescale,l=new je(s,i.isKeyFrame?"key":"delta",a,c,e,i.sampleSize);return this.packetToSampleIndex.set(l,e),l}async fetchPacketInFragment(e,r,n){if(r===-1)return null;let s=e.trackData.get(this.internalTrack.id).samples[r];x(s);let a;if(n.metadataOnly)a=Wt;else{let f=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);f instanceof Promise&&(f=await f),x(f),a=se(f,s.byteSize)}let c=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,l=s.duration/this.internalTrack.timescale,u=new je(a,s.isKeyFrame?"key":"delta",c,l,e.moofOffset+r,s.byteSize);return this.packetToFragmentLocation.set(u,{fragment:e,sampleIndex:r}),u}async performFragmentedLookup(e,r,n,i,s){let a=this.internalTrack.demuxer,c=null,l=null,u=-1;if(e){let{sampleIndex:y,correctSampleFound:b}=r(e);if(b)return this.fetchPacketInFragment(e,y,s);y!==-1&&(l=e,u=y)}let f=ze(this.internalTrack.fragmentLookupTable,n,y=>y.timestamp),d=f!==-1?this.internalTrack.fragmentLookupTable[f]:null,h=ze(this.internalTrack.fragmentPositionCache,n,y=>y.startTimestamp),m=h!==-1?this.internalTrack.fragmentPositionCache[h]:null,p=Math.max(d?.moofOffset??0,m?.moofOffset??0)||null,g;for(e?p===null||e.moofOffset>=p?(g=e.moofOffset+e.moofSize,c=e):g=p:g=p??0;;){if(c){let k=c.trackData.get(this.internalTrack.id);if(k&&k.startTimestamp>i)break}let y=a.reader.requestSliceRange(g,Ji,zo);if(y instanceof Promise&&(y=await y),!y)break;let b=g,w=Uo(y);if(!w)break;if(w.name==="moof"){c=await a.readFragment(b);let{sampleIndex:k,correctSampleFound:T}=r(c);if(T)return this.fetchPacketInFragment(c,k,s);k!==-1&&(l=c,u=k)}g=b+w.totalSize}if(d&&(!l||l.moofOffset<d.moofOffset)){let y=this.internalTrack.fragmentLookupTable[f-1];x(!y||y.timestamp<d.timestamp);let b=y?.timestamp??-1/0;return this.performFragmentedLookup(null,r,b,i,s)}return l?this.fetchPacketInFragment(l,u,s):null}},sI=class extends Xx{static{o(this,"IsobmffVideoTrackBacking")}constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let r=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=r&&Lx(r.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let r=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=r&&Bx(r.data)}let e={codec:Gf(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}},oI=class extends Xx{static{o(this,"IsobmffAudioTrackBacking")}constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:Qf(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},aI=o((t,e)=>{if(t.presentationTimestamps){let r=ze(t.presentationTimestamps,e,n=>n.presentationTimestamp);return r===-1?-1:t.presentationTimestamps[r].sampleIndex}else{let r=ze(t.sampleTimingEntries,e,i=>i.startDecodeTimestamp);if(r===-1)return-1;let n=t.sampleTimingEntries[r];return n.startIndex+Math.min(Math.floor((e-n.startDecodeTimestamp)/n.delta),n.count-1)}},"getSampleIndexForTimestamp"),Dee=o((t,e)=>{if(!t.keySampleIndices)return aI(t,e);if(t.presentationTimestamps){let r=ze(t.presentationTimestamps,e,n=>n.presentationTimestamp);if(r===-1)return-1;for(let n=r;n>=0;n--){let i=t.presentationTimestamps[n].sampleIndex;if(_o(t.keySampleIndices,i,a=>a)!==-1)return i}return-1}else{let r=aI(t,e),n=ze(t.keySampleIndices,r,i=>i);return t.keySampleIndices[n]??-1}},"getKeyframeSampleIndexForTimestamp"),Mee=o((t,e)=>{let r=ze(t.sampleTimingEntries,e,b=>b.startIndex),n=t.sampleTimingEntries[r];if(!n||n.startIndex+n.count<=e)return null;let s=n.startDecodeTimestamp+(e-n.startIndex)*n.delta,a=ze(t.sampleCompositionTimeOffsets,e,b=>b.startIndex),c=t.sampleCompositionTimeOffsets[a];c&&e-c.startIndex<c.count&&(s+=c.offset);let l=t.sampleSizes[Math.min(e,t.sampleSizes.length-1)],u=ze(t.sampleToChunk,e,b=>b.startSampleIndex),f=t.sampleToChunk[u];x(f);let d=f.startChunkIndex+Math.floor((e-f.startSampleIndex)/f.samplesPerChunk),h=t.chunkOffsets[d],m=f.startSampleIndex+(d-f.startChunkIndex)*f.samplesPerChunk,p=0,g=h;if(t.sampleSizes.length===1)g+=l*(e-m),p+=l*f.samplesPerChunk;else for(let b=m;b<m+f.samplesPerChunk;b++){let w=t.sampleSizes[b];b<e&&(g+=w),p+=w}let y=n.delta;if(t.presentationTimestamps){let b=t.presentationTimestampIndexMap[e];x(b!==void 0),b<t.presentationTimestamps.length-1&&(y=t.presentationTimestamps[b+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:y,sampleOffset:g,sampleSize:l,chunkOffset:h,chunkSize:p,isKeyFrame:t.keySampleIndices?_o(t.keySampleIndices,e,b=>b)!==-1:!0}},"getSampleInfo"),Oee=o((t,e)=>{if(!t.keySampleIndices)return e+1;let r=ze(t.keySampleIndices,e,n=>n);return t.keySampleIndices[r+1]??-1},"getNextKeyframeIndexForSample"),cI=o((t,e)=>{t.startTimestamp+=e,t.endTimestamp+=e;for(let r of t.samples)r.presentationTimestamp+=e;for(let r of t.presentationTimestamps)r.presentationTimestamp+=e},"offsetFragmentTrackDataByTimestamp"),Ree=o(t=>{let[e,r]=t,n=Math.atan2(r,e);return Number.isFinite(n)?n*(180/Math.PI):0},"extractRotationFromMatrix"),gU=o(t=>t.sampleSizes.length===0,"sampleTableIsEmpty")});function $o(t){if(t===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}var ad,cd,kp,es,I,Nee,ld,Sp,wU,xU,kU,Aee,ek,lI,In,ts,uI,ud,Oe,SU,qvt,tk,fI,rs,ic,fd,rk,nk,dI,on,ik=he(()=>{Ue();qt();ad=class{static{o(this,"EBMLFloat32")}constructor(e){this.value=e}},cd=class{static{o(this,"EBMLFloat64")}constructor(e){this.value=e}},kp=class{static{o(this,"EBMLSignedInt")}constructor(e){this.value=e}},es=class{static{o(this,"EBMLUnicodeString")}constructor(e){this.value=e}};(function(t){t[t.EBML=440786851]="EBML",t[t.EBMLVersion=17030]="EBMLVersion",t[t.EBMLReadVersion=17143]="EBMLReadVersion",t[t.EBMLMaxIDLength=17138]="EBMLMaxIDLength",t[t.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",t[t.DocType=17026]="DocType",t[t.DocTypeVersion=17031]="DocTypeVersion",t[t.DocTypeReadVersion=17029]="DocTypeReadVersion",t[t.Void=236]="Void",t[t.Segment=408125543]="Segment",t[t.SeekHead=290298740]="SeekHead",t[t.Seek=19899]="Seek",t[t.SeekID=21419]="SeekID",t[t.SeekPosition=21420]="SeekPosition",t[t.Duration=17545]="Duration",t[t.Info=357149030]="Info",t[t.TimestampScale=2807729]="TimestampScale",t[t.MuxingApp=19840]="MuxingApp",t[t.WritingApp=22337]="WritingApp",t[t.Tracks=374648427]="Tracks",t[t.TrackEntry=174]="TrackEntry",t[t.TrackNumber=215]="TrackNumber",t[t.TrackUID=29637]="TrackUID",t[t.TrackType=131]="TrackType",t[t.FlagEnabled=185]="FlagEnabled",t[t.FlagDefault=136]="FlagDefault",t[t.FlagForced=21930]="FlagForced",t[t.FlagOriginal=21934]="FlagOriginal",t[t.FlagHearingImpaired=21931]="FlagHearingImpaired",t[t.FlagVisualImpaired=21932]="FlagVisualImpaired",t[t.FlagCommentary=21935]="FlagCommentary",t[t.FlagLacing=156]="FlagLacing",t[t.Name=21358]="Name",t[t.Language=2274716]="Language",t[t.LanguageBCP47=2274717]="LanguageBCP47",t[t.CodecID=134]="CodecID",t[t.CodecPrivate=25506]="CodecPrivate",t[t.CodecDelay=22186]="CodecDelay",t[t.SeekPreRoll=22203]="SeekPreRoll",t[t.DefaultDuration=2352003]="DefaultDuration",t[t.Video=224]="Video",t[t.PixelWidth=176]="PixelWidth",t[t.PixelHeight=186]="PixelHeight",t[t.DisplayWidth=21680]="DisplayWidth",t[t.DisplayHeight=21690]="DisplayHeight",t[t.DisplayUnit=21682]="DisplayUnit",t[t.AlphaMode=21440]="AlphaMode",t[t.Audio=225]="Audio",t[t.SamplingFrequency=181]="SamplingFrequency",t[t.Channels=159]="Channels",t[t.BitDepth=25188]="BitDepth",t[t.SimpleBlock=163]="SimpleBlock",t[t.BlockGroup=160]="BlockGroup",t[t.Block=161]="Block",t[t.BlockAdditions=30113]="BlockAdditions",t[t.BlockMore=166]="BlockMore",t[t.BlockAdditional=165]="BlockAdditional",t[t.BlockAddID=238]="BlockAddID",t[t.BlockDuration=155]="BlockDuration",t[t.ReferenceBlock=251]="ReferenceBlock",t[t.Cluster=524531317]="Cluster",t[t.Timestamp=231]="Timestamp",t[t.Cues=475249515]="Cues",t[t.CuePoint=187]="CuePoint",t[t.CueTime=179]="CueTime",t[t.CueTrackPositions=183]="CueTrackPositions",t[t.CueTrack=247]="CueTrack",t[t.CueClusterPosition=241]="CueClusterPosition",t[t.Colour=21936]="Colour",t[t.MatrixCoefficients=21937]="MatrixCoefficients",t[t.TransferCharacteristics=21946]="TransferCharacteristics",t[t.Primaries=21947]="Primaries",t[t.Range=21945]="Range",t[t.Projection=30320]="Projection",t[t.ProjectionType=30321]="ProjectionType",t[t.ProjectionPoseRoll=30325]="ProjectionPoseRoll",t[t.Attachments=423732329]="Attachments",t[t.AttachedFile=24999]="AttachedFile",t[t.FileDescription=18046]="FileDescription",t[t.FileName=18030]="FileName",t[t.FileMediaType=18016]="FileMediaType",t[t.FileData=18012]="FileData",t[t.FileUID=18094]="FileUID",t[t.Chapters=272869232]="Chapters",t[t.Tags=307544935]="Tags",t[t.Tag=29555]="Tag",t[t.Targets=25536]="Targets",t[t.TargetTypeValue=26826]="TargetTypeValue",t[t.TargetType=25546]="TargetType",t[t.TagTrackUID=25541]="TagTrackUID",t[t.TagEditionUID=25545]="TagEditionUID",t[t.TagChapterUID=25540]="TagChapterUID",t[t.TagAttachmentUID=25542]="TagAttachmentUID",t[t.SimpleTag=26568]="SimpleTag",t[t.TagName=17827]="TagName",t[t.TagLanguage=17530]="TagLanguage",t[t.TagString=17543]="TagString",t[t.TagBinary=17541]="TagBinary",t[t.ContentEncodings=28032]="ContentEncodings",t[t.ContentEncoding=25152]="ContentEncoding",t[t.ContentEncodingOrder=20529]="ContentEncodingOrder",t[t.ContentEncodingScope=20530]="ContentEncodingScope",t[t.ContentCompression=20532]="ContentCompression",t[t.ContentCompAlgo=16980]="ContentCompAlgo",t[t.ContentCompSettings=16981]="ContentCompSettings",t[t.ContentEncryption=20533]="ContentEncryption"})(I||(I={}));Nee=[I.EBML,I.Segment],ld=[I.SeekHead,I.Info,I.Cluster,I.Tracks,I.Cues,I.Attachments,I.Chapters,I.Tags],Sp=[...Nee,...ld],wU=o(t=>t<256?1:t<65536?2:t<1<<24?3:t<2**32?4:t<2**40?5:6,"measureUnsignedInt"),xU=o(t=>t<1n<<8n?1:t<1n<<16n?2:t<1n<<24n?3:t<1n<<32n?4:t<1n<<40n?5:t<1n<<48n?6:t<1n<<56n?7:8,"measureUnsignedBigInt"),kU=o(t=>t>=-64&&t<64?1:t>=-8192&&t<8192?2:t>=-(1<<20)&&t<1<<20?3:t>=-(1<<27)&&t<1<<27?4:t>=-(2**34)&&t<2**34?5:6,"measureSignedInt"),Aee=o(t=>{if(t<127)return 1;if(t<16383)return 2;if(t<(1<<21)-1)return 3;if(t<(1<<28)-1)return 4;if(t<2**35-1)return 5;if(t<2**42-1)return 6;throw new Error("EBML varint size not supported "+t)},"measureVarInt"),ek=class{static{o(this,"EBMLWriter")}constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,r=wU(e)){let n=0;switch(r){case 6:this.helperView.setUint8(n++,e/2**40|0);case 5:this.helperView.setUint8(n++,e/2**32|0);case 4:this.helperView.setUint8(n++,e>>24);case 3:this.helperView.setUint8(n++,e>>16);case 2:this.helperView.setUint8(n++,e>>8);case 1:this.helperView.setUint8(n++,e);break;default:throw new Error("Bad unsigned int size "+r)}this.writer.write(this.helper.subarray(0,n))}writeUnsignedBigInt(e,r=xU(e)){let n=0;for(let i=r-1;i>=0;i--)this.helperView.setUint8(n++,Number(e>>BigInt(i*8)&0xffn));this.writer.write(this.helper.subarray(0,n))}writeSignedInt(e,r=kU(e)){e<0&&(e+=2**(r*8)),this.writeUnsignedInt(e,r)}writeVarInt(e,r=Aee(e)){let n=0;switch(r){case 1:this.helperView.setUint8(n++,128|e);break;case 2:this.helperView.setUint8(n++,64|e>>8),this.helperView.setUint8(n++,e);break;case 3:this.helperView.setUint8(n++,32|e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 4:this.helperView.setUint8(n++,16|e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 5:this.helperView.setUint8(n++,8|e/2**32&7),this.helperView.setUint8(n++,e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 6:this.helperView.setUint8(n++,4|e/2**40&3),this.helperView.setUint8(n++,e/2**32|0),this.helperView.setUint8(n++,e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;default:throw new Error("Bad EBML varint size "+r)}this.writer.write(this.helper.subarray(0,n))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split("").map(r=>r.charCodeAt(0))))}writeEBML(e){if(e!==null)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(let r of e)this.writeEBML(r);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){let r=this.writer.getPos(),n=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+n);let i=this.writer.getPos();if(this.dataOffsets.set(e,i),this.writeEBML(e.data),e.size!==-1){let s=this.writer.getPos()-i,a=this.writer.getPos();this.writer.seek(r),this.writeVarInt(s,n),this.writer.seek(a)}}else if(typeof e.data=="number"){let r=e.size??wU(e.data);this.writeVarInt(r),this.writeUnsignedInt(e.data,r)}else if(typeof e.data=="bigint"){let r=e.size??xU(e.data);this.writeVarInt(r),this.writeUnsignedBigInt(e.data,r)}else if(typeof e.data=="string")this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof ad)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof cd)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof kp){let r=e.size??kU(e.data.value);this.writeVarInt(r),this.writeSignedInt(e.data.value,r)}else if(e.data instanceof es){let r=lt.encode(e.data.value);this.writeVarInt(r.length),this.writer.write(r)}else kt(e.data)}},lI=8,In=2,ts=2*lI,uI=o(t=>{if(t.remainingLength<1)return null;let e=oe(t);if(t.skip(-1),e===0)return null;let r=1,n=128;for(;(e&n)===0;)r++,n>>=1;return t.remainingLength<r?null:r},"readVarIntSize"),ud=o(t=>{if(t.remainingLength<1)return null;let e=oe(t);if(e===0)return null;let r=1,n=128;for(;(e&n)===0;)r++,n>>=1;if(t.remainingLength<r-1)return null;let i=e&n-1;for(let s=1;s<r;s++)i*=256,i+=oe(t);return i},"readVarInt"),Oe=o((t,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let r=0;for(let n=0;n<e;n++)r*=256,r+=oe(t);return r},"readUnsignedInt"),SU=o((t,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let r=0n;for(let n=0;n<e;n++)r<<=8n,r+=BigInt(oe(t));return r},"readUnsignedBigInt"),qvt=o((t,e)=>{let r=Oe(t,e);return r&1<<e*8-1&&(r-=2**(e*8)),r},"readSignedInt"),tk=o(t=>{let e=uI(t);return e===null||t.remainingLength<e?null:Oe(t,e)},"readElementId"),fI=o(t=>{if(t.remainingLength<1)return null;if(oe(t)===255)return;t.skip(-1);let r=ud(t);if(r===null)return null;if(r!==72057594037927940)return r},"readElementSize"),rs=o(t=>{x(t.remainingLength>=In);let e=tk(t);if(e===null)return null;let r=fI(t);return r===null?null:{id:e,size:r}},"readElementHeader"),ic=o((t,e)=>{let r=se(t,e),n=0;for(;n<e&&r[n]!==0;)n+=1;return String.fromCharCode(...r.subarray(0,n))},"readAsciiString"),fd=o((t,e)=>{let r=se(t,e),n=0;for(;n<e&&r[n]!==0;)n+=1;return br.decode(r.subarray(0,n))},"readUnicodeString"),rk=o((t,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?TU(t):Zx(t)},"readFloat"),nk=o(async(t,e,r,n)=>{let i=new Set(r),s=e;for(;n===null||s<n;){let a=t.requestSliceRange(s,In,ts);if(a instanceof Promise&&(a=await a),!a)break;let c=rs(a);if(!c)break;if(i.has(c.id))return{pos:s,found:!0};$o(c.size),s=a.filePos+c.size}return{pos:n!==null&&n>s?n:s,found:!1}},"searchForNextElementId"),dI=o(async(t,e,r,n)=>{let s=new Set(r),a=e;for(;a<n;){let c=t.requestSliceRange(a,0,Math.min(65536,n-a));if(c instanceof Promise&&(c=await c),!c||c.length<lI)break;for(let l=0;l<c.length-lI;l++){c.filePos=a;let u=tk(c);if(u!==null&&s.has(u))return a;a++}}return null},"resync"),on={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};o($o,"assertDefinedSize")});var sk,hI=he(()=>{sk=o(t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isWebM?"webm":"x-matroska");if(t.codecStrings.length>0){let n=[...new Set(t.codecStrings.filter(Boolean))];r+=`; codecs="${n.join(", ")}"`}return r},"buildMatroskaMimeType")});var Ho,ok,Tp,mI,vU,ck,ak,pI,gI,EU=he(()=>{sn();Zt();Fo();Xi();lr();Ue();Qn();ik();hI();qt();(function(t){t[t.None=0]="None",t[t.Xiph=1]="Xiph",t[t.FixedSize=2]="FixedSize",t[t.Ebml=3]="Ebml"})(Ho||(Ho={}));(function(t){t[t.Block=1]="Block",t[t.Private=2]="Private",t[t.Next=4]="Next"})(ok||(ok={}));(function(t){t[t.Zlib=0]="Zlib",t[t.Bzlib=1]="Bzlib",t[t.lzo1x=2]="lzo1x",t[t.HeaderStripping=3]="HeaderStripping"})(Tp||(Tp={}));mI=[{id:I.SeekHead,flag:"seekHeadSeen"},{id:I.Info,flag:"infoSeen"},{id:I.Tracks,flag:"tracksSeen"},{id:I.Cues,flag:"cuesSeen"}],vU=10*2**20,ck=class extends wr{static{o(this,"MatroskaDemuxer")}constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...r)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(r=>r.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.getCodecParameterString()));return sk({isWebM:this.isWebM,hasVideo:this.segments.some(n=>n.tracks.some(i=>i.info?.type==="video")),hasAudio:this.segments.some(n=>n.tracks.some(i=>i.info?.type==="audio")),codecStrings:r.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let r of this.segments)r.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(r),r.metadataTagsCollected=!0);let e={};for(let r of this.segments)e={...e,...r.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,In,ts);if(r instanceof Promise&&(r=await r),!r)break;let n=rs(r);if(!n)break;let i=n.id,s=n.size,a=r.filePos;if(i===I.EBML){$o(s);let c=this.reader.requestSlice(a,s);if(c instanceof Promise&&(c=await c),!c)break;this.readContiguousElements(c)}else if(i===I.Segment){if(await this.readSegment(a,s),s===void 0||this.reader.fileSize===null)break}else if(i===I.Cluster){if(this.reader.fileSize===null)break;s===void 0&&(s=(await nk(this.reader,a,Sp,this.reader.fileSize)).pos-a);let c=Ze(this.segments);c&&(c.elementEndPos=a+s)}$o(s),e=a+s}})()}async readSegment(e,r){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:r===void 0?null:e+r,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let c=this.reader.requestSliceRange(n,In,ts);if(c instanceof Promise&&(c=await c),!c)break;let l=n,u=rs(c);if(!u||!ld.includes(u.id)&&u.id!==I.Void){let p=await dI(this.reader,l,ld,Math.min(this.currentSegment.elementEndPos??1/0,l+vU));if(p){n=p;continue}else break}let{id:f,size:d}=u,h=c.filePos,m=mI.findIndex(p=>p.id===f);if(m!==-1){let p=mI[m].flag;this.currentSegment[p]=!0,$o(d);let g=this.reader.requestSlice(h,d);g instanceof Promise&&(g=await g),g&&this.readContiguousElements(g)}else if(f===I.Tags||f===I.Attachments){f===I.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,$o(d);let p=this.reader.requestSlice(h,d);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(f===I.Cluster){this.currentSegment.clusterSeekStartPos=l;break}if(d===void 0)break;n=h+d}if(this.currentSegment.seekEntries.sort((c,l)=>c.segmentPosition-l.segmentPosition),this.reader.fileSize!==null)for(let c of this.currentSegment.seekEntries){let l=mI.find(p=>p.id===c.id);if(!l||this.currentSegment[l.flag])continue;let u=this.reader.requestSliceRange(e+c.segmentPosition,In,ts);if(u instanceof Promise&&(u=await u),!u)continue;let f=rs(u);if(!f)continue;let{id:d,size:h}=f;if(d!==l.id)continue;$o(h),this.currentSegment[l.flag]=!0;let m=this.reader.requestSlice(u.filePos,h);m instanceof Promise&&(m=await m),m&&this.readContiguousElements(m)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(let c of this.currentSegment.tracks)c.defaultDurationNs!==null&&(c.defaultDuration=this.currentSegment.timestampFactor*c.defaultDurationNs/1e9);this.currentSegment.tracks.sort((c,l)=>Number(l.disposition.default)-Number(c.disposition.default));let i=new Map(this.currentSegment.tracks.map(c=>[c.id,c]));for(let c of this.currentSegment.cuePoints){let l=i.get(c.trackId);l&&l.cuePoints.push(c)}for(let c of this.currentSegment.tracks){c.cuePoints.sort((l,u)=>l.time-u.time);for(let l=0;l<c.cuePoints.length-1;l++){let u=c.cuePoints[l],f=c.cuePoints[l+1];u.time===f.time&&(c.cuePoints.splice(l+1,1),l--)}}let s=null,a=-1/0;for(let c of this.currentSegment.tracks)c.cuePoints.length>a&&(a=c.cuePoints.length,s=c);for(let c of this.currentSegment.tracks)c.cuePoints.length===0&&(c.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,r){if(r.lastReadCluster?.elementStartPos===e)return r.lastReadCluster;let n=this.reader.requestSliceRange(e,In,ts);n instanceof Promise&&(n=await n),x(n);let i=e,s=rs(n);x(s);let a=s.id;x(a===I.Cluster);let c=s.size,l=n.filePos;c===void 0&&(c=(await nk(this.reader,l,Sp,r.elementEndPos)).pos-l);let u=this.reader.requestSlice(l,c);u instanceof Promise&&(u=await u);let f={segment:r,elementStartPos:i,elementEndPos:l+c,dataStartPos:l,timestamp:-1,trackData:new Map};if(this.currentCluster=f,u){let d=this.readContiguousElements(u,Sp);f.elementEndPos=d}for(let[,d]of f.trackData){let h=d.track;x(d.blocks.length>0);let m=!1;for(let b=0;b<d.blocks.length;b++){let w=d.blocks[b];w.timestamp+=f.timestamp,m||=w.lacing!==Ho.None}d.presentationTimestamps=d.blocks.map((b,w)=>({timestamp:b.timestamp,blockIndex:w})).sort((b,w)=>b.timestamp-w.timestamp);for(let b=0;b<d.presentationTimestamps.length;b++){let w=d.presentationTimestamps[b],k=d.blocks[w.blockIndex];if(d.firstKeyFrameTimestamp===null&&k.isKeyFrame&&(d.firstKeyFrameTimestamp=k.timestamp),b<d.presentationTimestamps.length-1){let T=d.presentationTimestamps[b+1];k.duration=T.timestamp-k.timestamp}else k.duration===0&&h.defaultDuration!=null&&k.lacing===Ho.None&&(k.duration=h.defaultDuration)}m&&(this.expandLacedBlocks(d.blocks,h),d.presentationTimestamps=d.blocks.map((b,w)=>({timestamp:b.timestamp,blockIndex:w})).sort((b,w)=>b.timestamp-w.timestamp));let p=d.blocks[d.presentationTimestamps[0].blockIndex],g=d.blocks[Ze(d.presentationTimestamps).blockIndex];d.startTimestamp=p.timestamp,d.endTimestamp=g.timestamp+g.duration;let y=ze(h.clusterPositionCache,d.startTimestamp,b=>b.startTimestamp);(y===-1||h.clusterPositionCache[y].elementStartPos!==i)&&h.clusterPositionCache.splice(y+1,0,{elementStartPos:f.elementStartPos,startTimestamp:d.startTimestamp})}return r.lastReadCluster=f,f}getTrackDataInCluster(e,r){let n=e.trackData.get(r);if(!n){let i=e.segment.tracks.find(s=>s.id===r);if(!i)return null;n={track:i,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(r,n)}return n}expandLacedBlocks(e,r){for(let n=0;n<e.length;n++){let i=e[n];if(i.lacing===Ho.None)continue;i.decoded||(i.data=this.decodeBlockData(r,i.data),i.decoded=!0);let s=xr.tempFromBytes(i.data),a=[],c=oe(s)+1;switch(i.lacing){case Ho.Xiph:{let u=0;for(let f=0;f<c-1;f++){let d=0;for(;s.bufferPos<s.length;){let h=oe(s);if(d+=h,h<255){a.push(d),u+=d;break}}}a.push(s.length-(s.bufferPos+u))}break;case Ho.FixedSize:{let u=s.length-1,f=Math.floor(u/c);for(let d=0;d<c;d++)a.push(f)}break;case Ho.Ebml:{let u=ud(s);x(u!==null);let f=u;a.push(f);let d=f;for(let h=1;h<c-1;h++){let m=s.bufferPos,p=ud(s);x(p!==null);let g=p,b=(1<<(s.bufferPos-m)*7-1)-1,w=g-b;f+=w,a.push(f),d+=f}a.push(s.length-(s.bufferPos+d))}break;default:x(!1)}x(a.length===c),e.splice(n,1);let l=i.duration||c*(r.defaultDuration??0);for(let u=0;u<c;u++){let f=a[u],d=se(s,f),h=i.timestamp+l*u/c,m=l/c;e.splice(n+u,0,{timestamp:h,duration:m,isKeyFrame:i.isKeyFrame,data:d,lacing:Ho.None,decoded:!0,mainAdditional:i.mainAdditional})}n+=c,n--}}async loadSegmentMetadata(e){for(let r of e.seekEntries){if(!(r.id===I.Tags&&!e.tagsSeen)){if(!(r.id===I.Attachments&&!e.attachmentsSeen))continue}let n=this.reader.requestSliceRange(e.dataStartPos+r.segmentPosition,In,ts);if(n instanceof Promise&&(n=await n),!n)continue;let i=rs(n);if(!i||i.id!==r.id)continue;let{size:s}=i;$o(s),x(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(n.filePos,s);a instanceof Promise&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,r.id===I.Tags?e.tagsSeen=!0:r.id===I.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,r){for(;e.remainingLength>=In;){let n=e.filePos;if(!this.traverseElement(e,r))return n}return e.filePos}traverseElement(e,r){let n=rs(e);if(!n||r&&r.includes(n.id))return!1;let{id:i,size:s}=n,a=e.filePos;switch($o(s),i){case I.DocType:this.isWebM=ic(e,s)==="webm";break;case I.Seek:{if(!this.currentSegment)break;let c={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(c),this.readContiguousElements(e.slice(a,s)),(c.id===-1||c.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case I.SeekID:{let c=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!c)break;c.id=Oe(e,s)}break;case I.SeekPosition:{let c=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!c)break;c.segmentPosition=Oe(e,s)}break;case I.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=Oe(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case I.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=rk(e,s)}break;case I.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...jr},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(c=>c.data?.type!=="decompress"||c.scope!==ok.Block||c.data.algorithm!==Tp.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let c=this.currentTrack.codecId.indexOf("/"),l=c===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,c);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let d=this.currentTrack.info.displayWidth*this.currentTrack.info.height,h=this.currentTrack.info.displayHeight*this.currentTrack.info.width;d>h?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*d/h):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*h/d)}this.currentTrack.codecId===on.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===on.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):l===on.vp8?this.currentTrack.info.codec="vp8":l===on.vp9?this.currentTrack.info.codec="vp9":l===on.av1&&(this.currentTrack.info.codec="av1");let u=this.currentTrack,f=new Pn(this.input,new pI(u));this.currentTrack.inputTrack=f,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){l===on.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===on.mp3?this.currentTrack.info.codec="mp3":l===on.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Qi):l===on.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):l===on.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):l===on.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):l===on.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));let u=this.currentTrack,f=new Et(this.input,new gI(u));this.currentTrack.inputTrack=f,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case I.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=Oe(e,s)}break;case I.TrackType:{if(!this.currentTrack)break;let c=Oe(e,s);c===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:c===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case I.FlagEnabled:{if(!this.currentTrack)break;Oe(e,s)||(this.currentTrack=null)}break;case I.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Oe(e,s)}break;case I.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Oe(e,s)}break;case I.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Oe(e,s)}break;case I.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Oe(e,s)}break;case I.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Oe(e,s)}break;case I.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Oe(e,s)}break;case I.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=ic(e,s)}break;case I.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=se(e,s)}break;case I.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Oe(e,s)}break;case I.Name:{if(!this.currentTrack)break;this.currentTrack.name=fd(e,s)}break;case I.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=ic(e,s),Mo(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Ft)}break;case I.LanguageBCP47:{if(!this.currentTrack)break;let l=ic(e,s).split("-")[0];l?this.currentTrack.languageCode=l:this.currentTrack.languageCode=Ft,this.currentTrack.hasLanguageBcp47=!0}break;case I.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case I.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=Oe(e,s)}break;case I.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=Oe(e,s)}break;case I.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=Oe(e,s)}break;case I.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=Oe(e,s)}break;case I.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=Oe(e,s)}break;case I.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=Oe(e,s)===1}break;case I.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(a,s))}break;case I.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let c=Oe(e,s),l=Il[c]??null;this.currentTrack.info.colorSpace.matrix=l}break;case I.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=Oe(e,s)===2}break;case I.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let c=Oe(e,s),l=Pl[c]??null;this.currentTrack.info.colorSpace.transfer=l}break;case I.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let c=Oe(e,s),l=Cl[c]??null;this.currentTrack.info.colorSpace.primaries=l}break;case I.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case I.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let l=-rk(e,s);try{this.currentTrack.info.rotation=Ha(l)}catch{}}break;case I.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(a,s))}break;case I.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=rk(e,s)}break;case I.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=Oe(e,s)}break;case I.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=Oe(e,s)}break;case I.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,s)),this.currentCueTime=null}break;case I.CueTime:this.currentCueTime=Oe(e,s);break;case I.CueTrackPositions:{if(this.currentCueTime===null)break;x(this.currentSegment);let c={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(c),this.readContiguousElements(e.slice(a,s)),(c.trackId===-1||c.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case I.CueTrack:{let c=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!c)break;c.trackId=Oe(e,s)}break;case I.CueClusterPosition:{let c=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!c)break;x(this.currentSegment),c.clusterPosition=this.currentSegment.dataStartPos+Oe(e,s)}break;case I.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=Oe(e,s)}break;case I.SimpleBlock:{if(!this.currentCluster)break;let c=ud(e);if(c===null)break;let l=this.getTrackDataInCluster(this.currentCluster,c);if(!l)break;let u=xp(e),f=oe(e),d=f>>1&3,h=!!(f&128);l.track.info?.type==="audio"&&l.track.info.codec&&(h=!0);let m=se(e,s-(e.filePos-a)),p=l.track.decodingInstructions.length>0;l.blocks.push({timestamp:u,duration:0,isKeyFrame:h,data:m,lacing:d,decoded:!p,mainAdditional:null})}break;case I.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,s)),this.currentBlock=null}break;case I.Block:{if(!this.currentCluster)break;let c=ud(e);if(c===null)break;let l=this.getTrackDataInCluster(this.currentCluster,c);if(!l)break;let u=xp(e),d=oe(e)>>1&3,h=se(e,s-(e.filePos-a)),m=l.track.decodingInstructions.length>0;this.currentBlock={timestamp:u,duration:0,isKeyFrame:!0,data:h,lacing:d,decoded:!m,mainAdditional:null},l.blocks.push(this.currentBlock)}break;case I.BlockAdditions:this.readContiguousElements(e.slice(a,s));break;case I.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case I.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=se(e,s)}break;case I.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Oe(e,s)}break;case I.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=Oe(e,s)}break;case I.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case I.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,s));break;case I.Targets:this.readContiguousElements(e.slice(a,s));break;case I.TargetTypeValue:Oe(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case I.TagTrackUID:case I.TagEditionUID:case I.TagChapterUID:case I.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case I.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,s))}break;case I.TagName:this.currentSimpleTagName=fd(e,s);break;case I.TagString:{if(!this.currentSimpleTagName)break;let c=fd(e,s);this.processTagValue(this.currentSimpleTagName,c)}break;case I.TagBinary:{if(!this.currentSimpleTagName)break;let c=se(e,s);this.processTagValue(this.currentSimpleTagName,c)}break;case I.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,s));let c=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(c.raw??={},c.raw[this.currentAttachedFile.fileUid.toString()]=new Oo(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let l=this.currentAttachedFile.fileName,u="unknown";if(l){let f=l.toLowerCase();f.startsWith("cover.")?u="coverFront":f.startsWith("back.")&&(u="coverBack")}c.images??=[],c.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:u,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case I.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=SU(e,s)}break;case I.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=fd(e,s)}break;case I.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=ic(e,s)}break;case I.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=se(e,s)}break;case I.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=fd(e,s)}break;case I.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,s)),this.currentTrack.decodingInstructions.sort((c,l)=>l.order-c.order)}break;case I.ContentEncoding:this.currentDecodingInstruction={order:0,scope:ok.Block,data:null},this.readContiguousElements(e.slice(a,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case I.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Oe(e,s)}break;case I.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Oe(e,s)}break;case I.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Tp.Zlib,settings:null},this.readContiguousElements(e.slice(a,s))}break;case I.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=Oe(e,s)}break;case I.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=se(e,s)}break;case I.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+s,!0}decodeBlockData(e,r){x(e.decodingInstructions.length>0);let n=r;for(let i of e.decodingInstructions)switch(x(i.data),i.data.type){case"decompress":switch(i.data.algorithm){case Tp.HeaderStripping:if(i.data.settings&&i.data.settings.length>0){let s=i.data.settings,a=new Uint8Array(s.length+n.length);a.set(s,0),a.set(n,s.length),n=a}break;default:}break;default:}return n}processTagValue(e,r){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=r,typeof r=="string")switch(e.toLowerCase()){case"title":n.title??=r;break;case"description":n.description??=r;break;case"artist":n.artist??=r;break;case"album":n.album??=r;break;case"album_artist":n.albumArtist??=r;break;case"genre":n.genre??=r;break;case"comment":n.comment??=r;break;case"lyrics":n.lyrics??=r;break;case"date":{let i=new Date(r);Number.isNaN(i.getTime())||(n.date??=i)}break;case"track_number":case"part_number":{let i=r.split("/"),s=Number.parseInt(i[0],10),a=i[1]&&Number.parseInt(i[1],10);Number.isInteger(s)&&s>0&&(n.trackNumber??=s),a&&Number.isInteger(a)&&a>0&&(n.tracksTotal??=a)}break;case"disc_number":case"disc":{let i=r.split("/"),s=Number.parseInt(i[0],10),a=i[1]&&Number.parseInt(i[1],10);Number.isInteger(s)&&s>0&&(n.discNumber??=s),a&&Number.isInteger(a)&&a>0&&(n.discsTotal??=a)}break}}},ak=class{static{o(this,"MatroskaTrackBacking")}constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,n=this.internalTrack.inputTrack.type,i=0;for(let s of e.segments)for(let a of s.tracks)if(a.inputTrack.type===n&&i++,a===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,r=>r.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Do(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,r){let n=this.intoTimescale(e);return this.performClusterLookup(null,i=>{let s=i.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let a=ze(s.presentationTimestamps,n,u=>u.timestamp),c=a!==-1?s.presentationTimestamps[a].blockIndex:-1,l=a!==-1&&n<s.endTimestamp;return{blockIndex:c,correctBlockFound:l}},n,n,r)}async getNextPacket(e,r){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,i=>{if(i===n.cluster){let s=i.trackData.get(this.internalTrack.id);if(n.blockIndex+1<s.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(i.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async getKeyPacket(e,r){let n=this.intoTimescale(e);return this.performClusterLookup(null,i=>{let s=i.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let a=qf(s.presentationTimestamps,u=>s.blocks[u.blockIndex].isKeyFrame&&u.timestamp<=n),c=a!==-1?s.presentationTimestamps[a].blockIndex:-1,l=a!==-1&&n<s.endTimestamp;return{blockIndex:c,correctBlockFound:l}},n,n,r)}async getNextKeyPacket(e,r){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,i=>{if(i===n.cluster){let a=i.trackData.get(this.internalTrack.id).blocks.findIndex((c,l)=>c.isKeyFrame&&l>n.blockIndex);if(a!==-1)return{blockIndex:a,correctBlockFound:!0}}else{let s=i.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){let a=s.blocks.findIndex(c=>c.isKeyFrame);return x(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async fetchPacketInCluster(e,r,n){if(r===-1)return null;let s=e.trackData.get(this.internalTrack.id).blocks[r];x(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0);let a=n.metadataOnly?Wt:s.data,c=s.timestamp/this.internalTrack.segment.timestampFactor,l=s.duration/this.internalTrack.segment.timestampFactor,u={};s.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(u.alpha=n.metadataOnly?Wt:s.mainAdditional,u.alphaByteLength=s.mainAdditional.byteLength);let f=new je(a,s.isKeyFrame?"key":"delta",c,l,e.dataStartPos+r,s.data.byteLength,u);return this.packetToClusterLocation.set(f,{cluster:e,blockIndex:r}),f}async performClusterLookup(e,r,n,i,s){let{demuxer:a,segment:c}=this.internalTrack,l=null,u=null,f=-1;if(e){let{blockIndex:b,correctBlockFound:w}=r(e);if(w)return this.fetchPacketInCluster(e,b,s);b!==-1&&(u=e,f=b)}let d=ze(this.internalTrack.cuePoints,n,b=>b.time),h=d!==-1?this.internalTrack.cuePoints[d]:null,m=ze(this.internalTrack.clusterPositionCache,n,b=>b.startTimestamp),p=m!==-1?this.internalTrack.clusterPositionCache[m]:null,g=Math.max(h?.clusterPosition??0,p?.elementStartPos??0)||null,y;for(e?g===null||e.elementStartPos>=g?(y=e.elementEndPos,l=e):y=g:y=g??c.clusterSeekStartPos;c.elementEndPos===null||y<=c.elementEndPos-In;){if(l){let P=l.trackData.get(this.internalTrack.id);if(P&&P.startTimestamp>i)break}let b=a.reader.requestSliceRange(y,In,ts);if(b instanceof Promise&&(b=await b),!b)break;let w=y,k=rs(b);if(!k||!ld.includes(k.id)&&k.id!==I.Void){let P=await dI(a.reader,w,ld,Math.min(c.elementEndPos??1/0,w+vU));if(P){y=P;continue}else break}let T=k.id,v=k.size,S=b.filePos;if(T===I.Cluster){l=await a.readCluster(w,c),v=l.elementEndPos-S;let{blockIndex:P,correctBlockFound:N}=r(l);if(N)return this.fetchPacketInCluster(l,P,s);P!==-1&&(u=l,f=P)}v===void 0&&(x(T!==I.Cluster),v=(await nk(a.reader,S,Sp,c.elementEndPos)).pos-S);let M=S+v;if(c.elementEndPos===null){let P=a.reader.requestSliceRange(M,In,ts);if(P instanceof Promise&&(P=await P),!P)break;if(tk(P)===I.Segment){c.elementEndPos=M;break}}y=M}if(h&&(!u||u.elementStartPos<h.clusterPosition)){let b=this.internalTrack.cuePoints[d-1];x(!b||b.time<h.time);let w=b?.time??-1/0;return this.performClusterLookup(null,r,w,i,s)}return u?this.fetchPacketInCluster(u,f,s):null}},pI=class extends ak{static{o(this,"MatroskaVideoTrackBacking")}constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));let n={codec:Gf({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?Jf(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Zf(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Lx(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Bx(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})():null}},gI=class extends ak{static{o(this,"MatroskaAudioTrackBacking")}constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:Qf({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}});var vp,yI=he(()=>{Ka();qt();vp=o(async(t,e,r)=>{let n=e;for(;r===null||n<r;){let i=t.requestSlice(n,4);if(i instanceof Promise&&(i=await i),!i)break;let s=X(i),a=Ol(s,t.fileSize!==null?t.fileSize-n:null);if(a.header)return{header:a.header,startPos:n};n+=a.bytesAdvanced}return null},"readNextMp3FrameHeader")});var lk,bI,CU=he(()=>{Fo();Xi();lr();Ue();Qn();Ka();sc();yI();qt();lk=class extends wr{static{o(this,"Mp3Demuxer")}constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new Tn,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.tracks=[new Et(this.input,new bI(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let c=this.reader.requestSlice(this.lastLoadedPos,Xn);if(c instanceof Promise&&(c=await c),!c){this.lastSampleLoaded=!0;return}let l=ns(c);if(!l)break;this.lastLoadedPos=c.filePos+l.size}let e=await vp(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}let r=e.header;this.lastLoadedPos=e.startPos+r.totalSize-1;let n=Qa(r.mpegVersionId,r.channel),i=this.reader.requestSlice(e.startPos+n,4);if(i instanceof Promise&&(i=await i),i){let c=X(i);if(c===Ga||c===Xf)return}this.firstFrameHeader||(this.firstFrameHeader=r),r.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${r.sampleRate} Hz. Might be a bug, so please report this file.`);let s=r.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:r.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=r.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return x(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let r=0,n=!1;for(;;){let i=this.reader.requestSlice(r,Xn);if(i instanceof Promise&&(i=await i),!i)break;let s=ns(i);if(!s)break;n=!0;let a=this.reader.requestSlice(i.filePos,s.size);if(a instanceof Promise&&(a=await a),!a)break;dd(a,s,this.metadataTags),r=i.filePos+s.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=Ep){let i=this.reader.requestSlice(this.reader.fileSize-Ep,Ep);i instanceof Promise&&(i=await i),x(i),It(i,3)==="TAG"&&PU(i,this.metadataTags)}return this.metadataTags}finally{e()}}},bI=class{static{o(this,"Mp3AudioTrackBacking")}constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return x(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return Ft}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return x(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return x(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...jr}}async getDecoderConfig(){return x(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,r){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(r.metadataOnly)i=Wt;else{let s=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;i=se(s,n.dataSize)}return new je(i,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{let i=_o(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(i===-1)throw new Error("Packet was not created from this track.");let s=i+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,r)}finally{n()}}async getPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let i=ze(this.demuxer.loadedSamples,e,s=>s.timestamp);if(i===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,r);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,r);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}}});var Cp,Fee,IU,uk,fk,dk,hk=he(()=>{sn();Ue();Cp=1399285583,Fee=79764919,IU=new Uint32Array(256);for(let t=0;t<256;t++){let e=t<<24;for(let r=0;r<8;r++)e=e&2147483648?e<<1^Fee:e<<1;IU[t]=e>>>0&4294967295}uk=o(t=>{let e=ge(t),r=e.getUint32(22,!0);e.setUint32(22,0,!0);let n=0;for(let i=0;i<t.length;i++){let s=t[i];n=(n<<8^IU[n>>>24^s])>>>0}return e.setUint32(22,r,!0),n},"computeOggPageCrc"),fk=o((t,e,r)=>{let n=0,i=null;if(t.length>0)if(e.codec==="vorbis"){x(e.vorbisInfo);let s=e.vorbisInfo.modeBlockflags.length,c=(1<<vz(s-1))-1<<1,l=(t[0]&c)>>1;if(l>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let u=r,f=e.vorbisInfo.modeBlockflags[l];if(i=e.vorbisInfo.blocksizes[f],f===1){let d=(c|1)+1,h=t[0]&d?1:0;u=e.vorbisInfo.blocksizes[h]}n=u!==null?u+i>>2:0}else e.codec==="opus"&&(n=Zz(t).durationInSamples);return{durationInSamples:n,vorbisBlockSize:i}},"extractSampleMetadata"),dk=o(t=>{let e="audio/ogg";if(t.codecStrings){let r=[...new Set(t.codecStrings)];e+=`; codecs="${r.join(", ")}"`}return e},"buildOggMimeType")});var oc,$l,mk,hd,_U,wI=he(()=>{qt();hk();oc=27,$l=282,mk=$l+65025,hd=o(t=>{let e=t.filePos;if(Ul(t)!==Cp)return null;t.skip(1);let n=oe(t),i=DU(t),s=Ul(t),a=Ul(t),c=Ul(t),l=oe(t),u=new Uint8Array(l);for(let m=0;m<l;m++)u[m]=oe(t);let f=27+l,d=u.reduce((m,p)=>m+p,0),h=f+d;return{headerStartPos:e,totalSize:h,dataStartPos:e+f,dataSize:d,headerType:n,granulePosition:i,serialNumber:s,sequenceNumber:a,checksum:c,lacingValues:u}},"readPageHeader"),_U=o((t,e)=>{for(;t.filePos<e-3;){let r=Ul(t),n=r&255,i=r>>>8&255,s=r>>>16&255,a=r>>>24&255,c=79;if(!(n!==c&&i!==c&&s!==c&&a!==c)){if(t.skip(-4),r===Cp)return!0;t.skip(1)}}return!1},"findNextPageHeader")});var pk,xI,MU,OU,RU=he(()=>{Zt();sn();Fo();Xi();lr();Ue();Qn();qt();hk();wI();pk=class extends wr{static{o(this,"OggDemuxer")}constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,oc,$l);if(r instanceof Promise&&(r=await r),!r)break;let n=hd(r);if(!n||!!!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let r of this.bitstreams){let n=await this.readPacket(r.bosPage,0);n&&(n.data.byteLength>=7&&n.data[0]===1&&n.data[1]===118&&n.data[2]===111&&n.data[3]===114&&n.data[4]===98&&n.data[5]===105&&n.data[6]===115?await this.readVorbisMetadata(n,r):n.data.byteLength>=8&&n.data[0]===79&&n.data[1]===112&&n.data[2]===117&&n.data[3]===115&&n.data[4]===72&&n.data[5]===101&&n.data[6]===97&&n.data[7]===100&&await this.readOpusMetadata(n,r),r.codecInfo.codec!==null&&this.tracks.push(new Et(this.input,new xI(r,this))))}})()}async readVorbisMetadata(e,r){let n=await this.findNextPacketStart(e);if(!n)return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||(n=await this.findNextPacketStart(i),!n))return;let s=await this.readPacket(n.startPage,n.startSegmentIndex);if(!s||i.data[0]!==3||s.data[0]!==5)return;let a=[],c=o(d=>{for(;a.push(Math.min(255,d)),!(d<255);)d-=255},"addBytesToSegmentTable");c(e.data.length),c(i.data.length);let l=new Uint8Array(1+a.length+e.data.length+i.data.length+s.data.length);l[0]=2,l.set(a,1),l.set(e.data,1+a.length),l.set(i.data,1+a.length+e.data.length),l.set(s.data,1+a.length+e.data.length+i.data.length),r.codecInfo.codec="vorbis",r.description=l,r.lastMetadataPacket=s;let u=ge(e.data);r.numberOfChannels=u.getUint8(11),r.sampleRate=u.getUint32(12,!0);let f=u.getUint8(28);r.codecInfo.vorbisInfo={blocksizes:[1<<(f&15),1<<(f>>4)],modeBlockflags:zx(s.data).modeBlockflags},sp(i.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,r){let n=await this.findNextPacketStart(e);if(!n)return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i)return;r.codecInfo.codec="opus",r.description=e.data,r.lastMetadataPacket=i;let s=Ja(e.data);r.numberOfChannels=s.outputChannelCount,r.sampleRate=Qi,r.codecInfo.opusInfo={preSkip:s.preSkip},sp(i.data.subarray(8),this.metadataTags)}async readPacket(e,r){x(r<e.lacingValues.length);let n=0;for(let d=0;d<r;d++)n+=e.lacingValues[d];let i=e,s=n,a=r,c=[];e:for(;;){let d=this.reader.requestSlice(i.dataStartPos,i.dataSize);d instanceof Promise&&(d=await d),x(d);let h=se(d,i.dataSize);for(;;){if(a===i.lacingValues.length){c.push(h.subarray(n,s));break}let p=i.lacingValues[a];if(s+=p,p<255){c.push(h.subarray(n,s));break e}a++}let m=i.headerStartPos+i.totalSize;for(;;){let p=this.reader.requestSliceRange(m,oc,$l);if(p instanceof Promise&&(p=await p),!p)return null;let g=hd(p);if(!g)return null;if(i=g,i.serialNumber===e.serialNumber)break;m=i.headerStartPos+i.totalSize}n=0,s=0,a=0}let l=c.reduce((d,h)=>d+h.length,0);if(l===0)return null;let u=new Uint8Array(l),f=0;for(let d=0;d<c.length;d++){let h=c[d];u.set(h,f),f+=h.length}return{data:u,endPage:i,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let n=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let i=this.reader.requestSliceRange(n,oc,$l);if(i instanceof Promise&&(i=await i),!i)return null;let s=hd(i);if(!s)return null;if(s.serialNumber===e.endPage.serialNumber)return{startPage:s,startSegmentIndex:0};n=s.headerStartPos+s.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(r=>r.getCodecParameterString()));return dk({codecStrings:e.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...r)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},xI=class{static{o(this,"OggAudioTrackBacking")}constructor(e,r){this.bitstream=e,this.demuxer=r,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Tn,this.internalSampleRate=e.codecInfo.codec==="opus"?Qi:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumber(){let e=this.demuxer.tracks.findIndex(r=>r._backing.bitstream===this.bitstream);return x(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return x(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return Ft}getDisposition(){return{...jr}}async getFirstTimestamp(){return 0}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(x(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,r,n){if(!e)return null;let{durationInSamples:i,vorbisBlockSize:s}=fk(e.data,this.bitstream.codecInfo,r.vorbisLastBlocksize),a=new je(n.metadataOnly?Wt:e.data,"key",Math.max(0,r.timestampInSamples)/this.internalSampleRate,i/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:r.timestampInSamples,durationInSamples:i,vorbisLastBlockSize:r.vorbisLastBlocksize,vorbisBlockSize:s}),a}async getFirstPacket(e){x(this.bitstream.lastMetadataPacket);let r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let n=0;this.bitstream.codecInfo.codec==="opus"&&(x(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let i=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(i,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,r){let n=this.encodedPacketToMetadata.get(e);if(!n)throw new Error("Packet was not created from this track.");let i=await this.demuxer.findNextPacketStart(n.packet);if(!i)return null;let s=n.timestampInSamples+n.durationInSamples,a=await this.demuxer.readPacket(i.startPage,i.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:s,vorbisLastBlocksize:n.vorbisBlockSize},r)}async getPacket(e,r){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,r);let n=Do(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(r);if(n<0)return null;x(this.bitstream.lastMetadataPacket);let i=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!i)return null;let s=i.startPage,a=this.demuxer.reader.fileSize,c=[s];e:for(;s.headerStartPos+s.totalSize<a;){let w=s.headerStartPos,k=Math.floor((w+a)/2),T=k;for(;;){let v=Math.min(T+mk,a-oc),S=this.demuxer.reader.requestSlice(T,v-T);if(S instanceof Promise&&(S=await S),x(S),!_U(S,v)){a=k+oc;continue e}let P=this.demuxer.reader.requestSliceRange(S.filePos,oc,$l);P instanceof Promise&&(P=await P),x(P);let N=hd(P);x(N);let O=!1;if(N.serialNumber===this.bitstream.serialNumber)O=!0;else{let A=this.demuxer.reader.requestSlice(N.headerStartPos,N.totalSize);A instanceof Promise&&(A=await A),x(A);let R=se(A,N.totalSize);O=uk(R)===N.checksum}if(!O){T=N.headerStartPos+4;continue}if(O&&N.serialNumber!==this.bitstream.serialNumber){T=N.headerStartPos+N.totalSize;continue}if(N.granulePosition===-1){T=N.headerStartPos+N.totalSize;continue}this.granulePositionToTimestampInSamples(N.granulePosition)>n?a=N.headerStartPos:(s=N,c.push(N));continue e}}let l=i.startPage;for(let w of c){if(w.granulePosition===s.granulePosition)break;(!l||w.headerStartPos>l.headerStartPos)&&(l=w)}let u=l,f=[u];for(;!(u.serialNumber===this.bitstream.serialNumber&&u.granulePosition===s.granulePosition);){let w=u.headerStartPos+u.totalSize,k=this.demuxer.reader.requestSliceRange(w,oc,$l);k instanceof Promise&&(k=await k),x(k);let T=hd(k);x(T),u=T,u.serialNumber===this.bitstream.serialNumber&&f.push(u)}x(u.granulePosition!==-1);let d=null,h,m,p=u,g=0;if(u.headerStartPos===i.startPage.headerStartPos)h=this.granulePositionToTimestampInSamples(0),m=!0,d=0;else{h=0,m=!1;for(let T=u.lacingValues.length-1;T>=0;T--)if(u.lacingValues[T]<255){d=T+1;break}if(d===null)throw new Error("Invalid page with granule position: no packets end on this page.");g=d-1;let w={data:Wt,endPage:p,endSegmentIndex:g};if(await this.demuxer.findNextPacketStart(w)){let T=OU(f,u,d);x(T);let v=MU(f,T.page,T.segmentIndex);v&&(u=v.page,d=v.segmentIndex)}else for(;;){let T=OU(f,u,d);if(!T)break;let v=MU(f,T.page,T.segmentIndex);if(!v)break;if(u=v.page,d=v.segmentIndex,T.page.headerStartPos!==p.headerStartPos){p=T.page,g=T.segmentIndex;break}}}let y=null,b=null;for(;u!==null;){x(d!==null);let w=await this.demuxer.readPacket(u,d);if(!w)break;if(!(u.headerStartPos===i.startPage.headerStartPos&&d<i.startSegmentIndex)){let v=this.createEncodedPacketFromOggPacket(w,{timestampInSamples:h,vorbisLastBlocksize:b?.vorbisBlockSize??null},r);x(v);let S=this.encodedPacketToMetadata.get(v);if(x(S),!m&&w.endPage.headerStartPos===p.headerStartPos&&w.endSegmentIndex===g?(h=this.granulePositionToTimestampInSamples(u.granulePosition),m=!0,v=this.createEncodedPacketFromOggPacket(w,{timestampInSamples:h-S.durationInSamples,vorbisLastBlocksize:b?.vorbisBlockSize??null},r),x(v),S=this.encodedPacketToMetadata.get(v),x(S)):h+=S.durationInSamples,y=v,b=S,m&&(Math.max(h,0)>n||Math.max(S.timestampInSamples,0)===n))break}let T=await this.demuxer.findNextPacketStart(w);if(!T)break;u=T.startPage,d=T.startSegmentIndex}return y}async getPacketSequential(e,r){let n=await this.sequentialScanMutex.acquire();try{let i=Do(e*this.internalSampleRate);e=i/this.internalSampleRate;let s=ze(this.sequentialScanCache,i,l=>l.timestampInSamples),a;if(s!==-1){let l=this.sequentialScanCache[s];a=this.createEncodedPacketFromOggPacket(l.packet,{timestampInSamples:l.timestampInSamples,vorbisLastBlocksize:l.vorbisLastBlockSize},r)}else a=await this.getFirstPacket(r);let c=0;for(;a&&a.timestamp<e;){let l=await this.getNextPacket(a,r);if(!l||l.timestamp>e)break;if(a=l,c++,c===100){c=0;let u=this.encodedPacketToMetadata.get(a);x(u),this.sequentialScanCache.length>0&&x(Ze(this.sequentialScanCache).timestampInSamples<=u.timestampInSamples),this.sequentialScanCache.push(u)}}return a}finally{n()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}},MU=o((t,e,r)=>{let n=e,i=r;e:for(;;){for(i--,i;i>=0;i--)if(n.lacingValues[i]<255){i++;break e}if(x(i===-1),!(n.headerType&1)){i=0;break}let a=BP(t,c=>c.headerStartPos<n.headerStartPos);if(!a)return null;n=a,i=n.lacingValues.length}if(x(i!==-1),i===n.lacingValues.length){let s=t[t.indexOf(n)+1];x(s),n=s,i=0}return{page:n,segmentIndex:i}},"findPacketStartPosition"),OU=o((t,e,r)=>{if(r>0)return{page:e,segmentIndex:r-1};let n=BP(t,i=>i.headerStartPos<e.headerStartPos);return n?{page:n,segmentIndex:n.lacingValues.length-1}:null},"findPreviousPacketEndPosition")});var _n,gk,md,kI,TI=he(()=>{Fo();Xi();lr();Ue();Qn();qt();sc();(function(t){t[t.PCM=1]="PCM",t[t.IEEE_FLOAT=3]="IEEE_FLOAT",t[t.ALAW=6]="ALAW",t[t.MULAW=7]="MULAW",t[t.EXTENSIBLE=65534]="EXTENSIBLE"})(_n||(_n={}));gk=class extends wr{static{o(this,"WaveDemuxer")}constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.tracks=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),x(e);let r=It(e,4),n=r!=="RIFX",i=r==="RF64",s=Vo(e,n),a=i?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(It(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let l=0,u=null,f=e.filePos;for(;a===null||f<a;){let h=this.reader.requestSlice(f,8);if(h instanceof Promise&&(h=await h),!h)break;let m=It(h,4),p=Vo(h,n),g=h.filePos;if(i&&l===0&&m!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(m==="fmt ")await this.parseFmtChunk(g,p,n);else if(m==="data"){if(u??=p,this.dataStart=h.filePos,this.dataSize=Math.min(u,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(m==="ds64"){let y=this.reader.requestSlice(g,p);if(y instanceof Promise&&(y=await y),!y)break;let b=SI(y,n);u=SI(y,n),a=Math.min(b+8,this.reader.fileSize??1/0)}else m==="LIST"?await this.parseListChunk(g,p,n):(m==="ID3 "||m==="id3 ")&&await this.parseId3Chunk(g,p);f=g+p+(p&1),l++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.tracks.push(new Et(this.input,new kI(this)))})()}async parseFmtChunk(e,r,n){let i=this.reader.requestSlice(e,r);if(i instanceof Promise&&(i=await i),!i)return;let s=pd(i,n),a=pd(i,n),c=Vo(i,n);i.skip(4);let l=pd(i,n),u;if(r===14?u=8:u=pd(i,n),r>=18&&s!==357){let f=pd(i,n),d=r-18;if(Math.min(d,f)>=22&&s===_n.EXTENSIBLE){i.skip(6);let m=se(i,16);s=m[0]|m[1]<<8}}(s===_n.MULAW||s===_n.ALAW)&&(u=8),this.audioInfo={format:s,numberOfChannels:a,sampleRate:c,sampleSizeInBytes:Math.ceil(u/8),blockSizeInBytes:l}}async parseListChunk(e,r,n){let i=this.reader.requestSlice(e,r);if(i instanceof Promise&&(i=await i),!i)return;let s=It(i,4);if(s!=="INFO"&&s!=="INF0")return;let a=i.filePos;for(;a<=e+r-8;){i.filePos=a;let c=It(i,4),l=Vo(i,n),u=se(i,l),f=0;for(let h=0;h<u.length&&u[h]!==0;h++)f++;let d=String.fromCharCode(...u.subarray(0,f));switch(this.metadataTags.raw??={},this.metadataTags.raw[c]=d,c){case"INAM":case"TITL":this.metadataTags.title??=d;break;case"TIT3":this.metadataTags.description??=d;break;case"IART":this.metadataTags.artist??=d;break;case"IPRD":this.metadataTags.album??=d;break;case"IPRT":case"ITRK":case"TRCK":{let h=d.split("/"),m=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(m)&&m>0&&(this.metadataTags.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{let h=new Date(d);Number.isNaN(h.getTime())||(this.metadataTags.date??=h)}break;case"YEAR":{let h=Number.parseInt(d,10);Number.isInteger(h)&&h>0&&(this.metadataTags.date??=new Date(h,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=d;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=d;break}a+=8+l+(l&1)}}async parseId3Chunk(e,r){let n=this.reader.requestSlice(e,r);if(n instanceof Promise&&(n=await n),!n)return;let i=ns(n);if(i){let s=r-Xn;if(i.size=Math.min(i.size,s),i.size>0){let a=n.slice(e+Xn,i.size);dd(a,i,this.metadataTags)}}}getCodec(){if(x(this.audioInfo),this.audioInfo.format===_n.MULAW)return"ulaw";if(this.audioInfo.format===_n.ALAW)return"alaw";if(this.audioInfo.format===_n.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===_n.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return x(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},md=2048,kI=class{static{o(this,"WaveAudioTrackBacking")}constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return x(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(x(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return x(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return x(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return x(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Ft}getDisposition(){return{...jr}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,r){x(e>=0),x(this.demuxer.audioInfo);let n=e*md*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let i=Math.min(md*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let l=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,i);if(l instanceof Promise&&(l=await l),!l)return null}let s;if(r.metadataOnly)s=Wt;else{let l=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,i);l instanceof Promise&&(l=await l),x(l),s=se(l,i)}let a=e*md/this.demuxer.audioInfo.sampleRate,c=i/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new je(s,"key",a,c,e,i)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,r){x(this.demuxer.audioInfo);let n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/md,(this.demuxer.dataSize-1)/(md*this.demuxer.audioInfo.blockSizeInBytes)));if(n<0)return null;let i=await this.getPacketAtIndex(n,r);if(i)return i;if(n===0)return null;x(this.demuxer.reader.fileSize===null);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,r);for(;s;){let a=await this.getNextPacket(s,r);if(!a)break;s=a}return s}getNextPacket(e,r){x(this.demuxer.audioInfo);let n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/md);return this.getPacketAtIndex(n+1,r)}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}}});var Wo,Jn,Dn,gd=he(()=>{Ti();qt();Wo=7,Jn=9,Dn=o(t=>{let e=t.filePos,r=se(t,9),n=new Te(r);if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let a=n.readBits(1),c=n.readBits(2)+1,l=n.readBits(4);if(l===15)return null;n.skipBits(1);let u=n.readBits(3);if(u===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let f=n.readBits(13);n.skipBits(11);let d=n.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let h=null;return a===1?t.filePos-=2:h=n.readBits(16),{objectType:c,samplingFrequencyIndex:l,channelConfiguration:u,frameLength:f,numberOfAacFrames:d,crcCheck:h,startPos:e}},"readAdtsFrameHeader")});var Pp,yk,vI,EI=he(()=>{qs();Fo();sc();Xi();lr();Ue();Qn();qt();gd();Pp=1024,yk=class extends wr{static{o(this,"AdtsDemuxer")}constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new Tn,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();x(this.firstFrameHeader),this.tracks=[new Et(this.input,new vI(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,Xn);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let c=ns(a);if(!c)break;this.lastLoadedPos=a.filePos+c.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,Wo,Jn);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let r=Dn(e);if(!r){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&r.startPos+r.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=r);let n=vi[r.samplingFrequencyIndex];x(n!==void 0);let i=Pp/n,s={timestamp:this.nextTimestampInSamples/n,duration:i,dataStart:r.startPos,dataSize:r.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=Pp,this.lastLoadedPos=r.startPos+r.frameLength}async getMimeType(){return"audio/aac"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return x(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let r=0;for(;;){let n=this.reader.requestSlice(r,Xn);if(n instanceof Promise&&(n=await n),!n)break;let i=ns(n);if(!i)break;let s=this.reader.requestSlice(n.filePos,i.size);if(s instanceof Promise&&(s=await s),!s)break;dd(s,i,this.metadataTags),r=n.filePos+i.size}return this.metadataTags}finally{e()}}},vI=class{static{o(this,"AdtsAudioTrackBacking")}constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/Pp}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return Ft}getCodec(){return"aac"}getInternalCodecId(){return x(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){x(this.demuxer.firstFrameHeader);let e=Ws[this.demuxer.firstFrameHeader.channelConfiguration];return x(e!==void 0),e}getSampleRate(){x(this.demuxer.firstFrameHeader);let e=vi[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return x(e!==void 0),e}getDisposition(){return{...jr}}async getDecoderConfig(){return x(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,r){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(r.metadataOnly)i=Wt;else{let s=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;i=se(s,n.dataSize)}return new je(i,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{let i=_o(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(i===-1)throw new Error("Packet was not created from this track.");let s=i+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,r)}finally{n()}}async getPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let i=ze(this.demuxer.loadedSamples,e,s=>s.timestamp);if(i===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,r);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,r);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}}});var bk,NU,wk,xk,AU,FU,CI=he(()=>{Ti();Ue();qt();bk=o(t=>t===0?null:t===1?192:t>=2&&t<=5?144*2**t:t===6?"uncommon-u8":t===7?"uncommon-u16":t>=8&&t<=15?2**t:null,"getBlockSizeOrUncommon"),NU=o((t,e)=>{switch(t){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},"getSampleRateOrUncommon"),wk=o(t=>{let e=0,r=new Te(se(t,1));for(;r.readBits(1)===1;)e++;if(e===0)return r.readBits(7);let n=[],i=e-1,s=new Te(se(t,i)),a=8-e-1;for(let l=0;l<a;l++)n.unshift(r.readBits(1));for(let l=0;l<i;l++)for(let u=0;u<8;u++){let f=s.readBits(1);u<2||n.unshift(f)}return n.reduce((l,u,f)=>l|u<<f,0)},"readCodedNumber"),xk=o((t,e)=>{if(e==="uncommon-u16")return jt(t)+1;if(e==="uncommon-u8")return oe(t)+1;if(typeof e=="number")return e;kt(e),x(!1)},"readBlockSize"),AU=o((t,e)=>e==="uncommon-u16"?jt(t):e==="uncommon-u16-10"?jt(t)*10:e==="uncommon-u8"?oe(t):typeof e=="number"?e:null,"readSampleRate"),FU=o(t=>{let r=0;for(let n of t){r^=n;for(let i=0;i<8;i++)(r&128)!==0?r=r<<1^7:r<<=1,r&=255}return r},"calculateCrc8")});var kk,PI,LU=he(()=>{sn();Fo();Xi();Ue();Qn();qt();lr();CI();Ti();kk=class extends wr{static{o(this,"FlacDemuxer")}constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new Tn,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),x(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),x(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;this.reader.fileSize===null||e<this.reader.fileSize;){let r=this.reader.requestSlice(e,4);if(r instanceof Promise&&(r=await r),e+=4,r===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);x(r);let n=oe(r),i=nc(r),s=(n&128)!==0;switch(n&127){case Ei.STREAMINFO:{let c=this.reader.requestSlice(e,i);if(c instanceof Promise&&(c=await c),x(c),c===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let l=se(c,34),u=new Te(l),f=u.readBits(16),d=u.readBits(16),h=u.readBits(24),m=u.readBits(24),p=u.readBits(20),g=u.readBits(3)+1;u.readBits(5);let y=u.readBits(36);u.skipBits(128);let b=new Uint8Array(42);b.set(new Uint8Array([102,76,97,67]),0),b.set(new Uint8Array([128,0,0,34]),4),b.set(l,8),this.audioInfo={numberOfChannels:g,sampleRate:p,totalSamples:y,minimumBlockSize:f,maximumBlockSize:d,minimumFrameSize:h,maximumFrameSize:m,description:b},this.track=new Et(this.input,new PI(this));break}case Ei.VORBIS_COMMENT:{let c=this.reader.requestSlice(e,i);c instanceof Promise&&(c=await c),x(c),sp(se(c,i),this.metadataTags);break}case Ei.PICTURE:{let c=this.reader.requestSlice(e,i);c instanceof Promise&&(c=await c),x(c);let l=X(c),u=X(c),f=br.decode(se(c,u)),d=X(c),h=br.decode(se(c,d));c.skip(16);let m=X(c),p=se(c,m);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:f,kind:l===3?"coverFront":l===4?"coverBack":"unknown",description:h});break}default:break}if(e+=i,s){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:r}){x(this.audioInfo);let n=6,i=16,s=10,a=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+i+2,c=this.audioInfo.minimumFrameSize||s,u=(this.audioInfo.maximumFrameSize||a)+i,f=await this.reader.requestSliceRange(e,i,u);if(!f)return null;let d=this.readFlacFrameHeader({slice:f,isFirstPacket:r});if(!d)return null;for(f.filePos=e+c;;){if(f.filePos>f.end-n)return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:f.end-e,isLastFrame:!0};if(oe(f)===255){let m=f.filePos,p=oe(f),g=this.blockingBit===1?249:248;if(p!==g){f.filePos=m;continue}f.skip(-2);let y=f.filePos-e,b=this.readFlacFrameHeader({slice:f,isFirstPacket:!1});if(!b){f.filePos=m;continue}if(this.blockingBit===0){if(b.num-d.num!==1){f.filePos=m;continue}}else if(b.num-d.num!==d.blockSize){f.filePos=m;continue}return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:y,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:r}){let n=e.filePos,i=se(e,4),s=new Te(i);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){x(r);let y=s.readBits(1);this.blockingBit=y}else if(this.blockingBit===1){if(x(!r),s.readBits(1)!==1)return null}else if(this.blockingBit===0){if(x(!r),s.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let c=bk(s.readBits(4));if(!c)return null;x(this.audioInfo);let l=NU(s.readBits(4),this.audioInfo.sampleRate);if(!l||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;let f=wk(e),d=xk(e,c),h=AU(e,l);if(h===null||h!==this.audioInfo.sampleRate)return null;let m=e.filePos-n,p=oe(e);e.skip(-m),e.skip(-1);let g=FU(se(e,m));return p!==g?null:{num:f,blockSize:d,sampleRate:h}}async advanceReader(){await this.readMetadata(),x(this.lastLoadedPos!==null),x(this.audioInfo);let e=this.lastLoadedPos,r=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!r){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:r.blockSize,byteOffset:e,byteSize:r.size};if(this.lastLoadedPos=this.lastLoadedPos+r.size,this.loadedSamples.push(s),r.isLastFrame){this.lastSampleLoaded=!0;return}}},PI=class{static{o(this,"FlacAudioTrackBacking")}constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return x(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return x(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Ft}getTimeResolution(){return x(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...jr}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return x(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,r){if(x(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");let n=await this.demuxer.readingMutex.acquire();try{for(;;){let i=ze(this.demuxer.loadedSamples,e,l=>l.blockOffset/this.demuxer.audioInfo.sampleRate);if(i===-1){await this.demuxer.advanceReader();continue}let s=this.demuxer.loadedSamples[i],a=s.blockOffset/this.demuxer.audioInfo.sampleRate,c=s.blockSize/this.demuxer.audioInfo.sampleRate;if(a+c<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,r);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(i,r)}}finally{n()}}async getNextPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{let i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,r)}finally{n()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}async getPacketAtIndex(e,r){let n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(r.metadataOnly)i=Wt;else{let c=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(c instanceof Promise&&(c=await c),!c)return null;i=se(c,n.byteSize)}x(this.demuxer.audioInfo);let s=n.blockOffset/this.demuxer.audioInfo.sampleRate,a=n.blockSize/this.demuxer.audioInfo.sampleRate;return new je(i,"key",s,a,e,n.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}});var Zn,kr,Sk,Tk=he(()=>{Zn=9e4,kr=188,Sk=o(t=>{let e="video/MP2T",r=[...new Set(t.filter(Boolean))];return r.length>0&&(e+=`; codecs="${r.join(", ")}"`),e},"buildMpegTsMimeType")});var Ek,Hl,Ip,vk,II,_I,DI,Lee,_p,Dp,BU=he(()=>{EI();gd();qs();Zt();sn();Fo();Xi();lr();Ue();Ka();Qn();qt();Tk();Ox();Ti();Ek=class extends wr{static{o(this,"MpegTsDemuxer")}constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.tracks=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=205,r=this.reader.requestSlice(0,e);r instanceof Promise&&(r=await r),x(r);let n=se(r,e);if(n[0]===71&&n[188]===71)this.packetOffset=0,this.packetStride=188;else if(n[0]===71&&n[204]===71)this.packetOffset=0,this.packetStride=204;else if(n[4]===71&&n[196]===71)this.packetOffset=4,this.packetStride=192;else throw new Error("Unreachable.");let i=256;this.minReferencePointByteDistance=i*this.packetStride;let s=this.packetOffset,a=null,c=!1,l=!1;for(;;){let u=await this.readPacketHeader(s);if(!u)break;if(u.payloadUnitStartIndicator===0){s+=this.packetStride;continue}let f=await this.readSection(s,!0,!l);if(!f)break;let d=3,h=32,m=!1;if(!l&&f.pid!==0&&!(f.payload[0]===0&&f.payload[1]===0&&f.payload[2]===1)){let y=new Te(f.payload),b=y.readAlignedByte();y.skipBits(8*b),m=y.readBits(8)===2}if(f.pid===0&&!c){let g=new Te(f.payload),y=g.readAlignedByte();g.skipBits(8*y),g.skipBits(14);let b=g.readBits(10);for(g.skipBits(40);8*(b+d)-g.pos>h;){let w=g.readBits(16);g.skipBits(3);let k=g.readBits(13);if(w!==0){if(a!==null)throw new Error("Only files with a single program are supported.");a=k}}if(a===null)throw new Error("Program Association Table must link to a Program Map Table.");c=!0}else if((f.pid===a||m)&&!l){let g=new Te(f.payload),y=g.readAlignedByte();g.skipBits(8*y),g.skipBits(12);let b=g.readBits(12);g.skipBits(43);let w=g.readBits(13);g.skipBits(6);let k=g.readBits(10);for(g.skipBits(8*k);8*(b+d)-g.pos>h;){let T=g.readBits(8);g.skipBits(3);let v=g.readBits(13);g.skipBits(6);let S=g.readBits(10),M=g.pos+8*S,P=!1,N=!1;for(;g.pos<M;){let Y=g.readBits(8),A=g.readBits(8);Y===106?P=!0:(Y===122||Y===204)&&(N=!0),g.skipBits(8*A)}let O=null;switch(T){case 3:case 4:case 15:O={type:"audio",codec:T===15?"aac":"mp3",aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;case 27:case 36:O={type:"video",codec:T===27?"avc":"hevc",avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 129:O={type:"audio",codec:"ac3",aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;case 135:O={type:"audio",codec:"eac3",aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;case 6:N?O={type:"audio",codec:"eac3",aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:P&&(O={type:"audio",codec:"ac3",aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:console.warn(`Unsupported stream_type 0x${T.toString(16)}; ignoring stream.`)}O&&this.elementaryStreams.push({demuxer:this,pid:v,streamType:T,initialized:!1,firstSection:null,info:O,referencePesPackets:[]})}l=!0}else{let g=this.elementaryStreams.find(y=>y.pid===f.pid);if(g&&!g.initialized){let y=Ip(f);if(!y)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${g.pid}`);if(g.firstSection=f,g.info.type==="video")if(g.info.codec==="avc"){if(g.info.avcCodecInfo=Jf(y.data),!g.info.avcCodecInfo)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from first packet.");let b=g.info.avcCodecInfo.sequenceParameterSets[0];x(b);let w=ip(b);g.info.width=w.displayWidth,g.info.height=w.displayHeight,w.pixelAspectRatio.num>w.pixelAspectRatio.den?(g.info.squarePixelWidth=Math.round(g.info.width*w.pixelAspectRatio.num/w.pixelAspectRatio.den),g.info.squarePixelHeight=g.info.height):(g.info.squarePixelWidth=g.info.width,g.info.squarePixelHeight=Math.round(g.info.height*w.pixelAspectRatio.den/w.pixelAspectRatio.num)),g.info.colorSpace={primaries:Cl[w.colourPrimaries],transfer:Pl[w.transferCharacteristics],matrix:Il[w.matrixCoefficients],fullRange:!!w.fullRangeFlag},g.info.reorderSize=w.maxDecFrameBuffering,g.initialized=!0}else if(g.info.codec==="hevc"){if(g.info.hevcCodecInfo=Zf(y.data),!g.info.hevcCodecInfo)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");let w=g.info.hevcCodecInfo.arrays.find(T=>T.nalUnitType===vt.SPS_NUT).nalUnits[0];x(w);let k=GP(w);g.info.width=k.displayWidth,g.info.height=k.displayHeight,k.pixelAspectRatio.num>k.pixelAspectRatio.den?(g.info.squarePixelWidth=Math.round(g.info.width*k.pixelAspectRatio.num/k.pixelAspectRatio.den),g.info.squarePixelHeight=g.info.height):(g.info.squarePixelWidth=g.info.width,g.info.squarePixelHeight=Math.round(g.info.height*k.pixelAspectRatio.den/k.pixelAspectRatio.num)),g.info.colorSpace={primaries:Cl[k.colourPrimaries],transfer:Pl[k.transferCharacteristics],matrix:Il[k.matrixCoefficients],fullRange:!!k.fullRangeFlag},g.info.reorderSize=k.maxDecFrameBuffering,g.initialized=!0}else throw new Error("Unhandled.");else if(g.info.codec==="aac"){let b=xr.tempFromBytes(y.data),w=Dn(b);if(!w)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");g.info.aacCodecInfo={isMpeg2:!1,objectType:w.objectType},g.info.numberOfChannels=Ws[w.channelConfiguration],g.info.sampleRate=vi[w.samplingFrequencyIndex],g.initialized=!0}else if(g.info.codec==="mp3"){let b=X(xr.tempFromBytes(y.data)),w=Ol(b,y.data.byteLength);if(!w.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");g.info.numberOfChannels=w.header.channel===3?1:2,g.info.sampleRate=w.header.sampleRate,g.initialized=!0}else if(g.info.codec==="ac3"){let b=$x(y.data);if(!b)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(b.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");g.info.numberOfChannels=ap[b.acmod]+b.lfeon,g.info.sampleRate=Rl[b.fscod],g.initialized=!0}else if(g.info.codec==="eac3"){let b=Hx(y.data);if(!b)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");let w=Vx(b);if(w===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");g.info.numberOfChannels=Wx(b),g.info.sampleRate=w,g.initialized=!0}else throw new Error("Unhandled.")}}if(l&&this.elementaryStreams.every(g=>g.initialized))break;s+=this.packetStride}if(!l)throw c?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(let u of this.elementaryStreams)u.info.type==="video"?this.tracks.push(new Pn(this.input,new II(u))):this.tracks.push(new Et(this.input,new _I(u)))})()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return{}}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...r)}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.getCodecParameterString()));return Sk(r)}async readSection(e,r,n=!1){let i=e,s=e,a=[],c=0,l=null,u=!0,f=0;for(;;){let h=await this.readPacket(s);if(s+=this.packetStride,!h)break;if(l){if(h.pid!==l.pid){if(n)break;continue}if(h.payloadUnitStartIndicator===1)break}else{if(h.payloadUnitStartIndicator===0)break;l=h}let m=!!(h.adaptationFieldControl&2),p=!!(h.adaptationFieldControl&1),g=0;if(m&&(g=1+h.body[0],h===l&&g>1&&(f=h.body[1]>>6&1)),p&&(g===0?(a.push(h.body),c+=h.body.byteLength):(a.push(h.body.subarray(g)),c+=h.body.byteLength-g)),i=s,!r&&c>=64){u=!1;break}if(_o(this.sectionEndPositions,i,b=>b)!==-1){u=!1;break}}if(u){let h=ze(this.sectionEndPositions,i,m=>m);this.sectionEndPositions.splice(h+1,0,i)}if(!l)return null;let d;if(a.length===1)d=a[0];else{let h=a.reduce((p,g)=>p+g.length,0);d=new Uint8Array(h);let m=0;for(let p of a)d.set(p,m),m+=p.length}return{startPos:e,endPos:r?i:null,pid:l.pid,payload:d,randomAccessIndicator:f}}async readPacketHeader(e){let r=this.reader.requestSlice(e,4);if(r instanceof Promise&&(r=await r),!r)return null;if(oe(r)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let i=jt(r),s=i>>15,a=i>>14&1,c=i>>13&1,l=i&8191,u=oe(r),f=u>>6,d=u>>4&3,h=u&15;return{payloadUnitStartIndicator:a,pid:l,adaptationFieldControl:d}}async readPacket(e){let r=this.reader.requestSlice(e,188);if(r instanceof Promise&&(r=await r),!r)return null;let n=se(r,188);if(n[0]!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let s=(n[1]<<8)+n[2],a=s>>15,c=s>>14&1,l=s>>13&1,u=s&8191,f=n[3],d=f>>6,h=f>>4&3,m=f&15;return{payloadUnitStartIndicator:c,pid:u,adaptationFieldControl:h,body:n.subarray(4)}}},Hl=o(t=>{if(t.payload.byteLength<3)return null;let e=new Te(t.payload);if(e.readBits(24)!==1)return null;let n=e.readBits(8);if(e.skipBits(16),n===188||n===190||n===191||n===240||n===241||n===255||n===242||n===248)return null;e.skipBits(8);let i=e.readBits(2);e.skipBits(14);let s=0;if(i===2||i===3)e.skipBits(4),s+=e.readBits(3)*(1<<30),e.skipBits(1),s+=e.readBits(15)*32768,e.skipBits(1),s+=e.readBits(15);else throw new Error("PES packets without PTS are not currently supported. If you think this file should be supported, please report it.");return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:s,randomAccessIndicator:t.randomAccessIndicator}},"readPesPacketHeader"),Ip=o(t=>{x(t.endPos!==null);let e=Hl(t);if(!e)return null;let r=new Te(t.payload);r.skipBits(32);let n=r.readBits(16),i=6;r.skipBits(16);let s=r.readBits(8),a=r.pos+8*s;r.pos=a;let c=a/8;x(Number.isInteger(c));let l=t.payload.subarray(c,n>0?i+n:t.payload.byteLength);return{...e,data:l}},"readPesPacket"),vk=class t{static{o(this,"MpegTsTrackBacking")}constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let e=this.elementaryStream.demuxer,r=this.elementaryStream.info.type,n=0;for(let i of e.tracks)if(i.type===r&&n++,x(i._backing instanceof t),i._backing.elementaryStream===this.elementaryStream)break;return n}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return Ft}getDisposition(){return jr}getTimeResolution(){return 9e4}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}createEncodedPacket(e,r,n){let i;return this.allPacketsAreKeyPackets()?i="key":i=e.randomAccessIndicator===1?"key":"delta",new je(n.metadataOnly?Wt:e.data,i,e.pts/9e4,Math.max(r/9e4,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let r=this.elementaryStream.firstSection;x(r);let n=Ip(r);x(n);let i=new _p(this.elementaryStream,n),s=new Dp(this,i),a=await s.readNext();if(!a)return null;let c=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(c,s),this.packetSectionStarts.set(c,a.packet.sectionStartPos),c}async getNextPacket(e,r){let n=this.packetBuffers.get(e);if(n){let f=await n.readNext();if(!f)return null;this.packetBuffers.delete(e);let d=this.createEncodedPacket(f.packet,f.duration,r);return this.packetBuffers.set(d,n),this.packetSectionStarts.set(d,f.packet.sectionStartPos),d}let i=this.packetSectionStarts.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");let a=await this.elementaryStream.demuxer.readSection(i,!0);x(a);let c=Ip(a);x(c);let l=new _p(this.elementaryStream,c);n=new Dp(this,l);let u=e.sequenceNumber;for(;;){let f=await n.readNext();if(!f)return null;if(f.packet.sequenceNumber>u){let d=this.createEncodedPacket(f.packet,f.duration,r);return this.packetBuffers.set(d,n),this.packetSectionStarts.set(d,f.packet.sectionStartPos),d}}}async getNextKeyPacket(e,r){let n=e;for(;;){if(n=await this.getNextPacket(n,r),!n)return null;if(n.type==="key")return n}}getPacket(e,r){return this.doPacketLookup(e,!1,r)}getKeyPacket(e,r){return this.doPacketLookup(e,!0,r)}async doPacketLookup(e,r,n){let i=Do(e*9e4),s=this.elementaryStream.demuxer,{reader:a,seekChunkSize:c}=s,l=this.elementaryStream.pid,u=o(async(k,T)=>{let v=k;for(;v<T;){let S=await s.readPacketHeader(v);if(!S)return null;if(S.pid===l&&S.payloadUnitStartIndicator===1){let M=await s.readSection(v,!1);if(!M)return null;let P=Hl(M);if(P)return P}v+=s.packetStride}return null},"findFirstPesPacketHeaderInChunk"),f=this.elementaryStream.firstSection;x(f);let d=Hl(f);if(x(d),i<d.pts)return null;let h,m=this.elementaryStream.referencePesPackets,p=ze(m,i,k=>k.pts),g=p!==-1?m[p]:null;if(g&&i-g.pts<9e4/2)h=g.sectionStartPos;else{let k=0;if(a.fileSize!==null){let T=Math.ceil(a.fileSize/c);if(T>1){let v=0,S=T-1;for(k=v;v<=S;){let M=Math.floor((v+S)/2),P=Sx(M*c,s.packetStride)+d.sectionStartPos,N=P+c,O=await u(P,N);if(!O){S=M-1;continue}O.pts<=i?(k=M,v=M+1):S=M-1}}}h=Sx(k*c,s.packetStride)+d.sectionStartPos}let y=await u(h,a.fileSize??1/0);y||(y=d);let b=this.getReorderSize(),w=o(async(k,T)=>{let v=await s.readSection(k,!0);x(v);let S=Ip(v);x(S);let M=new _p(this.elementaryStream,S),P=new Dp(this,M);for(;!((Ze(P.presentationOrderPackets)?.pts??-1/0)>=i||!await P.readNextPacket()););let N=qf(P.presentationOrderPackets,T);if(N===-1)return null;let O=P.presentationOrderPackets[N],Y=N===0?0:O.pts-P.presentationOrderPackets[N-1].pts;for(;P.decodeOrderPackets[0]!==O;)P.decodeOrderPackets.shift();P.lastDuration=Y;let A=await P.readNext();x(A);let R=this.createEncodedPacket(A.packet,A.duration,n);return this.packetBuffers.set(R,P),this.packetSectionStarts.set(R,A.packet.sectionStartPos),R},"retrieveEncodedPacket");if(!r||this.allPacketsAreKeyPackets()){e:for(;;){let k=y.sectionStartPos+s.packetStride;for(;;){let T=await s.readPacketHeader(k);if(!T)break e;if(T.pid===l&&T.payloadUnitStartIndicator===1){let v=await s.readSection(k,!1);if(v){let S=Hl(v);if(S){if(S.pts>i)break e;y=S,DI(this.elementaryStream,S);break}}}k+=s.packetStride}}e:for(let k=0;k<b;k++){let T=y.sectionStartPos-s.packetStride;for(;T>=s.packetOffset;){let v=await s.readPacketHeader(T);if(!v)break e;if(v.pid===l&&v.payloadUnitStartIndicator===1){let S=await s.readSection(T,!1);if(S){let M=Hl(S);if(M){y=M;break}}}T-=s.packetStride}}return w(y.sectionStartPos,k=>k.pts<=i)}else{let k=h,T=null;for(;;){let v=null,S=k<=d.sectionStartPos,M;S?(M=d,v=d):M=await u(k,a.fileSize??1/0);let P=!1,N=0;e:for(;M&&!(T!==null&&M.sectionStartPos>=T||(M.randomAccessIndicator===1&&M.pts<=i&&(v=M),M.pts>i&&(P=!0),P&&(N++,N>=b)));){let Y=M.sectionStartPos+s.packetStride;for(;;){let A=await s.readPacketHeader(Y);if(!A)break e;if(A.pid===l&&A.payloadUnitStartIndicator===1){let R=await s.readSection(Y,!1);if(R&&(M=Hl(R),M)){DI(this.elementaryStream,M);break}}Y+=s.packetStride}}if(v){let O=v;if(N===0)e:for(let A=0;A<b-1;A++){let R=O.sectionStartPos-s.packetStride;for(;R>=s.packetOffset;){let F=await s.readPacketHeader(R);if(!F)break e;if(F.pid===l&&F.payloadUnitStartIndicator===1){let $=await s.readSection(R,!1);if($){let W=Hl($);if(W){O=W;break}}}R-=s.packetStride}}let Y=await w(O.sectionStartPos,A=>A.pts<=i&&A.randomAccessIndicator===1);return x(Y),Y}x(!S),T=k,k=Math.max(Sx(k-d.sectionStartPos-c,s.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}},II=class extends vk{static{o(this,"MpegTsVideoTrackBacking")}constructor(e){super(e),this.elementaryStream=e,this.decoderConfig={codec:Gf({width:this.elementaryStream.info.width,height:this.elementaryStream.info.height,codec:this.elementaryStream.info.codec,codecDescription:null,colorSpace:this.elementaryStream.info.colorSpace,avcType:1,avcCodecInfo:this.elementaryStream.info.avcCodecInfo,hevcCodecInfo:this.elementaryStream.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:this.elementaryStream.info.width,codedHeight:this.elementaryStream.info.height,colorSpace:this.elementaryStream.info.colorSpace},(this.elementaryStream.info.width!==this.elementaryStream.info.squarePixelWidth||this.elementaryStream.info.height!==this.elementaryStream.info.squarePixelHeight)&&(this.decoderConfig.displayAspectWidth=this.elementaryStream.info.squarePixelWidth,this.decoderConfig.displayAspectHeight=this.elementaryStream.info.squarePixelHeight)}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return this.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},_I=class extends vk{static{o(this,"MpegTsAudioTrackBacking")}constructor(e){super(e),this.elementaryStream=e}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return{codec:Qf({codec:this.elementaryStream.info.codec,codecDescription:null,aacCodecInfo:this.elementaryStream.info.aacCodecInfo}),numberOfChannels:this.elementaryStream.info.numberOfChannels,sampleRate:this.elementaryStream.info.sampleRate}}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 1}},DI=o((t,e)=>{let r=t.referencePesPackets,n=ze(r,e.sectionStartPos,i=>i.sectionStartPos);if(n>=0){let i=r[n];if(e.pts<=i.pts)return!1;let s=t.demuxer.minReferencePointByteDistance;if(e.sectionStartPos-i.sectionStartPos<s)return!1;if(n<r.length-1){let a=r[n+1];if(a.pts<e.pts||a.sectionStartPos-e.sectionStartPos<s)return!1}}return r.splice(n+1,0,e),!0},"maybeInsertReferencePacket"),Lee=o(async t=>{x(!t.suppliedPacket);let e=t.elementaryStream;if(e.info.type==="video"){let r=e.info.codec,n=1024;if(r!=="avc"&&r!=="hevc")throw new Error("Unhandled.");let i=null;for(;;){let s=t.ensureBuffered(n);if(s instanceof Promise&&(s=await s),s===0)break;let a=t.currentPos,c=t.readBytes(s),l=c.byteLength,u=0;for(;u<l;){let f=c.indexOf(0,u);if(f===-1||f>=l)break;u=f;let d=a+u;if(u+4>=l){t.seekTo(d);break}let h=c[u+1],m=c[u+2],p=c[u+3],g=0,y=null;if(h===0&&m===0&&p===1?(g=4,y=c[u+4]):h===0&&m===1&&(g=3,y=p),g===0){u++;continue}let b=d;if(i===null){i=b,u+=g;continue}if(y!==null){let w=r==="avc"?Ao(y):Gs(y);if(r==="avc"?w===Cn.AUD:w===vt.AUD_NUT){let T=b-i;return t.seekTo(i),t.supplyPacket(T,0)}}u+=g}if(s<n)break}if(i!==null){let s=t.endPos-i;return t.seekTo(i),t.supplyPacket(s,0)}}else{let r=e.info.codec,n=128;for(;;){let i=t.ensureBuffered(n);i instanceof Promise&&(i=await i);let s=t.currentPos;for(;t.currentPos-s<i;){let a=t.readU8();if(r==="aac"){if(a!==255)continue;t.skip(-1);let c=t.currentPos,l=t.ensureBuffered(Jn);if(l instanceof Promise&&(l=await l),l<Jn)return;let u=t.readBytes(Jn),f=Dn(xr.tempFromBytes(u));if(f){t.seekTo(c);let d=t.ensureBuffered(f.frameLength);return d instanceof Promise&&(d=await d),t.supplyPacket(d,Math.round(Pp*9e4/e.info.sampleRate))}else t.seekTo(c+1)}else if(r==="mp3"){if(a!==255)continue;t.skip(-1);let c=t.currentPos,l=t.ensureBuffered(4);if(l instanceof Promise&&(l=await l),l<4)return;let u=t.readBytes(4),f=ge(u).getUint32(0),d=Ol(f,null);if(d.header){t.seekTo(c);let h=t.ensureBuffered(d.header.totalSize);h instanceof Promise&&(h=await h);let m=d.header.audioSamplesInFrame*9e4/e.info.sampleRate;return t.supplyPacket(h,Math.round(m))}else t.seekTo(c+1)}else if(r==="ac3"){if(a!==11)continue;t.skip(-1);let c=t.currentPos,l=t.ensureBuffered(5);if(l instanceof Promise&&(l=await l),l<5)return;let u=t.readBytes(5);if(u[0]!==11||u[1]!==119){t.seekTo(c+1);continue}let f=u[4]>>6,d=u[4]&63;if(f===3||d>37){t.seekTo(c+1);continue}let h=eU[3*d+f];x(h!==void 0),t.seekTo(c),l=t.ensureBuffered(h),l instanceof Promise&&(l=await l);let m=Math.round(tU*9e4/e.info.sampleRate);return t.supplyPacket(l,m)}else if(r==="eac3"){if(a!==11)continue;t.skip(-1);let c=t.currentPos,l=t.ensureBuffered(5);if(l instanceof Promise&&(l=await l),l<5)return;let u=t.readBytes(5);if(u[0]!==11||u[1]!==119){t.seekTo(c+1);continue}let d=(((u[2]&7)<<8|u[3])+1)*2,m=u[4]>>6===3?3:u[4]>>4&3,p=QP[m];t.seekTo(c),l=t.ensureBuffered(d),l instanceof Promise&&(l=await l);let g=p*256,y=Math.round(g*9e4/e.info.sampleRate);return t.supplyPacket(l,y)}else throw new Error("Unhandled.")}if(i<n)break}}},"markNextPacket"),_p=class t{static{o(this,"PacketReadingContext")}constructor(e,r){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.nextPts=0,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=r}clone(){let e=new t(this.elementaryStream,this.startingPesPacket);return e.currentPos=this.currentPos,e.pesPackets=[...this.pesPackets],e.currentPesPacketIndex=this.currentPesPacketIndex,e.currentPesPacketPos=this.currentPesPacketPos,e.endPos=this.endPos,e.nextPts=this.nextPts,e}ensureBuffered(e){let r=this.endPos-this.currentPos;return r>=e?e:this.bufferData(e-r).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){let e=this.pesPackets[this.currentPesPacketIndex];return x(e),e}async bufferData(e){let r=this.endPos+e;for(;this.endPos<r;){let n;if(this.pesPackets.length===0)n=this.startingPesPacket;else{let i=Ze(this.pesPackets).sectionEndPos;for(x(i!==null);;){let s=await this.demuxer.readPacketHeader(i);if(!s)return;if(s.pid===this.pid){let a=await this.demuxer.readSection(i,!0);if(!a)return;let c=Ip(a);if(c){n=c;break}}i+=this.demuxer.packetStride}}this.pesPackets.push(n),this.endPos+=n.data.byteLength,this.pesPackets.length===1&&(this.nextPts=n.pts)}}readBytes(e){let r=this.getCurrentPesPacket(),n=this.currentPos-this.currentPesPacketPos,i=n+e;if(this.currentPos+=e,i<=r.data.byteLength)return r.data.subarray(n,i);let s=new Uint8Array(e);s.set(r.data.subarray(n));let a=r.data.byteLength-n;for(;;){this.advanceCurrentPacket();let c=this.getCurrentPesPacket(),l=e-a;if(l<=c.data.byteLength){s.set(c.data.subarray(0,l),a);break}s.set(c.data,a),a+=c.data.byteLength}return s}readU8(){let e=this.getCurrentPesPacket(),r=this.currentPos-this.currentPesPacketPos;return this.currentPos++,r<e.data.byteLength?e.data[r]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;let r=this.getCurrentPesPacket();this.currentPesPacketPos-=r.data.byteLength,this.nextPts=r.pts}else for(;;){let r=this.getCurrentPesPacket(),n=this.currentPesPacketPos+r.data.byteLength;if(e<n)break;this.currentPesPacketPos+=r.data.byteLength,this.currentPesPacketIndex++,this.nextPts=this.getCurrentPesPacket().pts}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++,this.nextPts=this.getCurrentPesPacket().pts}supplyPacket(e,r){let n=this.getCurrentPesPacket();DI(this.elementaryStream,n);let i=this.nextPts;this.nextPts+=r;let s=n.sectionStartPos,a=s+(this.currentPos-this.currentPesPacketPos),c=this.readBytes(e),l=n.randomAccessIndicator;x(this.elementaryStream.firstSection),n.sectionStartPos===this.elementaryStream.firstSection.startPos&&(l=1),this.suppliedPacket={pts:i,data:c,sequenceNumber:a,sectionStartPos:s,randomAccessIndicator:l},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},Dp=class{static{o(this,"PacketBuffer")}constructor(e,r){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=r,this.reorderSize=e.getReorderSize(),x(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let e=this.decodeOrderPackets[0],r=this.presentationOrderPackets.indexOf(e);x(r!==-1);let n;for(r===this.presentationOrderPackets.length-1?n=this.lastDuration:(n=this.presentationOrderPackets[r+1].pts-e.pts,this.lastDuration=n),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let i=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(i))break;this.presentationOrderPackets.shift()}return{packet:e,duration:n}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket?e=this.context.suppliedPacket:(await Lee(this.context),e=this.context.suppliedPacket),this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){let e=this.decodeOrderPackets[0];for(x(e);;){let r=this.presentationOrderPackets.indexOf(e);if(r!==-1&&r<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>=this.reorderSize){let r=0;for(let i=1;i<this.reorderBuffer.length;i++)this.reorderBuffer[i].pts<this.reorderBuffer[r].pts&&(r=i);let n=this.reorderBuffer.splice(r,1)[0];this.presentationOrderPackets.push(n)}}flushReorderBuffer(){this.reorderBuffer.sort((e,r)=>e.pts-r.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}});var Mn,yd,Mp,Op,bd,Rp,Np,Ap,Fp,Lp,Bp,zp,MI,OI,RI,NI,AI,FI,LI,BI,zI,UI,zU,$I=he(()=>{yU();ik();EU();CU();Ka();sc();yI();RU();TI();gd();EI();qt();LU();BU();Tk();Mn=class{static{o(this,"InputFormat")}},yd=class extends Mn{static{o(this,"IsobmffInputFormat")}async _getMajorBrand(e){let r=e._reader.requestSlice(0,12);return r instanceof Promise&&(r=await r),!r||(r.skip(4),It(r,4)!=="ftyp")?null:It(r,4)}_createDemuxer(e){return new Jx(e)}},Mp=class extends yd{static{o(this,"Mp4InputFormat")}async _canReadInput(e){let r=await this._getMajorBrand(e);return!!r&&r!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Op=class extends yd{static{o(this,"QuickTimeInputFormat")}async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},bd=class extends Mn{static{o(this,"MatroskaInputFormat")}async isSupportedEBMLOfDocType(e,r){let n=e._reader.requestSlice(0,ts);if(n instanceof Promise&&(n=await n),!n)return!1;let i=uI(n);if(i===null||i<1||i>8||Oe(n,i)!==I.EBML)return!1;let a=fI(n);if(typeof a!="number")return!1;let c=e._reader.requestSlice(n.filePos,a);if(c instanceof Promise&&(c=await c),!c)return!1;let l=n.filePos;for(;c.filePos<=l+a-In;){let u=rs(c);if(!u)break;let{id:f,size:d}=u,h=c.filePos;if(d===void 0)return!1;switch(f){case I.EBMLVersion:if(Oe(c,d)!==1)return!1;break;case I.EBMLReadVersion:if(Oe(c,d)!==1)return!1;break;case I.DocType:if(ic(c,d)!==r)return!1;break;case I.DocTypeVersion:if(Oe(c,d)>4)return!1;break}c.filePos=h+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new ck(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Rp=class extends bd{static{o(this,"WebMInputFormat")}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},Np=class extends Mn{static{o(this,"Mp3InputFormat")}async _canReadInput(e){let r=0;for(;;){let d=e._reader.requestSlice(r,Xn);if(d instanceof Promise&&(d=await d),!d)break;let h=ns(d);if(!h)break;r=d.filePos+h.size}let n=await vp(e._reader,r,r+4096);if(!n)return!1;let i=n.header,s=Qa(i.mpegVersionId,i.channel),a=e._reader.requestSlice(n.startPos+s,4);if(a instanceof Promise&&(a=await a),!a)return!1;let c=X(a);if(c===Ga||c===Xf)return!0;r=n.startPos+n.header.totalSize;let u=await vp(e._reader,r,r+4);if(!u)return!1;let f=u.header;return!(i.channel!==f.channel||i.sampleRate!==f.sampleRate)}_createDemuxer(e){return new lk(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},Ap=class extends Mn{static{o(this,"WaveInputFormat")}async _canReadInput(e){let r=e._reader.requestSlice(0,12);if(r instanceof Promise&&(r=await r),!r)return!1;let n=It(r,4);return n!=="RIFF"&&n!=="RIFX"&&n!=="RF64"?!1:(r.skip(4),It(r,4)==="WAVE")}_createDemuxer(e){return new gk(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},Fp=class extends Mn{static{o(this,"OggInputFormat")}async _canReadInput(e){let r=e._reader.requestSlice(0,4);return r instanceof Promise&&(r=await r),r?It(r,4)==="OggS":!1}_createDemuxer(e){return new pk(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},Lp=class extends Mn{static{o(this,"FlacInputFormat")}async _canReadInput(e){let r=e._reader.requestSlice(0,4);return r instanceof Promise&&(r=await r),r?It(r,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new kk(e)}},Bp=class extends Mn{static{o(this,"AdtsInputFormat")}async _canReadInput(e){let r=0;for(;;){let a=e._reader.requestSlice(r,Xn);if(a instanceof Promise&&(a=await a),!a)break;let c=ns(a);if(!c)break;r=a.filePos+c.size}let n=e._reader.requestSliceRange(r,Wo,Jn);if(n instanceof Promise&&(n=await n),!n)return!1;let i=Dn(n);if(!i||(r+=i.frameLength,n=e._reader.requestSliceRange(r,Wo,Jn),n instanceof Promise&&(n=await n),!n))return!1;let s=Dn(n);return s?i.objectType===s.objectType&&i.samplingFrequencyIndex===s.samplingFrequencyIndex&&i.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new yk(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},zp=class extends Mn{static{o(this,"MpegTsInputFormat")}async _canReadInput(e){let r=205,n=e._reader.requestSlice(0,r);if(n instanceof Promise&&(n=await n),!n)return!1;let i=se(n,r);return i[0]===71&&i[188]===71||i[0]===71&&i[204]===71?!0:i[4]===71&&i[196]===71}_createDemuxer(e){return new Ek(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}},MI=new Mp,OI=new Op,RI=new bd,NI=new Rp,AI=new Np,FI=new Ap,LI=new Fp,BI=new Bp,zI=new Lp,UI=new zp,zU=[MI,OI,RI,NI,FI,LI,zI,AI,BI,UI]});var HI=ri(()=>{});var UU,Bee,Ci,Ck,Pk,$U,zee,Ik,_k,$p,Dk,VI,Up,WI=he(()=>{Ue();UU=us(HI(),1);od();Bee=typeof UU<"u"?UU:void 0,Ci=class{static{o(this,"Source")}constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new er;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new er;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}},Ck=class extends Ci{static{o(this,"BufferSource")}constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw new TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super(),this._onreadCalled=!1,this._bytes=qe(e),this._view=ge(e)}_retrieveSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this.onread?.(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}},Pk=class extends Ci{static{o(this,"BlobSource")}constructor(e,r={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.maxCacheSize!==void 0&&(!ja(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new Up({maxCacheSize:r.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:VI.fileSystem})}_retrieveSize(){let e=this._blob.size;return this._orchestrator.fileSize=e,e}_read(e,r){return this._orchestrator.read(e,r)}async _runWorker(e){let r=this._readers.get(e);for(r===void 0&&("stream"in this._blob&&!Wa()?r=this._blob.slice(e.currentPos).stream().getReader():r=null,this._readers.set(e,r));e.currentPos<e.targetPos&&!e.aborted;)if(r){let{done:n,value:i}=await r.read();if(n)throw this._orchestrator.forgetWorker(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else{let n=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+n.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(n))}e.running=!1,e.aborted&&await r?.cancel()}_dispose(){this._orchestrator.dispose()}},$U=.5*2**20,zee=o(((t,e,r)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))){let i=null;try{typeof window<"u"&&typeof window.location<"u"&&(i=new URL(r instanceof Request?r.url:r,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&i!==null&&i!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(t-2),16)}),"DEFAULT_RETRY_DELAY"),Ik=class extends Ci{static{o(this,"UrlSource")}constructor(e,r={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.requestInit!==void 0&&(!r.requestInit||typeof r.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(r.getRetryDelay!==void 0&&typeof r.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(r.maxCacheSize!==void 0&&(!ja(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(r.parallelism!==void 0&&(!Number.isInteger(r.parallelism)||r.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(r.fetchFn!==void 0&&typeof r.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=r,this._getRetryDelay=r.getRetryDelay??zee;let n=2;this._orchestrator=new Up({maxCacheSize:r.maxCacheSize??64*2**20,maxWorkerCount:r.parallelism??n,runWorker:this._runWorker.bind(this),prefetchProfile:VI.network})}async _retrieveSize(){let e=new AbortController,r=await UP(this._options.fetchFn??fetch,this._url,zP(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw new Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);let n,i;if(r.status===206)i=this._getTotalLengthFromRangeResponse(r),n=this._orchestrator.createWorker(0,Math.min(i,$U));else{let s=r.headers.get("Content-Length");if(s)i=Number(s),n=this._orchestrator.createWorker(0,i),this._orchestrator.options.maxCacheSize=1/0,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.");else throw new Error(`HTTP response (status ${r.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=i,this._existingResponses.set(n,{response:r,abortController:e}),this._orchestrator.runWorker(n),i}_read(e,r){return this._orchestrator.read(e,r)}async _runWorker(e){for(;;){let r=this._existingResponses.get(e);this._existingResponses.delete(e);let n=r?.abortController,i=r?.response;if(n||(n=new AbortController,i=await UP(this._options.fetchFn??fetch,this._url,zP(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>this._disposed)),x(i),!i.ok)throw new Error(`Error fetching ${String(this._url)}: ${i.status} ${i.statusText}`);if(e.currentPos>0&&i.status!==206)throw new Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!i.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let s=i.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){n.abort(),e.running=!1;return}let a;try{a=await s.read()}catch(u){if(this._disposed)throw u;let f=this._getRetryDelay(1,u,this._url);if(f!==null){console.error("Error while reading response stream. Attempting to resume.",u),await new Promise(d=>setTimeout(d,1e3*f));break}else throw u}if(e.aborted)continue;let{done:c,value:l}=a;if(c){if(e.currentPos>=e.targetPos){this._orchestrator.forgetWorker(e),e.running=!1;return}break}this.onread?.(e.currentPos,e.currentPos+l.length),this._orchestrator.supplyWorkerData(e,l)}}}_getTotalLengthFromRangeResponse(e){let r=e.headers.get("Content-Range");if(r){let i=/\/(\d+)/.exec(r);if(i)return Number(i[1])}let n=e.headers.get("Content-Length");if(n)return Number(n);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}},_k=class extends Ci{static{o(this,"FilePathSource")}constructor(e,r={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.maxCacheSize!==void 0&&(!ja(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._fileHandle=null,this._streamSource=new $p({getSize:o(async()=>(this._fileHandle=await Bee.fs.open(e,"r"),(await this._fileHandle.stat()).size),"getSize"),read:o(async(n,i)=>{x(this._fileHandle);let s=new Uint8Array(i-n);return await this._fileHandle.read(s,0,i-n,n),s},"read"),maxCacheSize:r.maxCacheSize,prefetchProfile:"fileSystem"})}_read(e,r){return this._streamSource._read(e,r)}_retrieveSize(){return this._streamSource._retrieveSize()}_dispose(){this._streamSource._dispose(),this._fileHandle?.close(),this._fileHandle=null}},$p=class extends Ci{static{o(this,"StreamSource")}constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(typeof e.getSize!="function")throw new TypeError("options.getSize must be a function.");if(typeof e.read!="function")throw new TypeError("options.read must be a function.");if(e.dispose!==void 0&&typeof e.dispose!="function")throw new TypeError("options.dispose, when provided, must be a function.");if(e.maxCacheSize!==void 0&&(!ja(e.maxCacheSize)||e.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(e.prefetchProfile&&!["none","fileSystem","network"].includes(e.prefetchProfile))throw new TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super(),this._options=e,this._orchestrator=new Up({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:VI[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this)})}_retrieveSize(){let e=this._options.getSize();if(e instanceof Promise)return e.then(r=>{if(!Number.isInteger(r)||r<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=r,r});if(!Number.isInteger(e)||e<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=e,e}_read(e,r){return this._orchestrator.read(e,r)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){let r=e.currentPos,n=e.targetPos,i=this._options.read(e.currentPos,n);if(i instanceof Promise&&(i=await i),e.aborted)break;if(i instanceof Uint8Array){if(i=qe(i),i.length!==n-e.currentPos)throw new Error(`options.read returned a Uint8Array with unexpected length: Requested ${n-e.currentPos} bytes, but got ${i.length}.`);this.onread?.(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else if(i instanceof ReadableStream){let s=i.getReader();for(;e.currentPos<n&&!e.aborted;){let{done:a,value:c}=await s.read();if(a){if(e.currentPos<n)throw new Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${n-r} bytes, but got ${e.currentPos-r}`);break}if(!(c instanceof Uint8Array))throw new TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if(e.aborted)break;let l=qe(c);this.onread?.(e.currentPos,e.currentPos+l.length),this._orchestrator.supplyWorkerData(e,l)}}else throw new TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.")}e.running=!1}_dispose(){this._orchestrator.dispose(),this._options.dispose?.()}},Dk=class extends Ci{static{o(this,"ReadableStreamSource")}constructor(e,r={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.maxCacheSize!==void 0&&(!ja(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=e,this._maxCacheSize=r.maxCacheSize??16*2**20}_retrieveSize(){return this._endIndex}_read(e,r){if(this._endIndex!==null&&r>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,r);let n=ze(this._cache,e,f=>f.start),i=n!==-1?this._cache[n]:null;if(i&&i.start<=e&&r<=i.end)return{bytes:i.bytes,view:i.view,offset:i.start};let s=e,a=new Uint8Array(r-e);if(n!==-1)for(let f=n;f<this._cache.length;f++){let d=this._cache[f];if(d.start>=r)break;let h=Math.max(e,d.start);h>s&&this._throwDueToCacheMiss();let m=Math.min(r,d.end);h<m&&(a.set(d.bytes.subarray(h-d.start,m-d.start),h-e),s=m)}if(s===r)return{bytes:a,view:ge(a),offset:e};this._currentIndex>s&&this._throwDueToCacheMiss();let{promise:c,resolve:l,reject:u}=ut();return this._pendingSlices.push({start:e,end:r,bytes:a,resolve:l,reject:u}),this._targetIndex=Math.max(this._targetIndex,r),this._pulling||(this._pulling=!0,this._pull().catch(f=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(d=>d.reject(f)),this._pendingSlices.length=0;else throw f})),c}_throwDueToCacheMiss(){throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){let{done:e,value:r}=await this._reader.read();if(e){for(let s of this._pendingSlices)s.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let n=this._currentIndex,i=this._currentIndex+r.byteLength;for(let s=0;s<this._pendingSlices.length;s++){let a=this._pendingSlices[s],c=Math.max(n,a.start),l=Math.min(i,a.end);c<l&&(a.bytes.set(r.subarray(c-n,l-n),c-a.start),l===a.end&&(a.resolve({bytes:a.bytes,view:ge(a.bytes),offset:a.start}),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:n,end:i,bytes:r,view:ge(r),age:0});this._cache.length>0;){let s=this._cache[0];if(this._maxRequestedIndex-s.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=r.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0}},VI={none:o((t,e)=>({start:t,end:e}),"none"),fileSystem:o((t,e)=>(t=Math.floor((t-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:t,end:e}),"fileSystem"),network:o((t,e,r)=>{t=Math.max(0,Math.floor((t-65536)/65536)*65536);for(let i of r){let a=Math.max((i.startPos+i.targetPos)/2,i.targetPos-8388608);if(Tx(t,e,a,i.targetPos)){let c=i.targetPos-i.startPos,l=Math.ceil((c+1)/8388608)*8388608,u=2**Math.ceil(Math.log2(c+1)),f=Math.min(u,l);e=Math.max(e,i.startPos+f)}}return e=Math.max(e,t+$U),{start:t,end:e}},"network")},Up=class{static{o(this,"ReadOrchestrator")}constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,r){x(this.fileSize!==null);let n=this.options.prefetchProfile(e,r,this.workers),i=Math.max(n.start,0),s=Math.min(n.end,this.fileSize);x(i<=e&&r<=s);let a=null,c=ze(this.cache,e,w=>w.start),l=c!==-1?this.cache[c]:null;l&&l.start<=e&&r<=l.end&&(l.age=this.nextAge++,a={bytes:l.bytes,view:l.view,offset:l.start});let u=ze(this.cache,i,w=>w.start),f=a?null:new Uint8Array(r-e),d=0,h=i,m=[];if(u!==-1){for(let w=u;w<this.cache.length;w++){let k=this.cache[w];if(k.start>=s)break;if(k.end<=i)continue;let T=Math.max(i,k.start),v=Math.min(s,k.end);if(x(T<=v),h<T&&m.push({start:h,end:T}),h=v,f){let S=Math.max(e,k.start),M=Math.min(r,k.end);if(S<M){let P=S-e;f.set(k.bytes.subarray(S-k.start,M-k.start),P),P===d&&(d=M-e)}}k.age=this.nextAge++}h<s&&m.push({start:h,end:s})}else m.push({start:i,end:s});if(f&&d>=f.length&&(a={bytes:f,view:ge(f),offset:e}),m.length===0)return x(a),a;let{promise:p,resolve:g,reject:y}=ut(),b=[];for(let w of m){let k=Math.max(e,w.start),T=Math.min(r,w.end);k===w.start&&T===w.end?b.push(w):k<T&&b.push({start:k,end:T})}for(let w of m){let k=f&&{start:e,bytes:f,holes:b,resolve:g,reject:y},T=!1;for(let v of this.workers)if(Tx(w.start-131072,w.start,v.currentPos,v.targetPos)){v.targetPos=Math.max(v.targetPos,w.end),T=!0,k&&!v.pendingSlices.includes(k)&&v.pendingSlices.push(k),v.running||this.runWorker(v);break}if(!T){let v=this.createWorker(w.start,w.end);k&&(v.pendingSlices=[k]),this.runWorker(v)}}return a||(x(f),a=p.then(w=>({bytes:w,view:ge(w),offset:e}))),a}createWorker(e,r){let n={startPos:e,currentPos:e,targetPos:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(n);this.workers.length>this.options.maxWorkerCount;){let i=0,s=this.workers[0];for(let a=1;a<this.workers.length;a++){let c=this.workers[a];c.age<s.age&&(i=a,s=c)}if(s.running&&s.pendingSlices.length>0)break;s.aborted=!0,this.workers.splice(i,1)}return n}runWorker(e){x(!e.running),x(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(r=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(n=>n.reject(r)),e.pendingSlices.length=0;else throw r})}supplyWorkerData(e,r){x(!e.aborted);let n=e.currentPos,i=n+r.length;this.insertIntoCache({start:n,end:i,bytes:r,view:ge(r),age:this.nextAge++}),e.currentPos+=r.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let s=0;s<e.pendingSlices.length;s++){let a=e.pendingSlices[s],c=Math.max(n,a.start),l=Math.min(i,a.start+a.bytes.length);c<l&&a.bytes.set(r.subarray(c-n,l-n),c-a.start);for(let u=0;u<a.holes.length;u++){let f=a.holes[u];n<=f.start&&i>f.start&&(f.start=i),f.end<=f.start&&(a.holes.splice(u,1),u--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(s,1),s--)}for(let s=0;s<this.workers.length;s++){let a=this.workers[s];e===a||a.running||Tx(n,i,a.currentPos,a.targetPos)&&(this.workers.splice(s,1),s--)}}forgetWorker(e){let r=this.workers.indexOf(e);x(r!==-1),this.workers.splice(r,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let r=ze(this.cache,e.start,n=>n.start)+1;if(r>0){let n=this.cache[r-1];if(n.end>=e.end)return;if(n.end>e.start){let i=new Uint8Array(e.end-n.start);i.set(n.bytes,0),i.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=i,n.view=ge(i),n.end=e.end,r--,e=n}else this.cache.splice(r,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(r,0,e),this.currentCacheSize+=e.bytes.length;for(let n=r+1;n<this.cache.length;n++){let i=this.cache[n];if(e.end<=i.start)break;if(e.end>=i.end){this.cache.splice(n,1),this.currentCacheSize-=i.bytes.length,n--;continue}let s=new Uint8Array(i.end-e.start);s.set(e.bytes,0),s.set(i.bytes,i.start-e.start),this.currentCacheSize-=e.end-i.start,e.bytes=s,e.view=ge(s),e.end=i.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let n=0,i=this.cache[0];for(let s=1;s<this.cache.length;s++){let a=this.cache[s];a.age<i.age&&(n=s,i=a)}if(this.currentCacheSize-i.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(n,1),this.currentCacheSize-=i.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}});var wd,er,od=he(()=>{$I();Ue();qt();WI();vx();wd=class{static{o(this,"Input")}get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(r=>!(r instanceof Mn)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Ci))throw new TypeError("options.source must be a Source.");if(e.source._disposed)throw new Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new Mk(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw new Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),x(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getFirstTimestamp(){let e=await this.getTracks();if(e.length===0)return 0;let r=await Promise.all(e.map(n=>n.getFirstTimestamp()));return Math.min(...r)}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(r=>r.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(r=>r.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(r=>r.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(r=>r.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}},er=class extends Error{static{o(this,"InputDisposedError")}constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}});var Mk,xr,On,se,oe,pd,jt,nc,xp,Vo,X,Ul,Bo,Uee,SI,Kn,bU,DU,TU,Zx,It,qt=he(()=>{od();Ue();Mk=class{static{o(this,"Reader")}constructor(e){this.source=e}requestSlice(e,r){if(this.source._disposed)throw new er;if(e<0||this.fileSize!==null&&e+r>this.fileSize)return null;let n=e+r,i=this.source._read(e,n);return i instanceof Promise?i.then(s=>s?new xr(s.bytes,s.view,s.offset,e,n):null):i?new xr(i.bytes,i.view,i.offset,e,n):null}requestSliceRange(e,r,n){if(this.source._disposed)throw new er;if(e<0)return null;if(this.fileSize!==null)return this.requestSlice(e,Ht(this.fileSize-e,r,n));{let i=this.requestSlice(e,n),s=o(a=>{if(a)return a;let c=o(u=>(x(u!==null),this.requestSlice(e,Ht(u-e,r,n))),"handleFileSize"),l=this.source._retrieveSize();return l instanceof Promise?l.then(c):c(l)},"handleAttempt");return i instanceof Promise?i.then(s):s(i)}}},xr=class t{static{o(this,"FileSlice")}constructor(e,r,n,i,s){this.bytes=e,this.view=r,this.offset=n,this.start=i,this.end=s,this.bufferPos=i-n}static tempFromBytes(e){return new t(e,ge(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,r=this.end-e){if(e<this.start||e+r>this.end)throw new RangeError("Slicing outside of original slice.");return new t(this.bytes,this.view,this.offset,e,e+r)}},On=o((t,e)=>{if(t.filePos<t.start||t.filePos+e>t.end)throw new RangeError(`Tried reading [${t.filePos}, ${t.filePos+e}), but slice is [${t.start}, ${t.end}). This is likely an internal error, please report it alongside the file that caused it.`)},"checkIsInRange"),se=o((t,e)=>{On(t,e);let r=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,r},"readBytes"),oe=o(t=>(On(t,1),t.view.getUint8(t.bufferPos++)),"readU8"),pd=o((t,e)=>{On(t,2);let r=t.view.getUint16(t.bufferPos,e);return t.bufferPos+=2,r},"readU16"),jt=o(t=>{On(t,2);let e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e},"readU16Be"),nc=o(t=>{On(t,3);let e=_l(t.view,t.bufferPos,!1);return t.bufferPos+=3,e},"readU24Be"),xp=o(t=>{On(t,2);let e=t.view.getInt16(t.bufferPos,!1);return t.bufferPos+=2,e},"readI16Be"),Vo=o((t,e)=>{On(t,4);let r=t.view.getUint32(t.bufferPos,e);return t.bufferPos+=4,r},"readU32"),X=o(t=>{On(t,4);let e=t.view.getUint32(t.bufferPos,!1);return t.bufferPos+=4,e},"readU32Be"),Ul=o(t=>{On(t,4);let e=t.view.getUint32(t.bufferPos,!0);return t.bufferPos+=4,e},"readU32Le"),Bo=o(t=>{On(t,4);let e=t.view.getInt32(t.bufferPos,!1);return t.bufferPos+=4,e},"readI32Be"),Uee=o(t=>{On(t,4);let e=t.view.getInt32(t.bufferPos,!0);return t.bufferPos+=4,e},"readI32Le"),SI=o((t,e)=>{let r,n;return e?(r=Vo(t,!0),n=Vo(t,!0)):(n=Vo(t,!1),r=Vo(t,!1)),n*4294967296+r},"readU64"),Kn=o(t=>{let e=X(t),r=X(t);return e*4294967296+r},"readU64Be"),bU=o(t=>{let e=Bo(t),r=X(t);return e*4294967296+r},"readI64Be"),DU=o(t=>{let e=Ul(t);return Uee(t)*4294967296+e},"readI64Le"),TU=o(t=>{On(t,4);let e=t.view.getFloat32(t.bufferPos,!1);return t.bufferPos+=4,e},"readF32Be"),Zx=o(t=>{On(t,8);let e=t.view.getFloat64(t.bufferPos,!1);return t.bufferPos+=8,e},"readF64Be"),It=o((t,e)=>{On(t,e);let r="";for(let n=0;n<e;n++)r+=String.fromCharCode(t.bytes[t.bufferPos++]);return r},"readAscii")});var xd,an,Ep,Xn,kd,PU,Sd,ns,dd,jI,ac,sc=he(()=>{Ka();Ue();qt();(function(t){t[t.Unsynchronisation=128]="Unsynchronisation",t[t.ExtendedHeader=64]="ExtendedHeader",t[t.ExperimentalIndicator=32]="ExperimentalIndicator",t[t.Footer=16]="Footer"})(xd||(xd={}));(function(t){t[t.ISO_8859_1=0]="ISO_8859_1",t[t.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",t[t.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",t[t.UTF_8=3]="UTF_8"})(an||(an={}));Ep=128,Xn=10,kd=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],PU=o((t,e)=>{let r=t.filePos;e.raw??={},e.raw.TAG??=se(t,Ep-3),t.filePos=r;let n=Sd(t,30);n&&(e.title??=n);let i=Sd(t,30);i&&(e.artist??=i);let s=Sd(t,30);s&&(e.album??=s);let a=Sd(t,4),c=Number.parseInt(a,10);Number.isInteger(c)&&c>0&&(e.date??=new Date(c,0,1));let l=se(t,30),u;if(l[28]===0&&l[29]!==0){let d=l[29];d>0&&(e.trackNumber??=d),t.skip(-30),u=Sd(t,28),t.skip(2)}else t.skip(-30),u=Sd(t,30);u&&(e.comment??=u);let f=oe(t);f<kd.length&&(e.genre??=kd[f])},"parseId3V1Tag"),Sd=o((t,e)=>{let r=se(t,e),n=Ml(r.indexOf(0),r.length),i=r.subarray(0,n),s="";for(let a=0;a<i.length;a++)s+=String.fromCharCode(i[a]);return s.trimEnd()},"readId3V1String"),ns=o(t=>{let e=t.filePos,r=It(t,3),n=oe(t),i=oe(t),s=oe(t),a=X(t);if(r!=="ID3"||n===255||i===255||(a&2155905152)!==0)return t.filePos=e,null;let c=Mx(a);return{majorVersion:n,revision:i,flags:s,size:c}},"readId3V2Header"),dd=o((t,e,r)=>{if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let n=se(t,e.size),i=new jI(e,n);if(e.flags&xd.Footer&&i.removeFooter(),e.flags&xd.Unsynchronisation&&e.majorVersion===3&&i.ununsynchronizeAll(),e.flags&xd.ExtendedHeader){let s=i.readU32();e.majorVersion===3?i.pos+=s:i.pos+=s-4}for(;i.pos<=i.bytes.length-i.frameHeaderSize();){let s=i.readId3V2Frame();if(!s)break;let a=i.pos,c=i.pos+s.size,l=!1,u=!1,f=!1;if(e.majorVersion===3?(l=!!(s.flags&64),u=!!(s.flags&128)):e.majorVersion===4&&(l=!!(s.flags&4),u=!!(s.flags&8),f=!!(s.flags&2)||!!(e.flags&xd.Unsynchronisation)),l){console.warn(`Skipping encrypted ID3v2 frame ${s.id}`),i.pos=c;continue}if(u){console.warn(`Skipping compressed ID3v2 frame ${s.id}`),i.pos=c;continue}switch(f&&i.ununsynchronizeRegion(i.pos,c),r.raw??={},s.id[0]==="T"?r.raw[s.id]??=i.readId3V2EncodingAndText(c):r.raw[s.id]??=i.readBytes(s.size),i.pos=a,s.id){case"TIT2":case"TT2":r.title??=i.readId3V2EncodingAndText(c);break;case"TIT3":case"TT3":r.description??=i.readId3V2EncodingAndText(c);break;case"TPE1":case"TP1":r.artist??=i.readId3V2EncodingAndText(c);break;case"TALB":case"TAL":r.album??=i.readId3V2EncodingAndText(c);break;case"TPE2":case"TP2":r.albumArtist??=i.readId3V2EncodingAndText(c);break;case"TRCK":case"TRK":{let h=i.readId3V2EncodingAndText(c).split("/"),m=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(m)&&m>0&&(r.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(r.tracksTotal??=p)}break;case"TPOS":case"TPA":{let h=i.readId3V2EncodingAndText(c).split("/"),m=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(m)&&m>0&&(r.discNumber??=m),p&&Number.isInteger(p)&&p>0&&(r.discsTotal??=p)}break;case"TCON":case"TCO":{let d=i.readId3V2EncodingAndText(c),h=/^\((\d+)\)/.exec(d);if(h){let m=Number.parseInt(h[1]);if(kd[m]!==void 0){r.genre??=kd[m];break}}if(h=/^\d+$/.exec(d),h){let m=Number.parseInt(h[0]);if(kd[m]!==void 0){r.genre??=kd[m];break}}r.genre??=d}break;case"TDRC":case"TDAT":{let d=i.readId3V2EncodingAndText(c),h=new Date(d);Number.isNaN(h.getTime())||(r.date??=h)}break;case"TYER":case"TYE":{let d=i.readId3V2EncodingAndText(c),h=Number.parseInt(d,10);Number.isInteger(h)&&(r.date??=new Date(h,0,1))}break;case"USLT":case"ULT":{let d=i.readU8();i.pos+=3,i.readId3V2Text(d,c),r.lyrics??=i.readId3V2Text(d,c)}break;case"COMM":case"COM":{let d=i.readU8();i.pos+=3,i.readId3V2Text(d,c),r.comment??=i.readId3V2Text(d,c)}break;case"APIC":case"PIC":{let d=i.readId3V2TextEncoding(),h;if(e.majorVersion===2){let y=i.readAscii(3);h=y==="PNG"?"image/png":y==="JPG"?"image/jpeg":"image/*"}else h=i.readId3V2Text(d,c);let m=i.readU8(),p=i.readId3V2Text(d,c).trimEnd(),g=c-i.pos;if(g>=0){let y=i.readBytes(g);r.images||(r.images=[]),r.images.push({data:y,mimeType:h,kind:m===3?"coverFront":m===4?"coverBack":"unknown",description:p})}}break;default:i.pos+=s.size;break}i.pos=c}},"parseId3V2Tag"),jI=class{static{o(this,"Id3V2Reader")}constructor(e,r){this.header=e,this.bytes=r,this.pos=0,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let r=0;r<this.bytes.length;r++){let n=this.bytes[r];e.push(n),n===255&&r!==this.bytes.length-1&&this.bytes[r]===0&&r++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,r){let n=[];for(let a=e;a<r;a++){let c=this.bytes[a];n.push(c),c===255&&a!==r-1&&this.bytes[a+1]===0&&a++}let i=this.bytes.subarray(0,e),s=this.bytes.subarray(r);this.bytes=new Uint8Array(i.length+n.length+s.length),this.bytes.set(i,0),this.bytes.set(n,i.length),this.bytes.set(s,i.length+n.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-Xn),this.view=new DataView(this.bytes.buffer)}readBytes(e){let r=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,r}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),r=this.view.getUint8(this.pos+1);return this.pos+=3,e*256+r}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let r="";for(let n=0;n<e;n++)r+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,r}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);if(e==="\0\0\0")return null;let r=this.readU24();return{id:e,size:r,flags:0}}else{let e=this.readAscii(4);if(e==="\0\0\0\0")return null;let r=this.readU32(),n=this.header.majorVersion===4?Mx(r):r,i=this.readU16(),s=this.pos,a=o(c=>{let l=this.pos+c;if(l>this.bytes.length)return!1;if(l<=this.bytes.length-this.frameHeaderSize()){this.pos+=c;let u=this.readAscii(4);if(u!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(u))return!1}return!0},"isSizeValid");if(!a(n)){let c=this.header.majorVersion===4?r:Mx(r);a(c)&&(n=c)}return this.pos=s,{id:e,size:n,flags:i}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,r){let n=this.pos,i=this.readBytes(r-this.pos);switch(e){case an.ISO_8859_1:{let s="";for(let a=0;a<i.length;a++){let c=i[a];if(c===0){this.pos=n+a+1;break}s+=String.fromCharCode(c)}return s}case an.UTF_16_WITH_BOM:if(i[0]===255&&i[1]===254){let s=new TextDecoder("utf-16le"),a=Ml(i.findIndex((c,l)=>c===0&&i[l+1]===0&&l%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(2,a))}else if(i[0]===254&&i[1]===255){let s=new TextDecoder("utf-16be"),a=Ml(i.findIndex((c,l)=>c===0&&i[l+1]===0&&l%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(2,a))}else{let s=Ml(i.findIndex(a=>a===0),i.length);return this.pos=n+Math.min(s+1,i.length),br.decode(i.subarray(0,s))}case an.UTF_16_BE_NO_BOM:{let s=new TextDecoder("utf-16be"),a=Ml(i.findIndex((c,l)=>c===0&&i[l+1]===0&&l%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(0,a))}case an.UTF_8:{let s=Ml(i.findIndex(a=>a===0),i.length);return this.pos=n+Math.min(s+1,i.length),br.decode(i.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let r=this.readId3V2TextEncoding();return this.readId3V2Text(r,e)}},ac=class{static{o(this,"Id3V2Writer")}constructor(e){this.helper=new Uint8Array(8),this.helperView=ge(this.helper),this.writer=e}writeId3V2Tag(e){let r=this.writer.getPos();this.writeAscii("ID3"),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);let n=this.writer.getPos(),i=new Set;for(let{key:c,value:l}of Gi(e))switch(c){case"title":this.writeId3V2TextFrame("TIT2",l),i.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",l),i.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",l),i.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",l),i.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",l),i.add("TPE2");break;case"trackNumber":{let u=e.tracksTotal!==void 0?`${l}/${e.tracksTotal}`:l.toString();this.writeId3V2TextFrame("TRCK",u),i.add("TRCK")}break;case"discNumber":{let u=e.discsTotal!==void 0?`${l}/${e.discsTotal}`:l.toString();this.writeId3V2TextFrame("TPOS",u),i.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",l),i.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",l.toISOString().slice(0,10)),i.add("TDRC");break;case"lyrics":this.writeId3V2LyricsFrame(l),i.add("USLT");break;case"comment":this.writeId3V2CommentFrame(l),i.add("COMM");break;case"images":{let u={coverFront:3,coverBack:4,unknown:0};for(let f of l){let d=u[f.kind]??0,h=f.description??"";this.writeId3V2ApicFrame(f.mimeType,d,h,f.data)}}break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:kt(c)}if(e.raw)for(let c in e.raw){let l=e.raw[c];if(l==null||c.length!==4||i.has(c))continue;let u;if(typeof l=="string"){let f=lt.encode(l);u=new Uint8Array(f.byteLength+2),u[0]=an.UTF_8,u.set(f,1)}else if(l instanceof Uint8Array)u=l;else continue;this.writeAscii(c),this.writeSynchsafeU32(u.byteLength),this.writeU16(0),this.writer.write(u)}let s=this.writer.getPos(),a=s-n;return this.writer.seek(r+6),this.writeSynchsafeU32(a),this.writer.seek(s),a+10}writeU8(e){this.helper[0]=e,this.writer.write(this.helper.subarray(0,1))}writeU16(e){this.helperView.setUint16(0,e,!1),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeAscii(e){for(let r=0;r<e.length;r++)this.helper[r]=e.charCodeAt(r);this.writer.write(this.helper.subarray(0,e.length))}writeSynchsafeU32(e){this.writeU32(Wz(e))}writeIsoString(e){let r=new Uint8Array(e.length+1);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);r[e.length]=0,this.writer.write(r)}writeUtf8String(e){let r=lt.encode(e);this.writer.write(r),this.writeU8(0)}writeId3V2TextFrame(e,r){let n=Va(r),s=1+(n?r.length:lt.encode(r).byteLength)+1;this.writeAscii(e),this.writeSynchsafeU32(s),this.writeU16(0),this.writeU8(n?an.ISO_8859_1:an.UTF_8),n?this.writeIsoString(r):this.writeUtf8String(r)}writeId3V2LyricsFrame(e){let r=Va(e),n="",i=4+n.length+1+e.length+1;this.writeAscii("USLT"),this.writeSynchsafeU32(i),this.writeU16(0),this.writeU8(r?an.ISO_8859_1:an.UTF_8),this.writeAscii("und"),r?(this.writeIsoString(n),this.writeIsoString(e)):(this.writeUtf8String(n),this.writeUtf8String(e))}writeId3V2CommentFrame(e){let r=Va(e),n=r?e.length:lt.encode(e).byteLength,i="",s=4+i.length+1+n+1;this.writeAscii("COMM"),this.writeSynchsafeU32(s),this.writeU16(0),this.writeU8(r?an.ISO_8859_1:an.UTF_8),this.writeU8(117),this.writeU8(110),this.writeU8(100),r?(this.writeIsoString(i),this.writeIsoString(e)):(this.writeUtf8String(i),this.writeUtf8String(e))}writeId3V2ApicFrame(e,r,n,i){let s=Va(e)&&Va(n),a=s?n.length:lt.encode(n).byteLength,c=1+e.length+1+1+a+1+i.byteLength;this.writeAscii("APIC"),this.writeSynchsafeU32(c),this.writeU16(0),this.writeU8(s?an.ISO_8859_1:an.UTF_8),s?this.writeIsoString(e):this.writeUtf8String(e),this.writeU8(r),s?this.writeIsoString(n):this.writeUtf8String(n),this.writer.write(i)}}});var Sr,jo=he(()=>{Ue();Sr=class{static{o(this,"Muxer")}constructor(e){this.mutex=new Tn,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,r,n){if(r+=e.source._timestampOffset,r<0)throw new Error(`Timestamps must be non-negative (got ${r}s).`);let i=this.trackTimestampInfo.get(e);if(i){if(n&&(i.maxTimestampBeforeLastKeyPacket=i.maxTimestamp),i.maxTimestampBeforeLastKeyPacket!==null&&r<i.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${r}s, but largest timestamp is ${i.maxTimestampBeforeLastKeyPacket}s.`);i.maxTimestamp=Math.max(i.maxTimestamp,r)}else{if(!n)throw new Error("First packet must be a key packet.");i={maxTimestamp:r,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,i)}return r}}});var Ok,HU=he(()=>{qs();Zt();sc();lr();Ue();jo();Ok=class extends Sr{static{o(this,"AdtsMuxer")}constructor(e,r){super(e),this.header=null,this.headerBitstream=null,this.inputIsAdts=null,this.format=r,this.writer=e._writer}async start(){Ro(this.output._metadataTags)||new ac(this.writer).writeId3V2Tag(this.output._metadataTags)}async getMimeType(){return"audio/aac"}async addEncodedVideoPacket(){throw new Error("ADTS does not support video.")}async addEncodedAudioPacket(e,r,n){let i=await this.mutex.acquire();try{if(this.validateAndNormalizeTimestamp(e,r.timestamp,r.type==="key"),this.inputIsAdts===null){En(n);let s=n?.decoderConfig?.description;if(this.inputIsAdts=!s,!this.inputIsAdts){let a=js(qe(s)),c=Ex(a);this.header=c.header,this.headerBitstream=c.bitstream}}if(this.inputIsAdts){let s=this.writer.getPos();this.writer.write(r.data),this.format._options.onFrame&&this.format._options.onFrame(r.data,s)}else{x(this.header);let s=r.data.byteLength+this.header.byteLength;Cx(this.headerBitstream,s);let a=this.writer.getPos();if(this.writer.write(this.header),this.writer.write(r.data),this.format._options.onFrame){let c=new Uint8Array(s);c.set(this.header,0),c.set(r.data,this.header.byteLength),this.format._options.onFrame(c,a)}}await this.writer.flush()}finally{i()}}async addSubtitleCue(){throw new Error("ADTS does not support subtitles.")}async finalize(){(await this.mutex.acquire())()}}});var VU,$ee,Hee,Rk,WU=he(()=>{Zt();sn();Ue();jo();qt();lr();CI();Ti();VU=new Uint8Array([102,76,97,67]),$ee=38,Hee=34,Rk=class extends Sr{static{o(this,"FlacMuxer")}constructor(e,r){super(e),this.metadataWritten=!1,this.blockSizes=[],this.frameSizes=[],this.sampleRate=null,this.channels=null,this.bitsPerSample=null,this.writer=e._writer,this.format=r,this.format._options.appendOnly&&(this.writer.ensureMonotonicity=!0)}async start(){this.writer.write(VU)}writeHeader({bitsPerSample:e,minimumBlockSize:r,maximumBlockSize:n,minimumFrameSize:i,maximumFrameSize:s,sampleRate:a,channels:c,totalSamples:l}){x(this.writer.getPos()===4);let u=!Ro(this.output._metadataTags),f=new Te(new Uint8Array(4));f.writeBits(1,+!u),f.writeBits(7,Ei.STREAMINFO),f.writeBits(24,Hee),this.writer.write(f.bytes);let d=new Te(new Uint8Array(18));if(d.writeBits(16,r),d.writeBits(16,n),d.writeBits(24,i),d.writeBits(24,s),d.writeBits(20,a),d.writeBits(3,c-1),d.writeBits(5,e-1),l>=2**32)throw new Error("This muxer only supports writing up to 2 ** 32 samples");d.writeBits(4,0),d.writeBits(32,l),this.writer.write(d.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){let r=32+e.mimeType.length+(e.description?.length??0)+e.data.length,n=new Uint8Array(r),i=0,s=ge(n);s.setUint32(i,e.kind==="coverFront"?3:e.kind==="coverBack"?4:0),i+=4,s.setUint32(i,e.mimeType.length),i+=4,n.set(lt.encode(e.mimeType),8),i+=e.mimeType.length,s.setUint32(i,e.description?.length??0),i+=4,n.set(lt.encode(e.description??""),i),i+=e.description?.length??0,i+=16,s.setUint32(i,e.data.length),i+=4,n.set(e.data,i),i+=e.data.length,x(i===r);let a=new Te(new Uint8Array(4));a.writeBits(1,0),a.writeBits(7,Ei.PICTURE),a.writeBits(24,r),this.writer.write(a.bytes),this.writer.write(n)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek($ee+VU.byteLength),Ro(this.output._metadataTags)){this.metadataWritten=!0;return}let e=this.output._metadataTags.images??[];for(let i of e)this.writePictureBlock(i);let r=op(new Uint8Array(0),this.output._metadataTags,!1),n=new Te(new Uint8Array(4));n.writeBits(1,1),n.writeBits(7,Ei.VORBIS_COMMENT),n.writeBits(24,r.length),this.writer.write(n.bytes),this.writer.write(r),this.metadataWritten=!0}async getMimeType(){return"audio/flac"}async addEncodedVideoPacket(){throw new Error("FLAC does not support video.")}async addEncodedAudioPacket(e,r,n){let i=await this.mutex.acquire();try{if(this.validateAndNormalizeTimestamp(e,r.timestamp,r.type==="key"),this.sampleRate===null){En(n),x(n),x(n.decoderConfig),x(n.decoderConfig.description),this.sampleRate=n.decoderConfig.sampleRate,this.channels=n.decoderConfig.numberOfChannels;let d=new Te(qe(n.decoderConfig.description));d.skipBits(167);let h=d.readBits(5)+1;this.bitsPerSample=h,this.format._options.appendOnly&&this.writeHeader({minimumBlockSize:16,maximumBlockSize:65535,minimumFrameSize:0,maximumFrameSize:0,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:0})}this.metadataWritten||this.writeVorbisCommentAndPictureBlock();let s=xr.tempFromBytes(r.data);s.skip(2);let a=se(s,2),c=new Te(a),l=bk(c.readBits(4));if(l===null)throw new Error("Invalid FLAC frame: Invalid block size.");wk(s);let u=xk(s,l);this.format._options.appendOnly||(this.blockSizes.push(u),this.frameSizes.push(r.data.length));let f=this.writer.getPos();this.writer.write(r.data),this.format._options.onFrame&&this.format._options.onFrame(r.data,f),await this.writer.flush()}finally{i()}}addSubtitleCue(){throw new Error("FLAC does not support subtitles.")}async finalize(){let e=await this.mutex.acquire();if(!this.format._options.appendOnly){let r=1/0,n=0,i=1/0,s=0,a=0;for(let c=0;c<this.blockSizes.length;c++)i=Math.min(i,this.frameSizes[c]),s=Math.max(s,this.frameSizes[c]),n=Math.max(n,this.blockSizes[c]),a+=this.blockSizes[c],c!==this.blockSizes.length-1&&(r=Math.min(r,this.blockSizes[c]));x(this.sampleRate!==null),x(this.channels!==null),x(this.bitsPerSample!==null),this.writer.seek(4),this.writeHeader({minimumBlockSize:r,maximumBlockSize:n,minimumFrameSize:i,maximumFrameSize:s,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:a})}e()}}});var Hp,Vee,Td,Nk,Wee,Ak,Fk,Vp=he(()=>{Hp=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,Vee=/^WEBVTT(.|\n)*?\n{2}/,Td=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Nk=class{static{o(this,"SubtitleParser")}constructor(e){this.preambleText=null,this.preambleEmitted=!1,this.options=e}parse(e){e=e.replaceAll(`\r
|
|
23
|
+
`),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,r),this.gl.linkProgram(n),n}createShader(e,r){let n=this.gl.createShader(e);return this.gl.shaderSource(n,r),this.gl.compileShader(n),n}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let r=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,r,this.gl.STATIC_DRAW);let i=this.gl.getAttribLocation(this.program,"a_position"),s=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,r){(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}},Za=class extends id{static{o(this,"VideoSampleSink")}constructor(e){if(!(e instanceof Pn))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,r){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=this._track.codec,i=this._track.rotation,s=await this._track.getDecoderConfig(),a=this._track.timeResolution;return x(n&&s),new ZP(e,r,n,s,i,a)}_createPacketSink(){return new Ki(this._track)}async getSample(e){Lo(e);for await(let r of this.mediaSamplesAtTimestamps([e]))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,r=1/0){return this.mediaSamplesInRange(e,r)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},sd=class{static{o(this,"CanvasSink")}constructor(e,r={}){if(this._nextCanvasIndex=0,!(e instanceof Pn))throw new TypeError("videoTrack must be an InputVideoTrack.");if(r&&typeof r!="object")throw new TypeError("options must be an object.");if(r.alpha!==void 0&&typeof r.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(r.width!==void 0&&(!Number.isInteger(r.width)||r.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(r.height!==void 0&&(!Number.isInteger(r.height)||r.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(r.fit!==void 0&&!["fill","contain","cover"].includes(r.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(r.width!==void 0&&r.height!==void 0&&r.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(r.crop!==void 0&&yp(r.crop,"options."),r.poolSize!==void 0&&(typeof r.poolSize!="number"||!Number.isInteger(r.poolSize)||r.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");let n=r.rotation??e.rotation,[i,s]=n%180===0?[e.squarePixelWidth,e.squarePixelHeight]:[e.squarePixelHeight,e.squarePixelWidth],a=r.crop;a&&gp(a,i,s);let[c,l]=a?[a.width,a.height]:[i,s],u=c/l;r.width!==void 0&&r.height===void 0?(c=r.width,l=Math.round(c/u)):r.width===void 0&&r.height!==void 0?(l=r.height,c=Math.round(l*u)):r.width!==void 0&&r.height!==void 0&&(c=r.width,l=r.height),this._videoTrack=e,this._alpha=r.alpha??!1,this._width=c,this._height=l,this._rotation=n,this._crop=a,this._fit=r.fit??"fill",this._videoSampleSink=new Za(e),this._canvasPool=Array.from({length:r.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let r=this._canvasPool[this._nextCanvasIndex],n=!1;r||(typeof document<"u"?(r=document.createElement("canvas"),r.width=this._width,r.height=this._height):r=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=r),n=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let i=r.getContext("2d",{alpha:this._alpha||Vs()});x(i),i.resetTransform(),n||(!this._alpha&&Vs()?(i.fillStyle="black",i.fillRect(0,0,this._width,this._height)):i.clearRect(0,0,this._width,this._height)),e.drawWithFit(i,{fit:this._fit,rotation:this._rotation,crop:this._crop});let s={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),s}async getCanvas(e){Lo(e);let r=await this._videoSampleSink.getSample(e);return r&&this._videoSampleToWrappedCanvas(r)}canvases(e=0,r=1/0){return Zm(this._videoSampleSink.samples(e,r),n=>this._videoSampleToWrappedCanvas(n))}canvasesAtTimestamps(e){return Zm(this._videoSampleSink.samplesAtTimestamps(e),r=>r&&this._videoSampleToWrappedCanvas(r))}},tI=class extends wp{static{o(this,"AudioDecoderWrapper")}constructor(e,r,n,i){super(e,r),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new $a,this.customDecoderQueueSize=0,this.currentTimestamp=null;let s=o(c=>{(this.currentTimestamp===null||Math.abs(c.timestamp-this.currentTimestamp)>=c.duration)&&(this.currentTimestamp=c.timestamp);let l=this.currentTimestamp;if(this.currentTimestamp+=c.duration,c.numberOfFrames===0){c.close();return}let u=i.sampleRate;c.setTimestamp(Math.round(l*u)/u),e(c)},"sampleHandler"),a=td.find(c=>c.supports(n,i));if(a)this.customDecoder=new a,this.customDecoder.codec=n,this.customDecoder.config=i,this.customDecoder.onSample=c=>{if(!(c instanceof Dr))throw new TypeError("The argument passed to onSample must be an AudioSample.");s(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:o(l=>{try{s(new Dr(l))}catch(u){this.onError(u)}},"output"),error:o(l=>{l.stack=c,this.onError(l)},"error")}),this.decoder.configure(i)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(x(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(x(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(x(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(x(this.decoder),this.decoder.close())}},rI=class extends wp{static{o(this,"PcmAudioDecoderWrapper")}constructor(e,r,n){super(e,r),this.decoderConfig=n,this.currentTimestamp=null,x(ht.includes(n.codec)),this.codec=n.codec;let{dataType:i,sampleSize:s,littleEndian:a}=_r(this.codec);switch(this.inputSampleSize=s,s){case 1:i==="unsigned"?this.readInputValue=(c,l)=>c.getUint8(l)-2**7:i==="signed"?this.readInputValue=(c,l)=>c.getInt8(l):i==="ulaw"?this.readInputValue=(c,l)=>oU(c.getUint8(l)):i==="alaw"?this.readInputValue=(c,l)=>cU(c.getUint8(l)):x(!1);break;case 2:i==="unsigned"?this.readInputValue=(c,l)=>c.getUint16(l,a)-2**15:i==="signed"?this.readInputValue=(c,l)=>c.getInt16(l,a):x(!1);break;case 3:i==="unsigned"?this.readInputValue=(c,l)=>_l(c,l,a)-2**23:i==="signed"?this.readInputValue=(c,l)=>kz(c,l,a):x(!1);break;case 4:i==="unsigned"?this.readInputValue=(c,l)=>c.getUint32(l,a)-2**31:i==="signed"?this.readInputValue=(c,l)=>c.getInt32(l,a):i==="float"?this.readInputValue=(c,l)=>c.getFloat32(l,a):x(!1);break;case 8:i==="float"?this.readInputValue=(c,l)=>c.getFloat64(l,a):x(!1);break;default:kt(s),x(!1)}switch(s){case 1:i==="ulaw"||i==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,l,u)=>c.setInt16(l,u,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(c,l,u)=>c.setUint8(l,u+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,l,u)=>c.setInt16(l,u,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(c,l,u)=>c.setInt32(l,u<<8,!0);break;case 4:this.outputSampleSize=4,i==="float"?(this.outputFormat="f32",this.writeOutputValue=(c,l,u)=>c.setFloat32(l,u,!0)):(this.outputFormat="s32",this.writeOutputValue=(c,l,u)=>c.setInt32(l,u,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(c,l,u)=>c.setFloat32(l,u,!0);break;default:kt(s),x(!1)}}getDecodeQueueSize(){return 0}decode(e){let r=ge(e.data),n=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,i=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(i),a=new DataView(s);for(let f=0;f<n*this.decoderConfig.numberOfChannels;f++){let d=f*this.inputSampleSize,h=f*this.outputSampleSize,m=this.readInputValue(r,d);this.writeOutputValue(a,h,m)}let c=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=c)&&(this.currentTimestamp=e.timestamp);let l=this.currentTimestamp;this.currentTimestamp+=c;let u=new Dr({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:l});this.onSample(u)}async flush(){}close(){}},ec=class extends id{static{o(this,"AudioSampleSink")}constructor(e){if(!(e instanceof Et))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,r){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=this._track.codec,i=await this._track.getDecoderConfig();return x(n&&i),ht.includes(i.codec)?new rI(e,r,i):new tI(e,r,n,i)}_createPacketSink(){return new Ki(this._track)}async getSample(e){Lo(e);for await(let r of this.mediaSamplesAtTimestamps([e]))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,r=1/0){return this.mediaSamplesInRange(e,r)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},qx=class{static{o(this,"AudioBufferSink")}constructor(e){if(!(e instanceof Et))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new ec(e)}_audioSampleToWrappedArrayBuffer(e){let r={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),r}async getBuffer(e){Lo(e);let r=await this._audioSampleSink.getSample(e);return r&&this._audioSampleToWrappedArrayBuffer(r)}buffers(e=0,r=1/0){return Zm(this._audioSampleSink.samples(e,r),n=>this._audioSampleToWrappedArrayBuffer(n))}buffersAtTimestamps(e){return Zm(this._audioSampleSink.samplesAtTimestamps(e),r=>r&&this._audioSampleToWrappedArrayBuffer(r))}}});var tc,Pn,Et,Xi=he(()=>{sn();rd();Yx();Ue();Qn();tc=class{static{o(this,"InputTrack")}constructor(e,r){this.input=e,this._backing=r}isVideoTrack(){return this instanceof Pn}isAudioTrack(){return this instanceof Et}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){let r=new Ki(this),n=1/0,i=-1/0,s=0,a=0;for await(let c of r.packets(void 0,void 0,{metadataOnly:!0})){if(s>=e&&c.timestamp>=i)break;n=Math.min(n,c.timestamp),i=Math.max(i,c.timestamp+c.duration),s++,a+=c.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(i-n)).toPrecision(16)):0,averageBitrate:s?Number((8*a/(i-n)).toPrecision(16)):0}}},Pn=class extends tc{static{o(this,"InputVideoTrack")}constructor(e,r){super(e,r),this._backing=r,this.pixelAspectRatio=qa({num:this._backing.getSquarePixelWidth()*this._backing.getCodedHeight(),den:this._backing.getSquarePixelHeight()*this._backing.getCodedWidth()})}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get squarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelHeight(){return this._backing.getSquarePixelHeight()}get displayWidth(){return this._backing.getRotation()%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this._backing.getRotation()%180===0?this.squarePixelHeight:this.squarePixelWidth}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pg"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let r=this._backing.getCodec();return x(r!==null),ed.some(i=>i.supports(r,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof je))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(this.codec===null)return null;let r=await this.getDecoderConfig();return x(r),Ux(this.codec,r,e.data)}},Et=class extends tc{static{o(this,"InputAudioTrack")}constructor(e,r){super(e,r),this._backing=r}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let r=this._backing.getCodec();return x(r!==null),td.some(n=>n.supports(r,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof je))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}}});var Gx,nI=he(()=>{Gx=o(t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");if(t.codecStrings.length>0){let n=[...new Set(t.codecStrings)];r+=`; codecs="${n.join(", ")}"`}return r},"buildIsobmffMimeType")});var Ji,zo,Uo,rc,Qx,Kx,Zi,pU,iI=he(()=>{lr();Ue();qt();Ji=8,zo=16,Uo=o(t=>{let e=X(t),r=It(t,4),n=8;e===1&&(e=Kn(t),n=16);let s=e-n;return s<0?null:{name:r,totalSize:e,headerSize:n,contentSize:s}},"readBoxHeader"),rc=o(t=>Bo(t)/65536,"readFixed_16_16"),Qx=o(t=>Bo(t)/1073741824,"readFixed_2_30"),Kx=o(t=>{let e=0;for(let r=0;r<4;r++){e<<=7;let n=oe(t);if(e|=n&127,(n&128)===0)break}return e},"readIsomVariableInteger"),Zi=o(t=>{let e=jt(t);return t.skip(2),e=Math.min(e,t.remainingLength),br.decode(se(t,e))},"readMetadataStringShort"),pU=o(t=>{let e=Uo(t);if(!e||e.name!=="data"||t.remainingLength<8)return null;let r=X(t);t.skip(4);let n=se(t,e.contentSize-8);switch(r){case 1:return br.decode(n);case 2:return new TextDecoder("utf-16be").decode(n);case 13:return new Gn(n,"image/jpeg");case 14:return new Gn(n,"image/png");case 27:return new Gn(n,"image/bmp");default:return n}},"readDataBox")});var Jx,Xx,sI,oI,aI,Dee,Mee,Oee,cI,Ree,gU,yU=he(()=>{qs();Zt();sn();Fo();Xi();Ue();Qn();nI();iI();qt();lr();Ox();Ti();Jx=class extends wr{static{o(this,"IsobmffDemuxer")}constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...r)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(r=>r.inputTrack.getCodecParameterString()));return Gx({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(r=>r.info?.type==="video"),hasAudio:this.tracks.some(r=>r.info?.type==="audio"),codecStrings:e.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,Ji,zo);if(r instanceof Promise&&(r=await r),!r)break;let n=e,i=Uo(r);if(!i)break;if(i.name==="ftyp"){let s=It(r,4);this.isQuickTime=s==="qt "}else if(i.name==="moov"){let s=this.reader.requestSlice(r.filePos,i.contentSize);if(s instanceof Promise&&(s=await s),!s)break;this.moovSlice=s,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((a,c)=>Number(c.disposition.default)-Number(a.disposition.default));for(let a of this.tracks){let c=a.editListPreviousSegmentDurations/this.movieTimescale;a.editListOffset-=Math.round(c*a.timescale)}break}e=n+i.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let r=this.reader.requestSlice(this.reader.fileSize-4,4);r instanceof Promise&&(r=await r),x(r);let n=X(r),i=this.reader.fileSize-n;if(i>=0&&i<=this.reader.fileSize-zo){let s=this.reader.requestSliceRange(i,Ji,zo);if(s instanceof Promise&&(s=await s),s){let a=Uo(s);if(a&&a.name==="mfra"){let c=this.reader.requestSlice(s.filePos,a.contentSize);c instanceof Promise&&(c=await c),c&&this.readContiguousBoxes(c)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=r,x(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&ht.includes(e.info.codec)&&r.sampleCompositionTimeOffsets.length===0){x(e.info?.type==="audio");let s=_r(e.info.codec),a=[],c=[];for(let l=0;l<r.sampleToChunk.length;l++){let u=r.sampleToChunk[l],f=r.sampleToChunk[l+1],d=(f?f.startChunkIndex:r.chunkOffsets.length)-u.startChunkIndex;for(let h=0;h<d;h++){let m=u.startSampleIndex+h*u.samplesPerChunk,p=m+u.samplesPerChunk,g=ze(r.sampleTimingEntries,m,P=>P.startIndex),y=r.sampleTimingEntries[g],b=ze(r.sampleTimingEntries,p,P=>P.startIndex),w=r.sampleTimingEntries[b],k=y.startDecodeTimestamp+(m-y.startIndex)*y.delta,v=w.startDecodeTimestamp+(p-w.startIndex)*w.delta-k,S=Ze(a);S&&S.delta===v?S.count++:a.push({startIndex:u.startChunkIndex+h,startDecodeTimestamp:k,count:1,delta:v});let M=u.samplesPerChunk*s.sampleSize*e.info.numberOfChannels;c.push(M)}u.startSampleIndex=u.startChunkIndex,u.samplesPerChunk=1}r.sampleTimingEntries=a,r.sampleSizes=c}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(let s of r.sampleTimingEntries)for(let a=0;a<s.count;a++)r.presentationTimestamps.push({presentationTimestamp:s.startDecodeTimestamp+a*s.delta,sampleIndex:s.startIndex+a});for(let s of r.sampleCompositionTimeOffsets)for(let a=0;a<s.count;a++){let c=s.startIndex+a,l=r.presentationTimestamps[c];l&&(l.presentationTimestamp+=s.offset)}r.presentationTimestamps.sort((s,a)=>s.presentationTimestamp-a.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let s=0;s<r.presentationTimestamps.length;s++)r.presentationTimestampIndexMap[r.presentationTimestamps[s].sampleIndex]=s}return r}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let r=this.reader.requestSliceRange(e,Ji,zo);r instanceof Promise&&(r=await r),x(r);let n=Uo(r);x(n?.name==="moof");let i=this.reader.requestSlice(e,n.totalSize);i instanceof Promise&&(i=await i),x(i),this.traverseBox(i);let s=this.lastReadFragment;x(s&&s.moofOffset===e);for(let[,a]of s.trackData){let c=a.track,{fragmentPositionCache:l}=c;if(!a.startTimestampIsFinal){let f=c.fragmentLookupTable.find(d=>d.moofOffset===s.moofOffset);if(f)cI(a,f.timestamp);else{let d=ze(l,s.moofOffset-1,h=>h.moofOffset);if(d!==-1){let h=l[d];cI(a,h.endTimestamp)}}a.startTimestampIsFinal=!0}let u=ze(l,a.startTimestamp,f=>f.startTimestamp);(u===-1||l[u].moofOffset!==s.moofOffset)&&l.splice(u+1,0,{moofOffset:s.moofOffset,startTimestamp:a.startTimestamp,endTimestamp:a.endTimestamp})}return s}readContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-Ji&&this.traverseBox(e););}*iterateContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-Ji;){let n=e.filePos,i=Uo(e);if(!i)break;yield{boxInfo:i,slice:e},e.filePos=n+i.totalSize}}traverseBox(e){let r=e.filePos,n=Uo(e);if(!n)return!1;let i=e.filePos,s=r+n.totalSize;switch(n.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"mvhd":{let a=oe(e);e.skip(3),a===1?(e.skip(16),this.movieTimescale=X(e),this.movieDurationInTimescale=Kn(e)):(e.skip(8),this.movieTimescale=X(e),this.movieDurationInTimescale=X(e))}break;case"trak":{let a={id:-1,demuxer:this,inputTrack:null,disposition:{...jr},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Ft,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=a,this.readContiguousBoxes(e.slice(i,n.contentSize)),a.id!==-1&&a.timescale!==-1&&a.info!==null){if(a.info.type==="video"&&a.info.width!==-1){let c=a;a.inputTrack=new Pn(this.input,new sI(c)),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){let c=a;a.inputTrack=new Et(this.input,new oI(c)),this.tracks.push(a)}}this.currentTrack=null}break;case"tkhd":{let a=this.currentTrack;if(!a)break;let c=oe(e),u=!!(nc(e)&1);if(a.disposition.default=u,c===0)e.skip(8),a.id=X(e),e.skip(4),a.durationInMovieTimescale=X(e);else if(c===1)e.skip(16),a.id=X(e),e.skip(4),a.durationInMovieTimescale=Kn(e);else throw new Error(`Incorrect track header version ${c}.`);e.skip(16);let f=[rc(e),rc(e),Qx(e),rc(e),rc(e),Qx(e),rc(e),rc(e),Qx(e)],d=Ha(ep(Ree(f),90));x(d===0||d===90||d===180||d===270),a.rotation=d}break;case"elst":{let a=this.currentTrack;if(!a)break;let c=oe(e);e.skip(3);let l=!1,u=0,f=X(e);for(let d=0;d<f;d++){let h=c===1?Kn(e):X(e),m=c===1?bU(e):Bo(e),p=rc(e);if(h!==0){if(l){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(m===-1){u+=h;continue}if(p!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}a.editListPreviousSegmentDurations=u,a.editListOffset=m,l=!0}}}break;case"mdhd":{let a=this.currentTrack;if(!a)break;let c=oe(e);e.skip(3),c===0?(e.skip(8),a.timescale=X(e),a.durationInMediaTimescale=X(e)):c===1&&(e.skip(16),a.timescale=X(e),a.durationInMediaTimescale=Kn(e));let l=jt(e);if(l>0){a.languageCode="";for(let u=0;u<3;u++)a.languageCode=String.fromCharCode(96+(l&31))+a.languageCode,l>>=5;Mo(a.languageCode)||(a.languageCode=Ft)}}break;case"hdlr":{let a=this.currentTrack;if(!a)break;e.skip(8);let c=It(e,4);c==="vide"?a.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:c==="soun"&&(a.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=r,this.readContiguousBoxes(e.slice(i,n.contentSize))}break;case"stsd":{let a=this.currentTrack;if(!a||a.info===null||a.sampleTable)break;let c=oe(e);e.skip(3);let l=X(e);for(let u=0;u<l;u++){let f=e.filePos,d=Uo(e);if(!d)break;a.internalCodecId=d.name;let h=d.name.toLowerCase();if(a.info.type==="video")h==="avc1"||h==="avc3"?(a.info.codec="avc",a.info.avcType=h==="avc1"?1:3):h==="hvc1"||h==="hev1"?a.info.codec="hevc":h==="vp08"?a.info.codec="vp8":h==="vp09"?a.info.codec="vp9":h==="av01"?a.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${d.name}').`),e.skip(24),a.info.width=jt(e),a.info.height=jt(e),a.info.squarePixelWidth=a.info.width,a.info.squarePixelHeight=a.info.height,e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,f+d.totalSize-e.filePos));else{h==="mp4a"||(h==="opus"?a.info.codec="opus":h==="flac"?a.info.codec="flac":h==="twos"||h==="sowt"||h==="raw "||h==="in24"||h==="in32"||h==="fl32"||h==="fl64"||h==="lpcm"||h==="ipcm"||h==="fpcm"||(h==="ulaw"?a.info.codec="ulaw":h==="alaw"?a.info.codec="alaw":h==="ac-3"?a.info.codec="ac3":h==="ec-3"?a.info.codec="eac3":console.warn(`Unsupported audio codec (sample entry type '${d.name}').`))),e.skip(8);let m=jt(e);e.skip(6);let p=jt(e),g=jt(e);e.skip(4);let y=X(e)/65536;if(c===0&&m>0){if(m===1)e.skip(4),g=8*X(e),e.skip(8);else if(m===2){e.skip(4),y=Zx(e),p=X(e),e.skip(4),g=X(e);let b=X(e);if(e.skip(8),h==="lpcm"){let w=g+7>>3,k=!!(b&1),T=!!(b&2),v=b&4?-1:0;g>0&&g<=64&&(k?g===32&&(a.info.codec=T?"pcm-f32be":"pcm-f32"):v&1<<w-1?w===1?a.info.codec="pcm-s8":w===2?a.info.codec=T?"pcm-s16be":"pcm-s16":w===3?a.info.codec=T?"pcm-s24be":"pcm-s24":w===4&&(a.info.codec=T?"pcm-s32be":"pcm-s32"):w===1&&(a.info.codec="pcm-u8")),a.info.codec===null&&console.warn("Unsupported PCM format.")}}}a.info.codec==="opus"&&(y=Qi),a.info.numberOfChannels=p,a.info.sampleRate=y,h==="twos"?g===8?a.info.codec="pcm-s8":g===16?a.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${g} for codec 'twos'.`),a.info.codec=null):h==="sowt"?g===8?a.info.codec="pcm-s8":g===16?a.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${g} for codec 'sowt'.`),a.info.codec=null):h==="raw "?a.info.codec="pcm-u8":h==="in24"?a.info.codec="pcm-s24be":h==="in32"?a.info.codec="pcm-s32be":h==="fl32"?a.info.codec="pcm-f32be":h==="fl64"?a.info.codec="pcm-f64be":h==="ipcm"?a.info.codec="pcm-s16be":h==="fpcm"&&(a.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,f+d.totalSize-e.filePos))}}}break;case"avcC":{let a=this.currentTrack;if(!a)break;x(a.info),a.info.codecDescription=se(e,n.contentSize)}break;case"hvcC":{let a=this.currentTrack;if(!a)break;x(a.info),a.info.codecDescription=se(e,n.contentSize)}break;case"vpcC":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="video"),e.skip(4);let c=oe(e),l=oe(e),u=oe(e),f=u>>4,d=u>>1&7,h=u&1,m=oe(e),p=oe(e),g=oe(e);a.info.vp9CodecInfo={profile:c,level:l,bitDepth:f,chromaSubsampling:d,videoFullRangeFlag:h,colourPrimaries:m,transferCharacteristics:p,matrixCoefficients:g}}break;case"av1C":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="video"),e.skip(1);let c=oe(e),l=c>>5,u=c&31,f=oe(e),d=f>>7,h=f>>6&1,m=f>>5&1,p=f>>4&1,g=f>>3&1,y=f>>2&1,b=f&3,w=l===2&&h?m?12:10:h?10:8;a.info.av1CodecInfo={profile:l,level:u,tier:d,bitDepth:w,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:y,chromaSamplePosition:b}}break;case"colr":{let a=this.currentTrack;if(!a||(x(a.info?.type==="video"),It(e,4)!=="nclx"))break;let l=jt(e),u=jt(e),f=jt(e),d=!!(oe(e)&128);a.info.colorSpace={primaries:Cl[l],transfer:Pl[u],matrix:Il[f],fullRange:d}}break;case"pasp":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="video");let c=X(e),l=X(e);c>l?a.info.squarePixelWidth=Math.round(a.info.width*c/l):a.info.squarePixelHeight=Math.round(a.info.height*l/c)}break;case"wave":this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"esds":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="audio"),e.skip(4);let c=oe(e);x(c===3),Kx(e),e.skip(2);let l=oe(e),u=(l&128)!==0,f=(l&64)!==0,d=(l&32)!==0;if(u&&e.skip(2),f){let y=oe(e);e.skip(y)}d&&e.skip(2);let h=oe(e);x(h===4);let m=Kx(e),p=e.filePos,g=oe(e);if(g===64||g===103?(a.info.codec="aac",a.info.aacCodecInfo={isMpeg2:g===103,objectType:null}):g===105||g===107?a.info.codec="mp3":g===221?a.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${g}) - discarding track.`),e.skip(12),m>e.filePos-p){let y=oe(e);x(y===5);let b=Kx(e);if(a.info.codecDescription=se(e,b),a.info.codec==="aac"){let w=js(a.info.codecDescription);w.numberOfChannels!==null&&(a.info.numberOfChannels=w.numberOfChannels),w.sampleRate!==null&&(a.info.sampleRate=w.sampleRate)}}}break;case"enda":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="audio"),jt(e)&255&&(a.info.codec==="pcm-s16be"?a.info.codec="pcm-s16":a.info.codec==="pcm-s24be"?a.info.codec="pcm-s24":a.info.codec==="pcm-s32be"?a.info.codec="pcm-s32":a.info.codec==="pcm-f32be"?a.info.codec="pcm-f32":a.info.codec==="pcm-f64be"&&(a.info.codec="pcm-f64"))}break;case"pcmC":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="audio"),e.skip(4);let l=!!(oe(e)&1),u=oe(e);a.info.codec==="pcm-s16be"?l?u===16?a.info.codec="pcm-s16":u===24?a.info.codec="pcm-s24":u===32?a.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${u}.`),a.info.codec=null):u===16?a.info.codec="pcm-s16be":u===24?a.info.codec="pcm-s24be":u===32?a.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${u}.`),a.info.codec=null):a.info.codec==="pcm-f32be"&&(l?u===32?a.info.codec="pcm-f32":u===64?a.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${u}.`),a.info.codec=null):u===32?a.info.codec="pcm-f32be":u===64?a.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${u}.`),a.info.codec=null));break}case"dOps":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="audio"),e.skip(1);let c=oe(e),l=jt(e),u=X(e),f=xp(e),d=oe(e),h;d!==0?h=se(e,2+c):h=new Uint8Array(0);let m=new Uint8Array(19+h.byteLength),p=new DataView(m.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,c),p.setUint16(10,l,!0),p.setUint32(12,u,!0),p.setInt16(16,f,!0),p.setUint8(18,d),m.set(h,19),a.info.codecDescription=m,a.info.numberOfChannels=c}break;case"dfLa":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="audio"),e.skip(4);let c=127,l=128,u=e.filePos;for(;e.filePos<s;){let p=oe(e),g=nc(e);if((p&c)===Ei.STREAMINFO){e.skip(10);let b=X(e),w=b>>>12,k=(b>>9&7)+1;a.info.sampleRate=w,a.info.numberOfChannels=k,e.skip(20)}else e.skip(g);if(p&l)break}let f=e.filePos;e.filePos=u;let d=se(e,f-u),h=new Uint8Array(4+d.byteLength);new DataView(h.buffer).setUint32(0,1716281667,!1),h.set(d,4),a.info.codecDescription=h}break;case"dac3":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="audio");let c=se(e,3),l=new Te(c),u=l.readBits(2);l.skipBits(8);let f=l.readBits(3),d=l.readBits(1);u<3&&(a.info.sampleRate=Rl[u]),a.info.numberOfChannels=ap[f]+d}break;case"dec3":{let a=this.currentTrack;if(!a)break;x(a.info?.type==="audio");let c=se(e,n.contentSize),l=rU(c);if(!l){console.warn("Invalid dec3 box contents, ignoring.");break}let u=Vx(l);u!==null&&(a.info.sampleRate=u),a.info.numberOfChannels=Wx(l)}break;case"stts":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let c=X(e),l=0,u=0;for(let f=0;f<c;f++){let d=X(e),h=X(e);a.sampleTable.sampleTimingEntries.push({startIndex:l,startDecodeTimestamp:u,count:d,delta:h}),l+=d,u+=d*h}}break;case"ctts":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let c=X(e),l=0;for(let u=0;u<c;u++){let f=X(e),d=Bo(e);a.sampleTable.sampleCompositionTimeOffsets.push({startIndex:l,count:f,offset:d}),l+=f}}break;case"stsz":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let c=X(e),l=X(e);if(c===0)for(let u=0;u<l;u++){let f=X(e);a.sampleTable.sampleSizes.push(f)}else a.sampleTable.sampleSizes.push(c)}break;case"stz2":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),e.skip(3);let c=oe(e),l=X(e),u=se(e,Math.ceil(l*c/8)),f=new Te(u);for(let d=0;d<l;d++){let h=f.readBits(c);a.sampleTable.sampleSizes.push(h)}}break;case"stss":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),a.sampleTable.keySampleIndices=[];let c=X(e);for(let l=0;l<c;l++){let u=X(e)-1;a.sampleTable.keySampleIndices.push(u)}a.sampleTable.keySampleIndices[0]!==0&&a.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let c=X(e);for(let u=0;u<c;u++){let f=X(e)-1,d=X(e),h=X(e);a.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:f,samplesPerChunk:d,sampleDescriptionIndex:h})}let l=0;for(let u=0;u<a.sampleTable.sampleToChunk.length;u++)if(a.sampleTable.sampleToChunk[u].startSampleIndex=l,u<a.sampleTable.sampleToChunk.length-1){let d=a.sampleTable.sampleToChunk[u+1].startChunkIndex-a.sampleTable.sampleToChunk[u].startChunkIndex;l+=d*a.sampleTable.sampleToChunk[u].samplesPerChunk}}break;case"stco":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let c=X(e);for(let l=0;l<c;l++){let u=X(e);a.sampleTable.chunkOffsets.push(u)}}break;case"co64":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let c=X(e);for(let l=0;l<c;l++){let u=Kn(e);a.sampleTable.chunkOffsets.push(u)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"mehd":{let a=oe(e);e.skip(3);let c=a===1?Kn(e):X(e);this.movieDurationInTimescale=c}break;case"trex":{e.skip(4);let a=X(e),c=X(e),l=X(e),u=X(e),f=X(e);this.fragmentTrackDefaults.push({trackId:a,defaultSampleDescriptionIndex:c,defaultSampleDuration:l,defaultSampleSize:u,defaultSampleFlags:f})}break;case"tfra":{let a=oe(e);e.skip(3);let c=X(e),l=this.tracks.find(w=>w.id===c);if(!l)break;let u=X(e),f=(u&48)>>4,d=(u&12)>>2,h=u&3,m=[oe,jt,nc,X],p=m[f],g=m[d],y=m[h],b=X(e);for(let w=0;w<b;w++){let k=a===1?Kn(e):X(e),T=a===1?Kn(e):X(e);p(e),g(e),y(e),l.fragmentLookupTable.push({timestamp:k,moofOffset:T})}l.fragmentLookupTable.sort((w,k)=>w.timestamp-k.timestamp);for(let w=0;w<l.fragmentLookupTable.length-1;w++){let k=l.fragmentLookupTable[w],T=l.fragmentLookupTable[w+1];k.timestamp===T.timestamp&&(l.fragmentLookupTable.splice(w+1,1),w--)}}break;case"moof":this.currentFragment={moofOffset:r,moofSize:n.totalSize,implicitBaseDataOffset:r,trackData:new Map},this.readContiguousBoxes(e.slice(i,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(x(this.currentFragment),this.readContiguousBoxes(e.slice(i,n.contentSize)),this.currentTrack){let a=this.currentFragment.trackData.get(this.currentTrack.id);if(a){let{currentFragmentState:c}=this.currentTrack;x(c),c.startTimestamp!==null&&(cI(a,c.startTimestamp),a.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{x(this.currentFragment),e.skip(1);let a=nc(e),c=!!(a&1),l=!!(a&2),u=!!(a&8),f=!!(a&16),d=!!(a&32),h=!!(a&65536),m=!!(a&131072),p=X(e),g=this.tracks.find(b=>b.id===p);if(!g)break;let y=this.fragmentTrackDefaults.find(b=>b.trackId===p);this.currentTrack=g,g.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:y?.defaultSampleDescriptionIndex??null,defaultSampleDuration:y?.defaultSampleDuration??null,defaultSampleSize:y?.defaultSampleSize??null,defaultSampleFlags:y?.defaultSampleFlags??null,startTimestamp:null},c?g.currentFragmentState.baseDataOffset=Kn(e):m&&(g.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),l&&(g.currentFragmentState.sampleDescriptionIndex=X(e)),u&&(g.currentFragmentState.defaultSampleDuration=X(e)),f&&(g.currentFragmentState.defaultSampleSize=X(e)),d&&(g.currentFragmentState.defaultSampleFlags=X(e)),h&&(g.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let a=this.currentTrack;if(!a)break;x(a.currentFragmentState);let c=oe(e);e.skip(3);let l=c===0?X(e):Kn(e);a.currentFragmentState.startTimestamp=l}break;case"trun":{let a=this.currentTrack;if(!a)break;if(x(this.currentFragment),x(a.currentFragmentState),this.currentFragment.trackData.has(a.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let c=oe(e),l=nc(e),u=!!(l&1),f=!!(l&4),d=!!(l&256),h=!!(l&512),m=!!(l&1024),p=!!(l&2048),g=X(e),y=a.currentFragmentState.baseDataOffset;u&&(y+=Bo(e));let b=null;f&&(b=X(e));let w=y;if(g===0){this.currentFragment.implicitBaseDataOffset=w;break}let k=0,T={track:a,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(a.id,T);for(let M=0;M<g;M++){let P;d?P=X(e):(x(a.currentFragmentState.defaultSampleDuration!==null),P=a.currentFragmentState.defaultSampleDuration);let N;h?N=X(e):(x(a.currentFragmentState.defaultSampleSize!==null),N=a.currentFragmentState.defaultSampleSize);let O;m?O=X(e):(x(a.currentFragmentState.defaultSampleFlags!==null),O=a.currentFragmentState.defaultSampleFlags),M===0&&b!==null&&(O=b);let Y=0;p&&(c===0?Y=X(e):Y=Bo(e));let A=!(O&65536);T.samples.push({presentationTimestamp:k+Y,duration:P,byteOffset:w,byteSize:N,isKeyFrame:A}),w+=N,k+=P}T.presentationTimestamps=T.samples.map((M,P)=>({presentationTimestamp:M.presentationTimestamp,sampleIndex:P})).sort((M,P)=>M.presentationTimestamp-P.presentationTimestamp);for(let M=0;M<T.presentationTimestamps.length;M++){let P=T.presentationTimestamps[M],N=T.samples[P.sampleIndex];if(T.firstKeyFrameTimestamp===null&&N.isKeyFrame&&(T.firstKeyFrameTimestamp=N.presentationTimestamp),M<T.presentationTimestamps.length-1){let O=T.presentationTimestamps[M+1];N.duration=O.presentationTimestamp-P.presentationTimestamp}}let v=T.samples[T.presentationTimestamps[0].sampleIndex],S=T.samples[Ze(T.presentationTimestamps).sampleIndex];T.startTimestamp=v.presentationTimestamp,T.endTimestamp=S.presentationTimestamp+S.duration,this.currentFragment.implicitBaseDataOffset=w}break;case"udta":{let a=this.iterateContiguousBoxes(e.slice(i,n.contentSize));for(let{boxInfo:c,slice:l}of a){if(c.name!=="meta"&&!this.currentTrack){let u=l.filePos;this.metadataTags.raw??={},c.name[0]==="\xA9"?this.metadataTags.raw[c.name]??=Zi(l):this.metadataTags.raw[c.name]??=se(l,c.contentSize),l.filePos=u}switch(c.name){case"meta":l.skip(-c.headerSize),this.traverseBox(l);break;case"\xA9nam":case"name":this.currentTrack?this.currentTrack.name=br.decode(se(l,c.contentSize)):this.metadataTags.title??=Zi(l);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=Zi(l));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=Zi(l));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=Zi(l));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Zi(l));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=Zi(l));break;case"\xA9day":if(!this.currentTrack){let u=new Date(Zi(l));Number.isNaN(u.getTime())||(this.metadataTags.date??=u)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=Zi(l));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=Zi(l));break}}}break;case"meta":{if(this.currentTrack)break;let c=X(e)!==0;this.currentMetadataKeys=new Map,c?this.readContiguousBoxes(e.slice(i,n.contentSize)):this.readContiguousBoxes(e.slice(i+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let a=X(e);for(let c=0;c<a;c++){let l=X(e);e.skip(4);let u=br.decode(se(e,l-8));this.currentMetadataKeys.set(c+1,u)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let a=this.iterateContiguousBoxes(e.slice(i,n.contentSize));for(let{boxInfo:c,slice:l}of a){let u=c.name,f=(u.charCodeAt(0)<<24)+(u.charCodeAt(1)<<16)+(u.charCodeAt(2)<<8)+u.charCodeAt(3);this.currentMetadataKeys.has(f)&&(u=this.currentMetadataKeys.get(f));let d=pU(l);switch(this.metadataTags.raw??={},this.metadataTags.raw[u]??=d,u){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof d=="string"&&(this.metadataTags.title??=d);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof d=="string"&&(this.metadataTags.description??=d);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof d=="string"&&(this.metadataTags.artist??=d);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof d=="string"&&(this.metadataTags.album??=d);break;case"aART":case"album_artist":typeof d=="string"&&(this.metadataTags.albumArtist??=d);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof d=="string"&&(this.metadataTags.comment??=d);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof d=="string"&&(this.metadataTags.genre??=d);break;case"\xA9lyr":case"lyrics":typeof d=="string"&&(this.metadataTags.lyrics??=d);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof d=="string"){let h=new Date(d);Number.isNaN(h.getTime())||(this.metadataTags.date??=h)}break;case"covr":case"com.apple.quicktime.artwork":d instanceof Gn?(this.metadataTags.images??=[],this.metadataTags.images.push({data:d.data,kind:"coverFront",mimeType:d.mimeType})):d instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:d,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof d=="string"){let h=d.split("/"),m=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(m)&&m>0&&(this.metadataTags.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(d instanceof Uint8Array&&d.length>=6){let h=ge(d),m=h.getUint16(2,!1),p=h.getUint16(4,!1);m>0&&(this.metadataTags.trackNumber??=m),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(d instanceof Uint8Array&&d.length>=6){let h=ge(d),m=h.getUint16(2,!1),p=h.getUint16(4,!1);m>0&&(this.metadataTags.discNumber??=m),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=s,!0}},Xx=class{static{o(this,"IsobmffTrackBacking")}constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,n=this.internalTrack.inputTrack.type,i=0;for(let s of e.tracks)if(s.inputTrack.type===n&&i++,s===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){let r=await this.fetchPacketForSampleIndex(0,e);return r||!this.internalTrack.demuxer.isFragmented?r:this.performFragmentedLookup(null,n=>n.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Do(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,r){let n=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=aI(i,n),a=await this.fetchPacketForSampleIndex(s,r);return!gU(i)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,c=>{let l=c.trackData.get(this.internalTrack.id);if(!l)return{sampleIndex:-1,correctSampleFound:!1};let u=ze(l.presentationTimestamps,n,h=>h.presentationTimestamp),f=u!==-1?l.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&n<l.endTimestamp;return{sampleIndex:f,correctSampleFound:d}},n,n,r)}async getNextPacket(e,r){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,r);let i=this.packetToFragmentLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,s=>{if(s===i.fragment){let a=s.trackData.get(this.internalTrack.id);if(i.sampleIndex+1<a.samples.length)return{sampleIndex:i.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,r)}async getKeyPacket(e,r){let n=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Dee(i,n),a=await this.fetchPacketForSampleIndex(s,r);return!gU(i)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,c=>{let l=c.trackData.get(this.internalTrack.id);if(!l)return{sampleIndex:-1,correctSampleFound:!1};let u=qf(l.presentationTimestamps,h=>l.samples[h.sampleIndex].isKeyFrame&&h.presentationTimestamp<=n),f=u!==-1?l.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&n<l.endTimestamp;return{sampleIndex:f,correctSampleFound:d}},n,n,r)}async getNextKeyPacket(e,r){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Oee(s,n);return this.fetchPacketForSampleIndex(a,r)}let i=this.packetToFragmentLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,s=>{if(s===i.fragment){let c=s.trackData.get(this.internalTrack.id).samples.findIndex((l,u)=>l.isKeyFrame&&u>i.sampleIndex);if(c!==-1)return{sampleIndex:c,correctSampleFound:!0}}else{let a=s.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){let c=a.samples.findIndex(l=>l.isKeyFrame);return x(c!==-1),{sampleIndex:c,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,r)}async fetchPacketForSampleIndex(e,r){if(e===-1)return null;let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=Mee(n,e);if(!i)return null;let s;if(r.metadataOnly)s=Wt;else{let u=this.internalTrack.demuxer.reader.requestSlice(i.sampleOffset,i.sampleSize);u instanceof Promise&&(u=await u),x(u),s=se(u,i.sampleSize)}let a=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=i.duration/this.internalTrack.timescale,l=new je(s,i.isKeyFrame?"key":"delta",a,c,e,i.sampleSize);return this.packetToSampleIndex.set(l,e),l}async fetchPacketInFragment(e,r,n){if(r===-1)return null;let s=e.trackData.get(this.internalTrack.id).samples[r];x(s);let a;if(n.metadataOnly)a=Wt;else{let f=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);f instanceof Promise&&(f=await f),x(f),a=se(f,s.byteSize)}let c=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,l=s.duration/this.internalTrack.timescale,u=new je(a,s.isKeyFrame?"key":"delta",c,l,e.moofOffset+r,s.byteSize);return this.packetToFragmentLocation.set(u,{fragment:e,sampleIndex:r}),u}async performFragmentedLookup(e,r,n,i,s){let a=this.internalTrack.demuxer,c=null,l=null,u=-1;if(e){let{sampleIndex:y,correctSampleFound:b}=r(e);if(b)return this.fetchPacketInFragment(e,y,s);y!==-1&&(l=e,u=y)}let f=ze(this.internalTrack.fragmentLookupTable,n,y=>y.timestamp),d=f!==-1?this.internalTrack.fragmentLookupTable[f]:null,h=ze(this.internalTrack.fragmentPositionCache,n,y=>y.startTimestamp),m=h!==-1?this.internalTrack.fragmentPositionCache[h]:null,p=Math.max(d?.moofOffset??0,m?.moofOffset??0)||null,g;for(e?p===null||e.moofOffset>=p?(g=e.moofOffset+e.moofSize,c=e):g=p:g=p??0;;){if(c){let k=c.trackData.get(this.internalTrack.id);if(k&&k.startTimestamp>i)break}let y=a.reader.requestSliceRange(g,Ji,zo);if(y instanceof Promise&&(y=await y),!y)break;let b=g,w=Uo(y);if(!w)break;if(w.name==="moof"){c=await a.readFragment(b);let{sampleIndex:k,correctSampleFound:T}=r(c);if(T)return this.fetchPacketInFragment(c,k,s);k!==-1&&(l=c,u=k)}g=b+w.totalSize}if(d&&(!l||l.moofOffset<d.moofOffset)){let y=this.internalTrack.fragmentLookupTable[f-1];x(!y||y.timestamp<d.timestamp);let b=y?.timestamp??-1/0;return this.performFragmentedLookup(null,r,b,i,s)}return l?this.fetchPacketInFragment(l,u,s):null}},sI=class extends Xx{static{o(this,"IsobmffVideoTrackBacking")}constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let r=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=r&&Lx(r.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let r=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=r&&Bx(r.data)}let e={codec:Gf(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}},oI=class extends Xx{static{o(this,"IsobmffAudioTrackBacking")}constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:Qf(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},aI=o((t,e)=>{if(t.presentationTimestamps){let r=ze(t.presentationTimestamps,e,n=>n.presentationTimestamp);return r===-1?-1:t.presentationTimestamps[r].sampleIndex}else{let r=ze(t.sampleTimingEntries,e,i=>i.startDecodeTimestamp);if(r===-1)return-1;let n=t.sampleTimingEntries[r];return n.startIndex+Math.min(Math.floor((e-n.startDecodeTimestamp)/n.delta),n.count-1)}},"getSampleIndexForTimestamp"),Dee=o((t,e)=>{if(!t.keySampleIndices)return aI(t,e);if(t.presentationTimestamps){let r=ze(t.presentationTimestamps,e,n=>n.presentationTimestamp);if(r===-1)return-1;for(let n=r;n>=0;n--){let i=t.presentationTimestamps[n].sampleIndex;if(_o(t.keySampleIndices,i,a=>a)!==-1)return i}return-1}else{let r=aI(t,e),n=ze(t.keySampleIndices,r,i=>i);return t.keySampleIndices[n]??-1}},"getKeyframeSampleIndexForTimestamp"),Mee=o((t,e)=>{let r=ze(t.sampleTimingEntries,e,b=>b.startIndex),n=t.sampleTimingEntries[r];if(!n||n.startIndex+n.count<=e)return null;let s=n.startDecodeTimestamp+(e-n.startIndex)*n.delta,a=ze(t.sampleCompositionTimeOffsets,e,b=>b.startIndex),c=t.sampleCompositionTimeOffsets[a];c&&e-c.startIndex<c.count&&(s+=c.offset);let l=t.sampleSizes[Math.min(e,t.sampleSizes.length-1)],u=ze(t.sampleToChunk,e,b=>b.startSampleIndex),f=t.sampleToChunk[u];x(f);let d=f.startChunkIndex+Math.floor((e-f.startSampleIndex)/f.samplesPerChunk),h=t.chunkOffsets[d],m=f.startSampleIndex+(d-f.startChunkIndex)*f.samplesPerChunk,p=0,g=h;if(t.sampleSizes.length===1)g+=l*(e-m),p+=l*f.samplesPerChunk;else for(let b=m;b<m+f.samplesPerChunk;b++){let w=t.sampleSizes[b];b<e&&(g+=w),p+=w}let y=n.delta;if(t.presentationTimestamps){let b=t.presentationTimestampIndexMap[e];x(b!==void 0),b<t.presentationTimestamps.length-1&&(y=t.presentationTimestamps[b+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:y,sampleOffset:g,sampleSize:l,chunkOffset:h,chunkSize:p,isKeyFrame:t.keySampleIndices?_o(t.keySampleIndices,e,b=>b)!==-1:!0}},"getSampleInfo"),Oee=o((t,e)=>{if(!t.keySampleIndices)return e+1;let r=ze(t.keySampleIndices,e,n=>n);return t.keySampleIndices[r+1]??-1},"getNextKeyframeIndexForSample"),cI=o((t,e)=>{t.startTimestamp+=e,t.endTimestamp+=e;for(let r of t.samples)r.presentationTimestamp+=e;for(let r of t.presentationTimestamps)r.presentationTimestamp+=e},"offsetFragmentTrackDataByTimestamp"),Ree=o(t=>{let[e,r]=t,n=Math.atan2(r,e);return Number.isFinite(n)?n*(180/Math.PI):0},"extractRotationFromMatrix"),gU=o(t=>t.sampleSizes.length===0,"sampleTableIsEmpty")});function $o(t){if(t===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}var ad,cd,kp,es,I,Nee,ld,Sp,wU,xU,kU,Aee,ek,lI,In,ts,uI,ud,Oe,SU,Yvt,tk,fI,rs,ic,fd,rk,nk,dI,on,ik=he(()=>{Ue();qt();ad=class{static{o(this,"EBMLFloat32")}constructor(e){this.value=e}},cd=class{static{o(this,"EBMLFloat64")}constructor(e){this.value=e}},kp=class{static{o(this,"EBMLSignedInt")}constructor(e){this.value=e}},es=class{static{o(this,"EBMLUnicodeString")}constructor(e){this.value=e}};(function(t){t[t.EBML=440786851]="EBML",t[t.EBMLVersion=17030]="EBMLVersion",t[t.EBMLReadVersion=17143]="EBMLReadVersion",t[t.EBMLMaxIDLength=17138]="EBMLMaxIDLength",t[t.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",t[t.DocType=17026]="DocType",t[t.DocTypeVersion=17031]="DocTypeVersion",t[t.DocTypeReadVersion=17029]="DocTypeReadVersion",t[t.Void=236]="Void",t[t.Segment=408125543]="Segment",t[t.SeekHead=290298740]="SeekHead",t[t.Seek=19899]="Seek",t[t.SeekID=21419]="SeekID",t[t.SeekPosition=21420]="SeekPosition",t[t.Duration=17545]="Duration",t[t.Info=357149030]="Info",t[t.TimestampScale=2807729]="TimestampScale",t[t.MuxingApp=19840]="MuxingApp",t[t.WritingApp=22337]="WritingApp",t[t.Tracks=374648427]="Tracks",t[t.TrackEntry=174]="TrackEntry",t[t.TrackNumber=215]="TrackNumber",t[t.TrackUID=29637]="TrackUID",t[t.TrackType=131]="TrackType",t[t.FlagEnabled=185]="FlagEnabled",t[t.FlagDefault=136]="FlagDefault",t[t.FlagForced=21930]="FlagForced",t[t.FlagOriginal=21934]="FlagOriginal",t[t.FlagHearingImpaired=21931]="FlagHearingImpaired",t[t.FlagVisualImpaired=21932]="FlagVisualImpaired",t[t.FlagCommentary=21935]="FlagCommentary",t[t.FlagLacing=156]="FlagLacing",t[t.Name=21358]="Name",t[t.Language=2274716]="Language",t[t.LanguageBCP47=2274717]="LanguageBCP47",t[t.CodecID=134]="CodecID",t[t.CodecPrivate=25506]="CodecPrivate",t[t.CodecDelay=22186]="CodecDelay",t[t.SeekPreRoll=22203]="SeekPreRoll",t[t.DefaultDuration=2352003]="DefaultDuration",t[t.Video=224]="Video",t[t.PixelWidth=176]="PixelWidth",t[t.PixelHeight=186]="PixelHeight",t[t.DisplayWidth=21680]="DisplayWidth",t[t.DisplayHeight=21690]="DisplayHeight",t[t.DisplayUnit=21682]="DisplayUnit",t[t.AlphaMode=21440]="AlphaMode",t[t.Audio=225]="Audio",t[t.SamplingFrequency=181]="SamplingFrequency",t[t.Channels=159]="Channels",t[t.BitDepth=25188]="BitDepth",t[t.SimpleBlock=163]="SimpleBlock",t[t.BlockGroup=160]="BlockGroup",t[t.Block=161]="Block",t[t.BlockAdditions=30113]="BlockAdditions",t[t.BlockMore=166]="BlockMore",t[t.BlockAdditional=165]="BlockAdditional",t[t.BlockAddID=238]="BlockAddID",t[t.BlockDuration=155]="BlockDuration",t[t.ReferenceBlock=251]="ReferenceBlock",t[t.Cluster=524531317]="Cluster",t[t.Timestamp=231]="Timestamp",t[t.Cues=475249515]="Cues",t[t.CuePoint=187]="CuePoint",t[t.CueTime=179]="CueTime",t[t.CueTrackPositions=183]="CueTrackPositions",t[t.CueTrack=247]="CueTrack",t[t.CueClusterPosition=241]="CueClusterPosition",t[t.Colour=21936]="Colour",t[t.MatrixCoefficients=21937]="MatrixCoefficients",t[t.TransferCharacteristics=21946]="TransferCharacteristics",t[t.Primaries=21947]="Primaries",t[t.Range=21945]="Range",t[t.Projection=30320]="Projection",t[t.ProjectionType=30321]="ProjectionType",t[t.ProjectionPoseRoll=30325]="ProjectionPoseRoll",t[t.Attachments=423732329]="Attachments",t[t.AttachedFile=24999]="AttachedFile",t[t.FileDescription=18046]="FileDescription",t[t.FileName=18030]="FileName",t[t.FileMediaType=18016]="FileMediaType",t[t.FileData=18012]="FileData",t[t.FileUID=18094]="FileUID",t[t.Chapters=272869232]="Chapters",t[t.Tags=307544935]="Tags",t[t.Tag=29555]="Tag",t[t.Targets=25536]="Targets",t[t.TargetTypeValue=26826]="TargetTypeValue",t[t.TargetType=25546]="TargetType",t[t.TagTrackUID=25541]="TagTrackUID",t[t.TagEditionUID=25545]="TagEditionUID",t[t.TagChapterUID=25540]="TagChapterUID",t[t.TagAttachmentUID=25542]="TagAttachmentUID",t[t.SimpleTag=26568]="SimpleTag",t[t.TagName=17827]="TagName",t[t.TagLanguage=17530]="TagLanguage",t[t.TagString=17543]="TagString",t[t.TagBinary=17541]="TagBinary",t[t.ContentEncodings=28032]="ContentEncodings",t[t.ContentEncoding=25152]="ContentEncoding",t[t.ContentEncodingOrder=20529]="ContentEncodingOrder",t[t.ContentEncodingScope=20530]="ContentEncodingScope",t[t.ContentCompression=20532]="ContentCompression",t[t.ContentCompAlgo=16980]="ContentCompAlgo",t[t.ContentCompSettings=16981]="ContentCompSettings",t[t.ContentEncryption=20533]="ContentEncryption"})(I||(I={}));Nee=[I.EBML,I.Segment],ld=[I.SeekHead,I.Info,I.Cluster,I.Tracks,I.Cues,I.Attachments,I.Chapters,I.Tags],Sp=[...Nee,...ld],wU=o(t=>t<256?1:t<65536?2:t<1<<24?3:t<2**32?4:t<2**40?5:6,"measureUnsignedInt"),xU=o(t=>t<1n<<8n?1:t<1n<<16n?2:t<1n<<24n?3:t<1n<<32n?4:t<1n<<40n?5:t<1n<<48n?6:t<1n<<56n?7:8,"measureUnsignedBigInt"),kU=o(t=>t>=-64&&t<64?1:t>=-8192&&t<8192?2:t>=-(1<<20)&&t<1<<20?3:t>=-(1<<27)&&t<1<<27?4:t>=-(2**34)&&t<2**34?5:6,"measureSignedInt"),Aee=o(t=>{if(t<127)return 1;if(t<16383)return 2;if(t<(1<<21)-1)return 3;if(t<(1<<28)-1)return 4;if(t<2**35-1)return 5;if(t<2**42-1)return 6;throw new Error("EBML varint size not supported "+t)},"measureVarInt"),ek=class{static{o(this,"EBMLWriter")}constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,r=wU(e)){let n=0;switch(r){case 6:this.helperView.setUint8(n++,e/2**40|0);case 5:this.helperView.setUint8(n++,e/2**32|0);case 4:this.helperView.setUint8(n++,e>>24);case 3:this.helperView.setUint8(n++,e>>16);case 2:this.helperView.setUint8(n++,e>>8);case 1:this.helperView.setUint8(n++,e);break;default:throw new Error("Bad unsigned int size "+r)}this.writer.write(this.helper.subarray(0,n))}writeUnsignedBigInt(e,r=xU(e)){let n=0;for(let i=r-1;i>=0;i--)this.helperView.setUint8(n++,Number(e>>BigInt(i*8)&0xffn));this.writer.write(this.helper.subarray(0,n))}writeSignedInt(e,r=kU(e)){e<0&&(e+=2**(r*8)),this.writeUnsignedInt(e,r)}writeVarInt(e,r=Aee(e)){let n=0;switch(r){case 1:this.helperView.setUint8(n++,128|e);break;case 2:this.helperView.setUint8(n++,64|e>>8),this.helperView.setUint8(n++,e);break;case 3:this.helperView.setUint8(n++,32|e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 4:this.helperView.setUint8(n++,16|e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 5:this.helperView.setUint8(n++,8|e/2**32&7),this.helperView.setUint8(n++,e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 6:this.helperView.setUint8(n++,4|e/2**40&3),this.helperView.setUint8(n++,e/2**32|0),this.helperView.setUint8(n++,e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;default:throw new Error("Bad EBML varint size "+r)}this.writer.write(this.helper.subarray(0,n))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split("").map(r=>r.charCodeAt(0))))}writeEBML(e){if(e!==null)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(let r of e)this.writeEBML(r);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){let r=this.writer.getPos(),n=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+n);let i=this.writer.getPos();if(this.dataOffsets.set(e,i),this.writeEBML(e.data),e.size!==-1){let s=this.writer.getPos()-i,a=this.writer.getPos();this.writer.seek(r),this.writeVarInt(s,n),this.writer.seek(a)}}else if(typeof e.data=="number"){let r=e.size??wU(e.data);this.writeVarInt(r),this.writeUnsignedInt(e.data,r)}else if(typeof e.data=="bigint"){let r=e.size??xU(e.data);this.writeVarInt(r),this.writeUnsignedBigInt(e.data,r)}else if(typeof e.data=="string")this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof ad)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof cd)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof kp){let r=e.size??kU(e.data.value);this.writeVarInt(r),this.writeSignedInt(e.data.value,r)}else if(e.data instanceof es){let r=lt.encode(e.data.value);this.writeVarInt(r.length),this.writer.write(r)}else kt(e.data)}},lI=8,In=2,ts=2*lI,uI=o(t=>{if(t.remainingLength<1)return null;let e=oe(t);if(t.skip(-1),e===0)return null;let r=1,n=128;for(;(e&n)===0;)r++,n>>=1;return t.remainingLength<r?null:r},"readVarIntSize"),ud=o(t=>{if(t.remainingLength<1)return null;let e=oe(t);if(e===0)return null;let r=1,n=128;for(;(e&n)===0;)r++,n>>=1;if(t.remainingLength<r-1)return null;let i=e&n-1;for(let s=1;s<r;s++)i*=256,i+=oe(t);return i},"readVarInt"),Oe=o((t,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let r=0;for(let n=0;n<e;n++)r*=256,r+=oe(t);return r},"readUnsignedInt"),SU=o((t,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let r=0n;for(let n=0;n<e;n++)r<<=8n,r+=BigInt(oe(t));return r},"readUnsignedBigInt"),Yvt=o((t,e)=>{let r=Oe(t,e);return r&1<<e*8-1&&(r-=2**(e*8)),r},"readSignedInt"),tk=o(t=>{let e=uI(t);return e===null||t.remainingLength<e?null:Oe(t,e)},"readElementId"),fI=o(t=>{if(t.remainingLength<1)return null;if(oe(t)===255)return;t.skip(-1);let r=ud(t);if(r===null)return null;if(r!==72057594037927940)return r},"readElementSize"),rs=o(t=>{x(t.remainingLength>=In);let e=tk(t);if(e===null)return null;let r=fI(t);return r===null?null:{id:e,size:r}},"readElementHeader"),ic=o((t,e)=>{let r=se(t,e),n=0;for(;n<e&&r[n]!==0;)n+=1;return String.fromCharCode(...r.subarray(0,n))},"readAsciiString"),fd=o((t,e)=>{let r=se(t,e),n=0;for(;n<e&&r[n]!==0;)n+=1;return br.decode(r.subarray(0,n))},"readUnicodeString"),rk=o((t,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?TU(t):Zx(t)},"readFloat"),nk=o(async(t,e,r,n)=>{let i=new Set(r),s=e;for(;n===null||s<n;){let a=t.requestSliceRange(s,In,ts);if(a instanceof Promise&&(a=await a),!a)break;let c=rs(a);if(!c)break;if(i.has(c.id))return{pos:s,found:!0};$o(c.size),s=a.filePos+c.size}return{pos:n!==null&&n>s?n:s,found:!1}},"searchForNextElementId"),dI=o(async(t,e,r,n)=>{let s=new Set(r),a=e;for(;a<n;){let c=t.requestSliceRange(a,0,Math.min(65536,n-a));if(c instanceof Promise&&(c=await c),!c||c.length<lI)break;for(let l=0;l<c.length-lI;l++){c.filePos=a;let u=tk(c);if(u!==null&&s.has(u))return a;a++}}return null},"resync"),on={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};o($o,"assertDefinedSize")});var sk,hI=he(()=>{sk=o(t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isWebM?"webm":"x-matroska");if(t.codecStrings.length>0){let n=[...new Set(t.codecStrings.filter(Boolean))];r+=`; codecs="${n.join(", ")}"`}return r},"buildMatroskaMimeType")});var Ho,ok,Tp,mI,vU,ck,ak,pI,gI,EU=he(()=>{sn();Zt();Fo();Xi();lr();Ue();Qn();ik();hI();qt();(function(t){t[t.None=0]="None",t[t.Xiph=1]="Xiph",t[t.FixedSize=2]="FixedSize",t[t.Ebml=3]="Ebml"})(Ho||(Ho={}));(function(t){t[t.Block=1]="Block",t[t.Private=2]="Private",t[t.Next=4]="Next"})(ok||(ok={}));(function(t){t[t.Zlib=0]="Zlib",t[t.Bzlib=1]="Bzlib",t[t.lzo1x=2]="lzo1x",t[t.HeaderStripping=3]="HeaderStripping"})(Tp||(Tp={}));mI=[{id:I.SeekHead,flag:"seekHeadSeen"},{id:I.Info,flag:"infoSeen"},{id:I.Tracks,flag:"tracksSeen"},{id:I.Cues,flag:"cuesSeen"}],vU=10*2**20,ck=class extends wr{static{o(this,"MatroskaDemuxer")}constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...r)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(r=>r.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.getCodecParameterString()));return sk({isWebM:this.isWebM,hasVideo:this.segments.some(n=>n.tracks.some(i=>i.info?.type==="video")),hasAudio:this.segments.some(n=>n.tracks.some(i=>i.info?.type==="audio")),codecStrings:r.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let r of this.segments)r.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(r),r.metadataTagsCollected=!0);let e={};for(let r of this.segments)e={...e,...r.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,In,ts);if(r instanceof Promise&&(r=await r),!r)break;let n=rs(r);if(!n)break;let i=n.id,s=n.size,a=r.filePos;if(i===I.EBML){$o(s);let c=this.reader.requestSlice(a,s);if(c instanceof Promise&&(c=await c),!c)break;this.readContiguousElements(c)}else if(i===I.Segment){if(await this.readSegment(a,s),s===void 0||this.reader.fileSize===null)break}else if(i===I.Cluster){if(this.reader.fileSize===null)break;s===void 0&&(s=(await nk(this.reader,a,Sp,this.reader.fileSize)).pos-a);let c=Ze(this.segments);c&&(c.elementEndPos=a+s)}$o(s),e=a+s}})()}async readSegment(e,r){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:r===void 0?null:e+r,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let c=this.reader.requestSliceRange(n,In,ts);if(c instanceof Promise&&(c=await c),!c)break;let l=n,u=rs(c);if(!u||!ld.includes(u.id)&&u.id!==I.Void){let p=await dI(this.reader,l,ld,Math.min(this.currentSegment.elementEndPos??1/0,l+vU));if(p){n=p;continue}else break}let{id:f,size:d}=u,h=c.filePos,m=mI.findIndex(p=>p.id===f);if(m!==-1){let p=mI[m].flag;this.currentSegment[p]=!0,$o(d);let g=this.reader.requestSlice(h,d);g instanceof Promise&&(g=await g),g&&this.readContiguousElements(g)}else if(f===I.Tags||f===I.Attachments){f===I.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,$o(d);let p=this.reader.requestSlice(h,d);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(f===I.Cluster){this.currentSegment.clusterSeekStartPos=l;break}if(d===void 0)break;n=h+d}if(this.currentSegment.seekEntries.sort((c,l)=>c.segmentPosition-l.segmentPosition),this.reader.fileSize!==null)for(let c of this.currentSegment.seekEntries){let l=mI.find(p=>p.id===c.id);if(!l||this.currentSegment[l.flag])continue;let u=this.reader.requestSliceRange(e+c.segmentPosition,In,ts);if(u instanceof Promise&&(u=await u),!u)continue;let f=rs(u);if(!f)continue;let{id:d,size:h}=f;if(d!==l.id)continue;$o(h),this.currentSegment[l.flag]=!0;let m=this.reader.requestSlice(u.filePos,h);m instanceof Promise&&(m=await m),m&&this.readContiguousElements(m)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(let c of this.currentSegment.tracks)c.defaultDurationNs!==null&&(c.defaultDuration=this.currentSegment.timestampFactor*c.defaultDurationNs/1e9);this.currentSegment.tracks.sort((c,l)=>Number(l.disposition.default)-Number(c.disposition.default));let i=new Map(this.currentSegment.tracks.map(c=>[c.id,c]));for(let c of this.currentSegment.cuePoints){let l=i.get(c.trackId);l&&l.cuePoints.push(c)}for(let c of this.currentSegment.tracks){c.cuePoints.sort((l,u)=>l.time-u.time);for(let l=0;l<c.cuePoints.length-1;l++){let u=c.cuePoints[l],f=c.cuePoints[l+1];u.time===f.time&&(c.cuePoints.splice(l+1,1),l--)}}let s=null,a=-1/0;for(let c of this.currentSegment.tracks)c.cuePoints.length>a&&(a=c.cuePoints.length,s=c);for(let c of this.currentSegment.tracks)c.cuePoints.length===0&&(c.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,r){if(r.lastReadCluster?.elementStartPos===e)return r.lastReadCluster;let n=this.reader.requestSliceRange(e,In,ts);n instanceof Promise&&(n=await n),x(n);let i=e,s=rs(n);x(s);let a=s.id;x(a===I.Cluster);let c=s.size,l=n.filePos;c===void 0&&(c=(await nk(this.reader,l,Sp,r.elementEndPos)).pos-l);let u=this.reader.requestSlice(l,c);u instanceof Promise&&(u=await u);let f={segment:r,elementStartPos:i,elementEndPos:l+c,dataStartPos:l,timestamp:-1,trackData:new Map};if(this.currentCluster=f,u){let d=this.readContiguousElements(u,Sp);f.elementEndPos=d}for(let[,d]of f.trackData){let h=d.track;x(d.blocks.length>0);let m=!1;for(let b=0;b<d.blocks.length;b++){let w=d.blocks[b];w.timestamp+=f.timestamp,m||=w.lacing!==Ho.None}d.presentationTimestamps=d.blocks.map((b,w)=>({timestamp:b.timestamp,blockIndex:w})).sort((b,w)=>b.timestamp-w.timestamp);for(let b=0;b<d.presentationTimestamps.length;b++){let w=d.presentationTimestamps[b],k=d.blocks[w.blockIndex];if(d.firstKeyFrameTimestamp===null&&k.isKeyFrame&&(d.firstKeyFrameTimestamp=k.timestamp),b<d.presentationTimestamps.length-1){let T=d.presentationTimestamps[b+1];k.duration=T.timestamp-k.timestamp}else k.duration===0&&h.defaultDuration!=null&&k.lacing===Ho.None&&(k.duration=h.defaultDuration)}m&&(this.expandLacedBlocks(d.blocks,h),d.presentationTimestamps=d.blocks.map((b,w)=>({timestamp:b.timestamp,blockIndex:w})).sort((b,w)=>b.timestamp-w.timestamp));let p=d.blocks[d.presentationTimestamps[0].blockIndex],g=d.blocks[Ze(d.presentationTimestamps).blockIndex];d.startTimestamp=p.timestamp,d.endTimestamp=g.timestamp+g.duration;let y=ze(h.clusterPositionCache,d.startTimestamp,b=>b.startTimestamp);(y===-1||h.clusterPositionCache[y].elementStartPos!==i)&&h.clusterPositionCache.splice(y+1,0,{elementStartPos:f.elementStartPos,startTimestamp:d.startTimestamp})}return r.lastReadCluster=f,f}getTrackDataInCluster(e,r){let n=e.trackData.get(r);if(!n){let i=e.segment.tracks.find(s=>s.id===r);if(!i)return null;n={track:i,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(r,n)}return n}expandLacedBlocks(e,r){for(let n=0;n<e.length;n++){let i=e[n];if(i.lacing===Ho.None)continue;i.decoded||(i.data=this.decodeBlockData(r,i.data),i.decoded=!0);let s=xr.tempFromBytes(i.data),a=[],c=oe(s)+1;switch(i.lacing){case Ho.Xiph:{let u=0;for(let f=0;f<c-1;f++){let d=0;for(;s.bufferPos<s.length;){let h=oe(s);if(d+=h,h<255){a.push(d),u+=d;break}}}a.push(s.length-(s.bufferPos+u))}break;case Ho.FixedSize:{let u=s.length-1,f=Math.floor(u/c);for(let d=0;d<c;d++)a.push(f)}break;case Ho.Ebml:{let u=ud(s);x(u!==null);let f=u;a.push(f);let d=f;for(let h=1;h<c-1;h++){let m=s.bufferPos,p=ud(s);x(p!==null);let g=p,b=(1<<(s.bufferPos-m)*7-1)-1,w=g-b;f+=w,a.push(f),d+=f}a.push(s.length-(s.bufferPos+d))}break;default:x(!1)}x(a.length===c),e.splice(n,1);let l=i.duration||c*(r.defaultDuration??0);for(let u=0;u<c;u++){let f=a[u],d=se(s,f),h=i.timestamp+l*u/c,m=l/c;e.splice(n+u,0,{timestamp:h,duration:m,isKeyFrame:i.isKeyFrame,data:d,lacing:Ho.None,decoded:!0,mainAdditional:i.mainAdditional})}n+=c,n--}}async loadSegmentMetadata(e){for(let r of e.seekEntries){if(!(r.id===I.Tags&&!e.tagsSeen)){if(!(r.id===I.Attachments&&!e.attachmentsSeen))continue}let n=this.reader.requestSliceRange(e.dataStartPos+r.segmentPosition,In,ts);if(n instanceof Promise&&(n=await n),!n)continue;let i=rs(n);if(!i||i.id!==r.id)continue;let{size:s}=i;$o(s),x(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(n.filePos,s);a instanceof Promise&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,r.id===I.Tags?e.tagsSeen=!0:r.id===I.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,r){for(;e.remainingLength>=In;){let n=e.filePos;if(!this.traverseElement(e,r))return n}return e.filePos}traverseElement(e,r){let n=rs(e);if(!n||r&&r.includes(n.id))return!1;let{id:i,size:s}=n,a=e.filePos;switch($o(s),i){case I.DocType:this.isWebM=ic(e,s)==="webm";break;case I.Seek:{if(!this.currentSegment)break;let c={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(c),this.readContiguousElements(e.slice(a,s)),(c.id===-1||c.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case I.SeekID:{let c=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!c)break;c.id=Oe(e,s)}break;case I.SeekPosition:{let c=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!c)break;c.segmentPosition=Oe(e,s)}break;case I.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=Oe(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case I.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=rk(e,s)}break;case I.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...jr},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(c=>c.data?.type!=="decompress"||c.scope!==ok.Block||c.data.algorithm!==Tp.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let c=this.currentTrack.codecId.indexOf("/"),l=c===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,c);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let d=this.currentTrack.info.displayWidth*this.currentTrack.info.height,h=this.currentTrack.info.displayHeight*this.currentTrack.info.width;d>h?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*d/h):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*h/d)}this.currentTrack.codecId===on.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===on.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):l===on.vp8?this.currentTrack.info.codec="vp8":l===on.vp9?this.currentTrack.info.codec="vp9":l===on.av1&&(this.currentTrack.info.codec="av1");let u=this.currentTrack,f=new Pn(this.input,new pI(u));this.currentTrack.inputTrack=f,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){l===on.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===on.mp3?this.currentTrack.info.codec="mp3":l===on.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Qi):l===on.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):l===on.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):l===on.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):l===on.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));let u=this.currentTrack,f=new Et(this.input,new gI(u));this.currentTrack.inputTrack=f,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case I.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=Oe(e,s)}break;case I.TrackType:{if(!this.currentTrack)break;let c=Oe(e,s);c===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:c===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case I.FlagEnabled:{if(!this.currentTrack)break;Oe(e,s)||(this.currentTrack=null)}break;case I.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Oe(e,s)}break;case I.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Oe(e,s)}break;case I.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Oe(e,s)}break;case I.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Oe(e,s)}break;case I.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Oe(e,s)}break;case I.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Oe(e,s)}break;case I.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=ic(e,s)}break;case I.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=se(e,s)}break;case I.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Oe(e,s)}break;case I.Name:{if(!this.currentTrack)break;this.currentTrack.name=fd(e,s)}break;case I.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=ic(e,s),Mo(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Ft)}break;case I.LanguageBCP47:{if(!this.currentTrack)break;let l=ic(e,s).split("-")[0];l?this.currentTrack.languageCode=l:this.currentTrack.languageCode=Ft,this.currentTrack.hasLanguageBcp47=!0}break;case I.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case I.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=Oe(e,s)}break;case I.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=Oe(e,s)}break;case I.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=Oe(e,s)}break;case I.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=Oe(e,s)}break;case I.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=Oe(e,s)}break;case I.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=Oe(e,s)===1}break;case I.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(a,s))}break;case I.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let c=Oe(e,s),l=Il[c]??null;this.currentTrack.info.colorSpace.matrix=l}break;case I.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=Oe(e,s)===2}break;case I.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let c=Oe(e,s),l=Pl[c]??null;this.currentTrack.info.colorSpace.transfer=l}break;case I.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let c=Oe(e,s),l=Cl[c]??null;this.currentTrack.info.colorSpace.primaries=l}break;case I.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case I.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let l=-rk(e,s);try{this.currentTrack.info.rotation=Ha(l)}catch{}}break;case I.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(a,s))}break;case I.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=rk(e,s)}break;case I.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=Oe(e,s)}break;case I.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=Oe(e,s)}break;case I.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,s)),this.currentCueTime=null}break;case I.CueTime:this.currentCueTime=Oe(e,s);break;case I.CueTrackPositions:{if(this.currentCueTime===null)break;x(this.currentSegment);let c={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(c),this.readContiguousElements(e.slice(a,s)),(c.trackId===-1||c.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case I.CueTrack:{let c=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!c)break;c.trackId=Oe(e,s)}break;case I.CueClusterPosition:{let c=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!c)break;x(this.currentSegment),c.clusterPosition=this.currentSegment.dataStartPos+Oe(e,s)}break;case I.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=Oe(e,s)}break;case I.SimpleBlock:{if(!this.currentCluster)break;let c=ud(e);if(c===null)break;let l=this.getTrackDataInCluster(this.currentCluster,c);if(!l)break;let u=xp(e),f=oe(e),d=f>>1&3,h=!!(f&128);l.track.info?.type==="audio"&&l.track.info.codec&&(h=!0);let m=se(e,s-(e.filePos-a)),p=l.track.decodingInstructions.length>0;l.blocks.push({timestamp:u,duration:0,isKeyFrame:h,data:m,lacing:d,decoded:!p,mainAdditional:null})}break;case I.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,s)),this.currentBlock=null}break;case I.Block:{if(!this.currentCluster)break;let c=ud(e);if(c===null)break;let l=this.getTrackDataInCluster(this.currentCluster,c);if(!l)break;let u=xp(e),d=oe(e)>>1&3,h=se(e,s-(e.filePos-a)),m=l.track.decodingInstructions.length>0;this.currentBlock={timestamp:u,duration:0,isKeyFrame:!0,data:h,lacing:d,decoded:!m,mainAdditional:null},l.blocks.push(this.currentBlock)}break;case I.BlockAdditions:this.readContiguousElements(e.slice(a,s));break;case I.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case I.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=se(e,s)}break;case I.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Oe(e,s)}break;case I.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=Oe(e,s)}break;case I.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case I.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,s));break;case I.Targets:this.readContiguousElements(e.slice(a,s));break;case I.TargetTypeValue:Oe(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case I.TagTrackUID:case I.TagEditionUID:case I.TagChapterUID:case I.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case I.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,s))}break;case I.TagName:this.currentSimpleTagName=fd(e,s);break;case I.TagString:{if(!this.currentSimpleTagName)break;let c=fd(e,s);this.processTagValue(this.currentSimpleTagName,c)}break;case I.TagBinary:{if(!this.currentSimpleTagName)break;let c=se(e,s);this.processTagValue(this.currentSimpleTagName,c)}break;case I.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,s));let c=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(c.raw??={},c.raw[this.currentAttachedFile.fileUid.toString()]=new Oo(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let l=this.currentAttachedFile.fileName,u="unknown";if(l){let f=l.toLowerCase();f.startsWith("cover.")?u="coverFront":f.startsWith("back.")&&(u="coverBack")}c.images??=[],c.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:u,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case I.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=SU(e,s)}break;case I.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=fd(e,s)}break;case I.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=ic(e,s)}break;case I.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=se(e,s)}break;case I.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=fd(e,s)}break;case I.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,s)),this.currentTrack.decodingInstructions.sort((c,l)=>l.order-c.order)}break;case I.ContentEncoding:this.currentDecodingInstruction={order:0,scope:ok.Block,data:null},this.readContiguousElements(e.slice(a,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case I.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Oe(e,s)}break;case I.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Oe(e,s)}break;case I.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Tp.Zlib,settings:null},this.readContiguousElements(e.slice(a,s))}break;case I.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=Oe(e,s)}break;case I.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=se(e,s)}break;case I.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+s,!0}decodeBlockData(e,r){x(e.decodingInstructions.length>0);let n=r;for(let i of e.decodingInstructions)switch(x(i.data),i.data.type){case"decompress":switch(i.data.algorithm){case Tp.HeaderStripping:if(i.data.settings&&i.data.settings.length>0){let s=i.data.settings,a=new Uint8Array(s.length+n.length);a.set(s,0),a.set(n,s.length),n=a}break;default:}break;default:}return n}processTagValue(e,r){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=r,typeof r=="string")switch(e.toLowerCase()){case"title":n.title??=r;break;case"description":n.description??=r;break;case"artist":n.artist??=r;break;case"album":n.album??=r;break;case"album_artist":n.albumArtist??=r;break;case"genre":n.genre??=r;break;case"comment":n.comment??=r;break;case"lyrics":n.lyrics??=r;break;case"date":{let i=new Date(r);Number.isNaN(i.getTime())||(n.date??=i)}break;case"track_number":case"part_number":{let i=r.split("/"),s=Number.parseInt(i[0],10),a=i[1]&&Number.parseInt(i[1],10);Number.isInteger(s)&&s>0&&(n.trackNumber??=s),a&&Number.isInteger(a)&&a>0&&(n.tracksTotal??=a)}break;case"disc_number":case"disc":{let i=r.split("/"),s=Number.parseInt(i[0],10),a=i[1]&&Number.parseInt(i[1],10);Number.isInteger(s)&&s>0&&(n.discNumber??=s),a&&Number.isInteger(a)&&a>0&&(n.discsTotal??=a)}break}}},ak=class{static{o(this,"MatroskaTrackBacking")}constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,n=this.internalTrack.inputTrack.type,i=0;for(let s of e.segments)for(let a of s.tracks)if(a.inputTrack.type===n&&i++,a===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,r=>r.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Do(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,r){let n=this.intoTimescale(e);return this.performClusterLookup(null,i=>{let s=i.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let a=ze(s.presentationTimestamps,n,u=>u.timestamp),c=a!==-1?s.presentationTimestamps[a].blockIndex:-1,l=a!==-1&&n<s.endTimestamp;return{blockIndex:c,correctBlockFound:l}},n,n,r)}async getNextPacket(e,r){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,i=>{if(i===n.cluster){let s=i.trackData.get(this.internalTrack.id);if(n.blockIndex+1<s.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(i.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async getKeyPacket(e,r){let n=this.intoTimescale(e);return this.performClusterLookup(null,i=>{let s=i.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let a=qf(s.presentationTimestamps,u=>s.blocks[u.blockIndex].isKeyFrame&&u.timestamp<=n),c=a!==-1?s.presentationTimestamps[a].blockIndex:-1,l=a!==-1&&n<s.endTimestamp;return{blockIndex:c,correctBlockFound:l}},n,n,r)}async getNextKeyPacket(e,r){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,i=>{if(i===n.cluster){let a=i.trackData.get(this.internalTrack.id).blocks.findIndex((c,l)=>c.isKeyFrame&&l>n.blockIndex);if(a!==-1)return{blockIndex:a,correctBlockFound:!0}}else{let s=i.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){let a=s.blocks.findIndex(c=>c.isKeyFrame);return x(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async fetchPacketInCluster(e,r,n){if(r===-1)return null;let s=e.trackData.get(this.internalTrack.id).blocks[r];x(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0);let a=n.metadataOnly?Wt:s.data,c=s.timestamp/this.internalTrack.segment.timestampFactor,l=s.duration/this.internalTrack.segment.timestampFactor,u={};s.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(u.alpha=n.metadataOnly?Wt:s.mainAdditional,u.alphaByteLength=s.mainAdditional.byteLength);let f=new je(a,s.isKeyFrame?"key":"delta",c,l,e.dataStartPos+r,s.data.byteLength,u);return this.packetToClusterLocation.set(f,{cluster:e,blockIndex:r}),f}async performClusterLookup(e,r,n,i,s){let{demuxer:a,segment:c}=this.internalTrack,l=null,u=null,f=-1;if(e){let{blockIndex:b,correctBlockFound:w}=r(e);if(w)return this.fetchPacketInCluster(e,b,s);b!==-1&&(u=e,f=b)}let d=ze(this.internalTrack.cuePoints,n,b=>b.time),h=d!==-1?this.internalTrack.cuePoints[d]:null,m=ze(this.internalTrack.clusterPositionCache,n,b=>b.startTimestamp),p=m!==-1?this.internalTrack.clusterPositionCache[m]:null,g=Math.max(h?.clusterPosition??0,p?.elementStartPos??0)||null,y;for(e?g===null||e.elementStartPos>=g?(y=e.elementEndPos,l=e):y=g:y=g??c.clusterSeekStartPos;c.elementEndPos===null||y<=c.elementEndPos-In;){if(l){let P=l.trackData.get(this.internalTrack.id);if(P&&P.startTimestamp>i)break}let b=a.reader.requestSliceRange(y,In,ts);if(b instanceof Promise&&(b=await b),!b)break;let w=y,k=rs(b);if(!k||!ld.includes(k.id)&&k.id!==I.Void){let P=await dI(a.reader,w,ld,Math.min(c.elementEndPos??1/0,w+vU));if(P){y=P;continue}else break}let T=k.id,v=k.size,S=b.filePos;if(T===I.Cluster){l=await a.readCluster(w,c),v=l.elementEndPos-S;let{blockIndex:P,correctBlockFound:N}=r(l);if(N)return this.fetchPacketInCluster(l,P,s);P!==-1&&(u=l,f=P)}v===void 0&&(x(T!==I.Cluster),v=(await nk(a.reader,S,Sp,c.elementEndPos)).pos-S);let M=S+v;if(c.elementEndPos===null){let P=a.reader.requestSliceRange(M,In,ts);if(P instanceof Promise&&(P=await P),!P)break;if(tk(P)===I.Segment){c.elementEndPos=M;break}}y=M}if(h&&(!u||u.elementStartPos<h.clusterPosition)){let b=this.internalTrack.cuePoints[d-1];x(!b||b.time<h.time);let w=b?.time??-1/0;return this.performClusterLookup(null,r,w,i,s)}return u?this.fetchPacketInCluster(u,f,s):null}},pI=class extends ak{static{o(this,"MatroskaVideoTrackBacking")}constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));let n={codec:Gf({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?Jf(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Zf(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Lx(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Bx(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})():null}},gI=class extends ak{static{o(this,"MatroskaAudioTrackBacking")}constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:Qf({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}});var vp,yI=he(()=>{Ka();qt();vp=o(async(t,e,r)=>{let n=e;for(;r===null||n<r;){let i=t.requestSlice(n,4);if(i instanceof Promise&&(i=await i),!i)break;let s=X(i),a=Ol(s,t.fileSize!==null?t.fileSize-n:null);if(a.header)return{header:a.header,startPos:n};n+=a.bytesAdvanced}return null},"readNextMp3FrameHeader")});var lk,bI,CU=he(()=>{Fo();Xi();lr();Ue();Qn();Ka();sc();yI();qt();lk=class extends wr{static{o(this,"Mp3Demuxer")}constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new Tn,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.tracks=[new Et(this.input,new bI(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let c=this.reader.requestSlice(this.lastLoadedPos,Xn);if(c instanceof Promise&&(c=await c),!c){this.lastSampleLoaded=!0;return}let l=ns(c);if(!l)break;this.lastLoadedPos=c.filePos+l.size}let e=await vp(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}let r=e.header;this.lastLoadedPos=e.startPos+r.totalSize-1;let n=Qa(r.mpegVersionId,r.channel),i=this.reader.requestSlice(e.startPos+n,4);if(i instanceof Promise&&(i=await i),i){let c=X(i);if(c===Ga||c===Xf)return}this.firstFrameHeader||(this.firstFrameHeader=r),r.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${r.sampleRate} Hz. Might be a bug, so please report this file.`);let s=r.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:r.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=r.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return x(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let r=0,n=!1;for(;;){let i=this.reader.requestSlice(r,Xn);if(i instanceof Promise&&(i=await i),!i)break;let s=ns(i);if(!s)break;n=!0;let a=this.reader.requestSlice(i.filePos,s.size);if(a instanceof Promise&&(a=await a),!a)break;dd(a,s,this.metadataTags),r=i.filePos+s.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=Ep){let i=this.reader.requestSlice(this.reader.fileSize-Ep,Ep);i instanceof Promise&&(i=await i),x(i),It(i,3)==="TAG"&&PU(i,this.metadataTags)}return this.metadataTags}finally{e()}}},bI=class{static{o(this,"Mp3AudioTrackBacking")}constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return x(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return Ft}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return x(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return x(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...jr}}async getDecoderConfig(){return x(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,r){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(r.metadataOnly)i=Wt;else{let s=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;i=se(s,n.dataSize)}return new je(i,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{let i=_o(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(i===-1)throw new Error("Packet was not created from this track.");let s=i+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,r)}finally{n()}}async getPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let i=ze(this.demuxer.loadedSamples,e,s=>s.timestamp);if(i===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,r);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,r);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}}});var Cp,Fee,IU,uk,fk,dk,hk=he(()=>{sn();Ue();Cp=1399285583,Fee=79764919,IU=new Uint32Array(256);for(let t=0;t<256;t++){let e=t<<24;for(let r=0;r<8;r++)e=e&2147483648?e<<1^Fee:e<<1;IU[t]=e>>>0&4294967295}uk=o(t=>{let e=ge(t),r=e.getUint32(22,!0);e.setUint32(22,0,!0);let n=0;for(let i=0;i<t.length;i++){let s=t[i];n=(n<<8^IU[n>>>24^s])>>>0}return e.setUint32(22,r,!0),n},"computeOggPageCrc"),fk=o((t,e,r)=>{let n=0,i=null;if(t.length>0)if(e.codec==="vorbis"){x(e.vorbisInfo);let s=e.vorbisInfo.modeBlockflags.length,c=(1<<vz(s-1))-1<<1,l=(t[0]&c)>>1;if(l>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let u=r,f=e.vorbisInfo.modeBlockflags[l];if(i=e.vorbisInfo.blocksizes[f],f===1){let d=(c|1)+1,h=t[0]&d?1:0;u=e.vorbisInfo.blocksizes[h]}n=u!==null?u+i>>2:0}else e.codec==="opus"&&(n=Zz(t).durationInSamples);return{durationInSamples:n,vorbisBlockSize:i}},"extractSampleMetadata"),dk=o(t=>{let e="audio/ogg";if(t.codecStrings){let r=[...new Set(t.codecStrings)];e+=`; codecs="${r.join(", ")}"`}return e},"buildOggMimeType")});var oc,$l,mk,hd,_U,wI=he(()=>{qt();hk();oc=27,$l=282,mk=$l+65025,hd=o(t=>{let e=t.filePos;if(Ul(t)!==Cp)return null;t.skip(1);let n=oe(t),i=DU(t),s=Ul(t),a=Ul(t),c=Ul(t),l=oe(t),u=new Uint8Array(l);for(let m=0;m<l;m++)u[m]=oe(t);let f=27+l,d=u.reduce((m,p)=>m+p,0),h=f+d;return{headerStartPos:e,totalSize:h,dataStartPos:e+f,dataSize:d,headerType:n,granulePosition:i,serialNumber:s,sequenceNumber:a,checksum:c,lacingValues:u}},"readPageHeader"),_U=o((t,e)=>{for(;t.filePos<e-3;){let r=Ul(t),n=r&255,i=r>>>8&255,s=r>>>16&255,a=r>>>24&255,c=79;if(!(n!==c&&i!==c&&s!==c&&a!==c)){if(t.skip(-4),r===Cp)return!0;t.skip(1)}}return!1},"findNextPageHeader")});var pk,xI,MU,OU,RU=he(()=>{Zt();sn();Fo();Xi();lr();Ue();Qn();qt();hk();wI();pk=class extends wr{static{o(this,"OggDemuxer")}constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,oc,$l);if(r instanceof Promise&&(r=await r),!r)break;let n=hd(r);if(!n||!!!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let r of this.bitstreams){let n=await this.readPacket(r.bosPage,0);n&&(n.data.byteLength>=7&&n.data[0]===1&&n.data[1]===118&&n.data[2]===111&&n.data[3]===114&&n.data[4]===98&&n.data[5]===105&&n.data[6]===115?await this.readVorbisMetadata(n,r):n.data.byteLength>=8&&n.data[0]===79&&n.data[1]===112&&n.data[2]===117&&n.data[3]===115&&n.data[4]===72&&n.data[5]===101&&n.data[6]===97&&n.data[7]===100&&await this.readOpusMetadata(n,r),r.codecInfo.codec!==null&&this.tracks.push(new Et(this.input,new xI(r,this))))}})()}async readVorbisMetadata(e,r){let n=await this.findNextPacketStart(e);if(!n)return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||(n=await this.findNextPacketStart(i),!n))return;let s=await this.readPacket(n.startPage,n.startSegmentIndex);if(!s||i.data[0]!==3||s.data[0]!==5)return;let a=[],c=o(d=>{for(;a.push(Math.min(255,d)),!(d<255);)d-=255},"addBytesToSegmentTable");c(e.data.length),c(i.data.length);let l=new Uint8Array(1+a.length+e.data.length+i.data.length+s.data.length);l[0]=2,l.set(a,1),l.set(e.data,1+a.length),l.set(i.data,1+a.length+e.data.length),l.set(s.data,1+a.length+e.data.length+i.data.length),r.codecInfo.codec="vorbis",r.description=l,r.lastMetadataPacket=s;let u=ge(e.data);r.numberOfChannels=u.getUint8(11),r.sampleRate=u.getUint32(12,!0);let f=u.getUint8(28);r.codecInfo.vorbisInfo={blocksizes:[1<<(f&15),1<<(f>>4)],modeBlockflags:zx(s.data).modeBlockflags},sp(i.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,r){let n=await this.findNextPacketStart(e);if(!n)return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i)return;r.codecInfo.codec="opus",r.description=e.data,r.lastMetadataPacket=i;let s=Ja(e.data);r.numberOfChannels=s.outputChannelCount,r.sampleRate=Qi,r.codecInfo.opusInfo={preSkip:s.preSkip},sp(i.data.subarray(8),this.metadataTags)}async readPacket(e,r){x(r<e.lacingValues.length);let n=0;for(let d=0;d<r;d++)n+=e.lacingValues[d];let i=e,s=n,a=r,c=[];e:for(;;){let d=this.reader.requestSlice(i.dataStartPos,i.dataSize);d instanceof Promise&&(d=await d),x(d);let h=se(d,i.dataSize);for(;;){if(a===i.lacingValues.length){c.push(h.subarray(n,s));break}let p=i.lacingValues[a];if(s+=p,p<255){c.push(h.subarray(n,s));break e}a++}let m=i.headerStartPos+i.totalSize;for(;;){let p=this.reader.requestSliceRange(m,oc,$l);if(p instanceof Promise&&(p=await p),!p)return null;let g=hd(p);if(!g)return null;if(i=g,i.serialNumber===e.serialNumber)break;m=i.headerStartPos+i.totalSize}n=0,s=0,a=0}let l=c.reduce((d,h)=>d+h.length,0);if(l===0)return null;let u=new Uint8Array(l),f=0;for(let d=0;d<c.length;d++){let h=c[d];u.set(h,f),f+=h.length}return{data:u,endPage:i,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let n=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let i=this.reader.requestSliceRange(n,oc,$l);if(i instanceof Promise&&(i=await i),!i)return null;let s=hd(i);if(!s)return null;if(s.serialNumber===e.endPage.serialNumber)return{startPage:s,startSegmentIndex:0};n=s.headerStartPos+s.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(r=>r.getCodecParameterString()));return dk({codecStrings:e.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...r)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},xI=class{static{o(this,"OggAudioTrackBacking")}constructor(e,r){this.bitstream=e,this.demuxer=r,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Tn,this.internalSampleRate=e.codecInfo.codec==="opus"?Qi:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumber(){let e=this.demuxer.tracks.findIndex(r=>r._backing.bitstream===this.bitstream);return x(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return x(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return Ft}getDisposition(){return{...jr}}async getFirstTimestamp(){return 0}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(x(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,r,n){if(!e)return null;let{durationInSamples:i,vorbisBlockSize:s}=fk(e.data,this.bitstream.codecInfo,r.vorbisLastBlocksize),a=new je(n.metadataOnly?Wt:e.data,"key",Math.max(0,r.timestampInSamples)/this.internalSampleRate,i/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:r.timestampInSamples,durationInSamples:i,vorbisLastBlockSize:r.vorbisLastBlocksize,vorbisBlockSize:s}),a}async getFirstPacket(e){x(this.bitstream.lastMetadataPacket);let r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let n=0;this.bitstream.codecInfo.codec==="opus"&&(x(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let i=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(i,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,r){let n=this.encodedPacketToMetadata.get(e);if(!n)throw new Error("Packet was not created from this track.");let i=await this.demuxer.findNextPacketStart(n.packet);if(!i)return null;let s=n.timestampInSamples+n.durationInSamples,a=await this.demuxer.readPacket(i.startPage,i.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:s,vorbisLastBlocksize:n.vorbisBlockSize},r)}async getPacket(e,r){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,r);let n=Do(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(r);if(n<0)return null;x(this.bitstream.lastMetadataPacket);let i=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!i)return null;let s=i.startPage,a=this.demuxer.reader.fileSize,c=[s];e:for(;s.headerStartPos+s.totalSize<a;){let w=s.headerStartPos,k=Math.floor((w+a)/2),T=k;for(;;){let v=Math.min(T+mk,a-oc),S=this.demuxer.reader.requestSlice(T,v-T);if(S instanceof Promise&&(S=await S),x(S),!_U(S,v)){a=k+oc;continue e}let P=this.demuxer.reader.requestSliceRange(S.filePos,oc,$l);P instanceof Promise&&(P=await P),x(P);let N=hd(P);x(N);let O=!1;if(N.serialNumber===this.bitstream.serialNumber)O=!0;else{let A=this.demuxer.reader.requestSlice(N.headerStartPos,N.totalSize);A instanceof Promise&&(A=await A),x(A);let R=se(A,N.totalSize);O=uk(R)===N.checksum}if(!O){T=N.headerStartPos+4;continue}if(O&&N.serialNumber!==this.bitstream.serialNumber){T=N.headerStartPos+N.totalSize;continue}if(N.granulePosition===-1){T=N.headerStartPos+N.totalSize;continue}this.granulePositionToTimestampInSamples(N.granulePosition)>n?a=N.headerStartPos:(s=N,c.push(N));continue e}}let l=i.startPage;for(let w of c){if(w.granulePosition===s.granulePosition)break;(!l||w.headerStartPos>l.headerStartPos)&&(l=w)}let u=l,f=[u];for(;!(u.serialNumber===this.bitstream.serialNumber&&u.granulePosition===s.granulePosition);){let w=u.headerStartPos+u.totalSize,k=this.demuxer.reader.requestSliceRange(w,oc,$l);k instanceof Promise&&(k=await k),x(k);let T=hd(k);x(T),u=T,u.serialNumber===this.bitstream.serialNumber&&f.push(u)}x(u.granulePosition!==-1);let d=null,h,m,p=u,g=0;if(u.headerStartPos===i.startPage.headerStartPos)h=this.granulePositionToTimestampInSamples(0),m=!0,d=0;else{h=0,m=!1;for(let T=u.lacingValues.length-1;T>=0;T--)if(u.lacingValues[T]<255){d=T+1;break}if(d===null)throw new Error("Invalid page with granule position: no packets end on this page.");g=d-1;let w={data:Wt,endPage:p,endSegmentIndex:g};if(await this.demuxer.findNextPacketStart(w)){let T=OU(f,u,d);x(T);let v=MU(f,T.page,T.segmentIndex);v&&(u=v.page,d=v.segmentIndex)}else for(;;){let T=OU(f,u,d);if(!T)break;let v=MU(f,T.page,T.segmentIndex);if(!v)break;if(u=v.page,d=v.segmentIndex,T.page.headerStartPos!==p.headerStartPos){p=T.page,g=T.segmentIndex;break}}}let y=null,b=null;for(;u!==null;){x(d!==null);let w=await this.demuxer.readPacket(u,d);if(!w)break;if(!(u.headerStartPos===i.startPage.headerStartPos&&d<i.startSegmentIndex)){let v=this.createEncodedPacketFromOggPacket(w,{timestampInSamples:h,vorbisLastBlocksize:b?.vorbisBlockSize??null},r);x(v);let S=this.encodedPacketToMetadata.get(v);if(x(S),!m&&w.endPage.headerStartPos===p.headerStartPos&&w.endSegmentIndex===g?(h=this.granulePositionToTimestampInSamples(u.granulePosition),m=!0,v=this.createEncodedPacketFromOggPacket(w,{timestampInSamples:h-S.durationInSamples,vorbisLastBlocksize:b?.vorbisBlockSize??null},r),x(v),S=this.encodedPacketToMetadata.get(v),x(S)):h+=S.durationInSamples,y=v,b=S,m&&(Math.max(h,0)>n||Math.max(S.timestampInSamples,0)===n))break}let T=await this.demuxer.findNextPacketStart(w);if(!T)break;u=T.startPage,d=T.startSegmentIndex}return y}async getPacketSequential(e,r){let n=await this.sequentialScanMutex.acquire();try{let i=Do(e*this.internalSampleRate);e=i/this.internalSampleRate;let s=ze(this.sequentialScanCache,i,l=>l.timestampInSamples),a;if(s!==-1){let l=this.sequentialScanCache[s];a=this.createEncodedPacketFromOggPacket(l.packet,{timestampInSamples:l.timestampInSamples,vorbisLastBlocksize:l.vorbisLastBlockSize},r)}else a=await this.getFirstPacket(r);let c=0;for(;a&&a.timestamp<e;){let l=await this.getNextPacket(a,r);if(!l||l.timestamp>e)break;if(a=l,c++,c===100){c=0;let u=this.encodedPacketToMetadata.get(a);x(u),this.sequentialScanCache.length>0&&x(Ze(this.sequentialScanCache).timestampInSamples<=u.timestampInSamples),this.sequentialScanCache.push(u)}}return a}finally{n()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}},MU=o((t,e,r)=>{let n=e,i=r;e:for(;;){for(i--,i;i>=0;i--)if(n.lacingValues[i]<255){i++;break e}if(x(i===-1),!(n.headerType&1)){i=0;break}let a=BP(t,c=>c.headerStartPos<n.headerStartPos);if(!a)return null;n=a,i=n.lacingValues.length}if(x(i!==-1),i===n.lacingValues.length){let s=t[t.indexOf(n)+1];x(s),n=s,i=0}return{page:n,segmentIndex:i}},"findPacketStartPosition"),OU=o((t,e,r)=>{if(r>0)return{page:e,segmentIndex:r-1};let n=BP(t,i=>i.headerStartPos<e.headerStartPos);return n?{page:n,segmentIndex:n.lacingValues.length-1}:null},"findPreviousPacketEndPosition")});var _n,gk,md,kI,TI=he(()=>{Fo();Xi();lr();Ue();Qn();qt();sc();(function(t){t[t.PCM=1]="PCM",t[t.IEEE_FLOAT=3]="IEEE_FLOAT",t[t.ALAW=6]="ALAW",t[t.MULAW=7]="MULAW",t[t.EXTENSIBLE=65534]="EXTENSIBLE"})(_n||(_n={}));gk=class extends wr{static{o(this,"WaveDemuxer")}constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.tracks=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),x(e);let r=It(e,4),n=r!=="RIFX",i=r==="RF64",s=Vo(e,n),a=i?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(It(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let l=0,u=null,f=e.filePos;for(;a===null||f<a;){let h=this.reader.requestSlice(f,8);if(h instanceof Promise&&(h=await h),!h)break;let m=It(h,4),p=Vo(h,n),g=h.filePos;if(i&&l===0&&m!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(m==="fmt ")await this.parseFmtChunk(g,p,n);else if(m==="data"){if(u??=p,this.dataStart=h.filePos,this.dataSize=Math.min(u,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(m==="ds64"){let y=this.reader.requestSlice(g,p);if(y instanceof Promise&&(y=await y),!y)break;let b=SI(y,n);u=SI(y,n),a=Math.min(b+8,this.reader.fileSize??1/0)}else m==="LIST"?await this.parseListChunk(g,p,n):(m==="ID3 "||m==="id3 ")&&await this.parseId3Chunk(g,p);f=g+p+(p&1),l++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.tracks.push(new Et(this.input,new kI(this)))})()}async parseFmtChunk(e,r,n){let i=this.reader.requestSlice(e,r);if(i instanceof Promise&&(i=await i),!i)return;let s=pd(i,n),a=pd(i,n),c=Vo(i,n);i.skip(4);let l=pd(i,n),u;if(r===14?u=8:u=pd(i,n),r>=18&&s!==357){let f=pd(i,n),d=r-18;if(Math.min(d,f)>=22&&s===_n.EXTENSIBLE){i.skip(6);let m=se(i,16);s=m[0]|m[1]<<8}}(s===_n.MULAW||s===_n.ALAW)&&(u=8),this.audioInfo={format:s,numberOfChannels:a,sampleRate:c,sampleSizeInBytes:Math.ceil(u/8),blockSizeInBytes:l}}async parseListChunk(e,r,n){let i=this.reader.requestSlice(e,r);if(i instanceof Promise&&(i=await i),!i)return;let s=It(i,4);if(s!=="INFO"&&s!=="INF0")return;let a=i.filePos;for(;a<=e+r-8;){i.filePos=a;let c=It(i,4),l=Vo(i,n),u=se(i,l),f=0;for(let h=0;h<u.length&&u[h]!==0;h++)f++;let d=String.fromCharCode(...u.subarray(0,f));switch(this.metadataTags.raw??={},this.metadataTags.raw[c]=d,c){case"INAM":case"TITL":this.metadataTags.title??=d;break;case"TIT3":this.metadataTags.description??=d;break;case"IART":this.metadataTags.artist??=d;break;case"IPRD":this.metadataTags.album??=d;break;case"IPRT":case"ITRK":case"TRCK":{let h=d.split("/"),m=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(m)&&m>0&&(this.metadataTags.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{let h=new Date(d);Number.isNaN(h.getTime())||(this.metadataTags.date??=h)}break;case"YEAR":{let h=Number.parseInt(d,10);Number.isInteger(h)&&h>0&&(this.metadataTags.date??=new Date(h,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=d;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=d;break}a+=8+l+(l&1)}}async parseId3Chunk(e,r){let n=this.reader.requestSlice(e,r);if(n instanceof Promise&&(n=await n),!n)return;let i=ns(n);if(i){let s=r-Xn;if(i.size=Math.min(i.size,s),i.size>0){let a=n.slice(e+Xn,i.size);dd(a,i,this.metadataTags)}}}getCodec(){if(x(this.audioInfo),this.audioInfo.format===_n.MULAW)return"ulaw";if(this.audioInfo.format===_n.ALAW)return"alaw";if(this.audioInfo.format===_n.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===_n.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return x(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},md=2048,kI=class{static{o(this,"WaveAudioTrackBacking")}constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return x(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(x(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return x(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return x(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return x(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Ft}getDisposition(){return{...jr}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,r){x(e>=0),x(this.demuxer.audioInfo);let n=e*md*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let i=Math.min(md*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let l=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,i);if(l instanceof Promise&&(l=await l),!l)return null}let s;if(r.metadataOnly)s=Wt;else{let l=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,i);l instanceof Promise&&(l=await l),x(l),s=se(l,i)}let a=e*md/this.demuxer.audioInfo.sampleRate,c=i/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new je(s,"key",a,c,e,i)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,r){x(this.demuxer.audioInfo);let n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/md,(this.demuxer.dataSize-1)/(md*this.demuxer.audioInfo.blockSizeInBytes)));if(n<0)return null;let i=await this.getPacketAtIndex(n,r);if(i)return i;if(n===0)return null;x(this.demuxer.reader.fileSize===null);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,r);for(;s;){let a=await this.getNextPacket(s,r);if(!a)break;s=a}return s}getNextPacket(e,r){x(this.demuxer.audioInfo);let n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/md);return this.getPacketAtIndex(n+1,r)}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}}});var Wo,Jn,Dn,gd=he(()=>{Ti();qt();Wo=7,Jn=9,Dn=o(t=>{let e=t.filePos,r=se(t,9),n=new Te(r);if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let a=n.readBits(1),c=n.readBits(2)+1,l=n.readBits(4);if(l===15)return null;n.skipBits(1);let u=n.readBits(3);if(u===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let f=n.readBits(13);n.skipBits(11);let d=n.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let h=null;return a===1?t.filePos-=2:h=n.readBits(16),{objectType:c,samplingFrequencyIndex:l,channelConfiguration:u,frameLength:f,numberOfAacFrames:d,crcCheck:h,startPos:e}},"readAdtsFrameHeader")});var Pp,yk,vI,EI=he(()=>{qs();Fo();sc();Xi();lr();Ue();Qn();qt();gd();Pp=1024,yk=class extends wr{static{o(this,"AdtsDemuxer")}constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new Tn,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();x(this.firstFrameHeader),this.tracks=[new Et(this.input,new vI(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,Xn);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let c=ns(a);if(!c)break;this.lastLoadedPos=a.filePos+c.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,Wo,Jn);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let r=Dn(e);if(!r){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&r.startPos+r.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=r);let n=vi[r.samplingFrequencyIndex];x(n!==void 0);let i=Pp/n,s={timestamp:this.nextTimestampInSamples/n,duration:i,dataStart:r.startPos,dataSize:r.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=Pp,this.lastLoadedPos=r.startPos+r.frameLength}async getMimeType(){return"audio/aac"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return x(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let r=0;for(;;){let n=this.reader.requestSlice(r,Xn);if(n instanceof Promise&&(n=await n),!n)break;let i=ns(n);if(!i)break;let s=this.reader.requestSlice(n.filePos,i.size);if(s instanceof Promise&&(s=await s),!s)break;dd(s,i,this.metadataTags),r=n.filePos+i.size}return this.metadataTags}finally{e()}}},vI=class{static{o(this,"AdtsAudioTrackBacking")}constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/Pp}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return Ft}getCodec(){return"aac"}getInternalCodecId(){return x(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){x(this.demuxer.firstFrameHeader);let e=Ws[this.demuxer.firstFrameHeader.channelConfiguration];return x(e!==void 0),e}getSampleRate(){x(this.demuxer.firstFrameHeader);let e=vi[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return x(e!==void 0),e}getDisposition(){return{...jr}}async getDecoderConfig(){return x(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,r){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(r.metadataOnly)i=Wt;else{let s=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;i=se(s,n.dataSize)}return new je(i,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{let i=_o(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(i===-1)throw new Error("Packet was not created from this track.");let s=i+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,r)}finally{n()}}async getPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let i=ze(this.demuxer.loadedSamples,e,s=>s.timestamp);if(i===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,r);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,r);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}}});var bk,NU,wk,xk,AU,FU,CI=he(()=>{Ti();Ue();qt();bk=o(t=>t===0?null:t===1?192:t>=2&&t<=5?144*2**t:t===6?"uncommon-u8":t===7?"uncommon-u16":t>=8&&t<=15?2**t:null,"getBlockSizeOrUncommon"),NU=o((t,e)=>{switch(t){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},"getSampleRateOrUncommon"),wk=o(t=>{let e=0,r=new Te(se(t,1));for(;r.readBits(1)===1;)e++;if(e===0)return r.readBits(7);let n=[],i=e-1,s=new Te(se(t,i)),a=8-e-1;for(let l=0;l<a;l++)n.unshift(r.readBits(1));for(let l=0;l<i;l++)for(let u=0;u<8;u++){let f=s.readBits(1);u<2||n.unshift(f)}return n.reduce((l,u,f)=>l|u<<f,0)},"readCodedNumber"),xk=o((t,e)=>{if(e==="uncommon-u16")return jt(t)+1;if(e==="uncommon-u8")return oe(t)+1;if(typeof e=="number")return e;kt(e),x(!1)},"readBlockSize"),AU=o((t,e)=>e==="uncommon-u16"?jt(t):e==="uncommon-u16-10"?jt(t)*10:e==="uncommon-u8"?oe(t):typeof e=="number"?e:null,"readSampleRate"),FU=o(t=>{let r=0;for(let n of t){r^=n;for(let i=0;i<8;i++)(r&128)!==0?r=r<<1^7:r<<=1,r&=255}return r},"calculateCrc8")});var kk,PI,LU=he(()=>{sn();Fo();Xi();Ue();Qn();qt();lr();CI();Ti();kk=class extends wr{static{o(this,"FlacDemuxer")}constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new Tn,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),x(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),x(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;this.reader.fileSize===null||e<this.reader.fileSize;){let r=this.reader.requestSlice(e,4);if(r instanceof Promise&&(r=await r),e+=4,r===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);x(r);let n=oe(r),i=nc(r),s=(n&128)!==0;switch(n&127){case Ei.STREAMINFO:{let c=this.reader.requestSlice(e,i);if(c instanceof Promise&&(c=await c),x(c),c===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let l=se(c,34),u=new Te(l),f=u.readBits(16),d=u.readBits(16),h=u.readBits(24),m=u.readBits(24),p=u.readBits(20),g=u.readBits(3)+1;u.readBits(5);let y=u.readBits(36);u.skipBits(128);let b=new Uint8Array(42);b.set(new Uint8Array([102,76,97,67]),0),b.set(new Uint8Array([128,0,0,34]),4),b.set(l,8),this.audioInfo={numberOfChannels:g,sampleRate:p,totalSamples:y,minimumBlockSize:f,maximumBlockSize:d,minimumFrameSize:h,maximumFrameSize:m,description:b},this.track=new Et(this.input,new PI(this));break}case Ei.VORBIS_COMMENT:{let c=this.reader.requestSlice(e,i);c instanceof Promise&&(c=await c),x(c),sp(se(c,i),this.metadataTags);break}case Ei.PICTURE:{let c=this.reader.requestSlice(e,i);c instanceof Promise&&(c=await c),x(c);let l=X(c),u=X(c),f=br.decode(se(c,u)),d=X(c),h=br.decode(se(c,d));c.skip(16);let m=X(c),p=se(c,m);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:f,kind:l===3?"coverFront":l===4?"coverBack":"unknown",description:h});break}default:break}if(e+=i,s){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:r}){x(this.audioInfo);let n=6,i=16,s=10,a=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+i+2,c=this.audioInfo.minimumFrameSize||s,u=(this.audioInfo.maximumFrameSize||a)+i,f=await this.reader.requestSliceRange(e,i,u);if(!f)return null;let d=this.readFlacFrameHeader({slice:f,isFirstPacket:r});if(!d)return null;for(f.filePos=e+c;;){if(f.filePos>f.end-n)return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:f.end-e,isLastFrame:!0};if(oe(f)===255){let m=f.filePos,p=oe(f),g=this.blockingBit===1?249:248;if(p!==g){f.filePos=m;continue}f.skip(-2);let y=f.filePos-e,b=this.readFlacFrameHeader({slice:f,isFirstPacket:!1});if(!b){f.filePos=m;continue}if(this.blockingBit===0){if(b.num-d.num!==1){f.filePos=m;continue}}else if(b.num-d.num!==d.blockSize){f.filePos=m;continue}return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:y,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:r}){let n=e.filePos,i=se(e,4),s=new Te(i);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){x(r);let y=s.readBits(1);this.blockingBit=y}else if(this.blockingBit===1){if(x(!r),s.readBits(1)!==1)return null}else if(this.blockingBit===0){if(x(!r),s.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let c=bk(s.readBits(4));if(!c)return null;x(this.audioInfo);let l=NU(s.readBits(4),this.audioInfo.sampleRate);if(!l||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;let f=wk(e),d=xk(e,c),h=AU(e,l);if(h===null||h!==this.audioInfo.sampleRate)return null;let m=e.filePos-n,p=oe(e);e.skip(-m),e.skip(-1);let g=FU(se(e,m));return p!==g?null:{num:f,blockSize:d,sampleRate:h}}async advanceReader(){await this.readMetadata(),x(this.lastLoadedPos!==null),x(this.audioInfo);let e=this.lastLoadedPos,r=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!r){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:r.blockSize,byteOffset:e,byteSize:r.size};if(this.lastLoadedPos=this.lastLoadedPos+r.size,this.loadedSamples.push(s),r.isLastFrame){this.lastSampleLoaded=!0;return}}},PI=class{static{o(this,"FlacAudioTrackBacking")}constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return x(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return x(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Ft}getTimeResolution(){return x(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...jr}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return x(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,r){if(x(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");let n=await this.demuxer.readingMutex.acquire();try{for(;;){let i=ze(this.demuxer.loadedSamples,e,l=>l.blockOffset/this.demuxer.audioInfo.sampleRate);if(i===-1){await this.demuxer.advanceReader();continue}let s=this.demuxer.loadedSamples[i],a=s.blockOffset/this.demuxer.audioInfo.sampleRate,c=s.blockSize/this.demuxer.audioInfo.sampleRate;if(a+c<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,r);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(i,r)}}finally{n()}}async getNextPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{let i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,r)}finally{n()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}async getPacketAtIndex(e,r){let n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(r.metadataOnly)i=Wt;else{let c=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(c instanceof Promise&&(c=await c),!c)return null;i=se(c,n.byteSize)}x(this.demuxer.audioInfo);let s=n.blockOffset/this.demuxer.audioInfo.sampleRate,a=n.blockSize/this.demuxer.audioInfo.sampleRate;return new je(i,"key",s,a,e,n.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}});var Zn,kr,Sk,Tk=he(()=>{Zn=9e4,kr=188,Sk=o(t=>{let e="video/MP2T",r=[...new Set(t.filter(Boolean))];return r.length>0&&(e+=`; codecs="${r.join(", ")}"`),e},"buildMpegTsMimeType")});var Ek,Hl,Ip,vk,II,_I,DI,Lee,_p,Dp,BU=he(()=>{EI();gd();qs();Zt();sn();Fo();Xi();lr();Ue();Ka();Qn();qt();Tk();Ox();Ti();Ek=class extends wr{static{o(this,"MpegTsDemuxer")}constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.tracks=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=205,r=this.reader.requestSlice(0,e);r instanceof Promise&&(r=await r),x(r);let n=se(r,e);if(n[0]===71&&n[188]===71)this.packetOffset=0,this.packetStride=188;else if(n[0]===71&&n[204]===71)this.packetOffset=0,this.packetStride=204;else if(n[4]===71&&n[196]===71)this.packetOffset=4,this.packetStride=192;else throw new Error("Unreachable.");let i=256;this.minReferencePointByteDistance=i*this.packetStride;let s=this.packetOffset,a=null,c=!1,l=!1;for(;;){let u=await this.readPacketHeader(s);if(!u)break;if(u.payloadUnitStartIndicator===0){s+=this.packetStride;continue}let f=await this.readSection(s,!0,!l);if(!f)break;let d=3,h=32,m=!1;if(!l&&f.pid!==0&&!(f.payload[0]===0&&f.payload[1]===0&&f.payload[2]===1)){let y=new Te(f.payload),b=y.readAlignedByte();y.skipBits(8*b),m=y.readBits(8)===2}if(f.pid===0&&!c){let g=new Te(f.payload),y=g.readAlignedByte();g.skipBits(8*y),g.skipBits(14);let b=g.readBits(10);for(g.skipBits(40);8*(b+d)-g.pos>h;){let w=g.readBits(16);g.skipBits(3);let k=g.readBits(13);if(w!==0){if(a!==null)throw new Error("Only files with a single program are supported.");a=k}}if(a===null)throw new Error("Program Association Table must link to a Program Map Table.");c=!0}else if((f.pid===a||m)&&!l){let g=new Te(f.payload),y=g.readAlignedByte();g.skipBits(8*y),g.skipBits(12);let b=g.readBits(12);g.skipBits(43);let w=g.readBits(13);g.skipBits(6);let k=g.readBits(10);for(g.skipBits(8*k);8*(b+d)-g.pos>h;){let T=g.readBits(8);g.skipBits(3);let v=g.readBits(13);g.skipBits(6);let S=g.readBits(10),M=g.pos+8*S,P=!1,N=!1;for(;g.pos<M;){let Y=g.readBits(8),A=g.readBits(8);Y===106?P=!0:(Y===122||Y===204)&&(N=!0),g.skipBits(8*A)}let O=null;switch(T){case 3:case 4:case 15:O={type:"audio",codec:T===15?"aac":"mp3",aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;case 27:case 36:O={type:"video",codec:T===27?"avc":"hevc",avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 129:O={type:"audio",codec:"ac3",aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;case 135:O={type:"audio",codec:"eac3",aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;case 6:N?O={type:"audio",codec:"eac3",aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:P&&(O={type:"audio",codec:"ac3",aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:console.warn(`Unsupported stream_type 0x${T.toString(16)}; ignoring stream.`)}O&&this.elementaryStreams.push({demuxer:this,pid:v,streamType:T,initialized:!1,firstSection:null,info:O,referencePesPackets:[]})}l=!0}else{let g=this.elementaryStreams.find(y=>y.pid===f.pid);if(g&&!g.initialized){let y=Ip(f);if(!y)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${g.pid}`);if(g.firstSection=f,g.info.type==="video")if(g.info.codec==="avc"){if(g.info.avcCodecInfo=Jf(y.data),!g.info.avcCodecInfo)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from first packet.");let b=g.info.avcCodecInfo.sequenceParameterSets[0];x(b);let w=ip(b);g.info.width=w.displayWidth,g.info.height=w.displayHeight,w.pixelAspectRatio.num>w.pixelAspectRatio.den?(g.info.squarePixelWidth=Math.round(g.info.width*w.pixelAspectRatio.num/w.pixelAspectRatio.den),g.info.squarePixelHeight=g.info.height):(g.info.squarePixelWidth=g.info.width,g.info.squarePixelHeight=Math.round(g.info.height*w.pixelAspectRatio.den/w.pixelAspectRatio.num)),g.info.colorSpace={primaries:Cl[w.colourPrimaries],transfer:Pl[w.transferCharacteristics],matrix:Il[w.matrixCoefficients],fullRange:!!w.fullRangeFlag},g.info.reorderSize=w.maxDecFrameBuffering,g.initialized=!0}else if(g.info.codec==="hevc"){if(g.info.hevcCodecInfo=Zf(y.data),!g.info.hevcCodecInfo)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");let w=g.info.hevcCodecInfo.arrays.find(T=>T.nalUnitType===vt.SPS_NUT).nalUnits[0];x(w);let k=GP(w);g.info.width=k.displayWidth,g.info.height=k.displayHeight,k.pixelAspectRatio.num>k.pixelAspectRatio.den?(g.info.squarePixelWidth=Math.round(g.info.width*k.pixelAspectRatio.num/k.pixelAspectRatio.den),g.info.squarePixelHeight=g.info.height):(g.info.squarePixelWidth=g.info.width,g.info.squarePixelHeight=Math.round(g.info.height*k.pixelAspectRatio.den/k.pixelAspectRatio.num)),g.info.colorSpace={primaries:Cl[k.colourPrimaries],transfer:Pl[k.transferCharacteristics],matrix:Il[k.matrixCoefficients],fullRange:!!k.fullRangeFlag},g.info.reorderSize=k.maxDecFrameBuffering,g.initialized=!0}else throw new Error("Unhandled.");else if(g.info.codec==="aac"){let b=xr.tempFromBytes(y.data),w=Dn(b);if(!w)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");g.info.aacCodecInfo={isMpeg2:!1,objectType:w.objectType},g.info.numberOfChannels=Ws[w.channelConfiguration],g.info.sampleRate=vi[w.samplingFrequencyIndex],g.initialized=!0}else if(g.info.codec==="mp3"){let b=X(xr.tempFromBytes(y.data)),w=Ol(b,y.data.byteLength);if(!w.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");g.info.numberOfChannels=w.header.channel===3?1:2,g.info.sampleRate=w.header.sampleRate,g.initialized=!0}else if(g.info.codec==="ac3"){let b=$x(y.data);if(!b)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(b.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");g.info.numberOfChannels=ap[b.acmod]+b.lfeon,g.info.sampleRate=Rl[b.fscod],g.initialized=!0}else if(g.info.codec==="eac3"){let b=Hx(y.data);if(!b)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");let w=Vx(b);if(w===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");g.info.numberOfChannels=Wx(b),g.info.sampleRate=w,g.initialized=!0}else throw new Error("Unhandled.")}}if(l&&this.elementaryStreams.every(g=>g.initialized))break;s+=this.packetStride}if(!l)throw c?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(let u of this.elementaryStreams)u.info.type==="video"?this.tracks.push(new Pn(this.input,new II(u))):this.tracks.push(new Et(this.input,new _I(u)))})()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return{}}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...r)}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.getCodecParameterString()));return Sk(r)}async readSection(e,r,n=!1){let i=e,s=e,a=[],c=0,l=null,u=!0,f=0;for(;;){let h=await this.readPacket(s);if(s+=this.packetStride,!h)break;if(l){if(h.pid!==l.pid){if(n)break;continue}if(h.payloadUnitStartIndicator===1)break}else{if(h.payloadUnitStartIndicator===0)break;l=h}let m=!!(h.adaptationFieldControl&2),p=!!(h.adaptationFieldControl&1),g=0;if(m&&(g=1+h.body[0],h===l&&g>1&&(f=h.body[1]>>6&1)),p&&(g===0?(a.push(h.body),c+=h.body.byteLength):(a.push(h.body.subarray(g)),c+=h.body.byteLength-g)),i=s,!r&&c>=64){u=!1;break}if(_o(this.sectionEndPositions,i,b=>b)!==-1){u=!1;break}}if(u){let h=ze(this.sectionEndPositions,i,m=>m);this.sectionEndPositions.splice(h+1,0,i)}if(!l)return null;let d;if(a.length===1)d=a[0];else{let h=a.reduce((p,g)=>p+g.length,0);d=new Uint8Array(h);let m=0;for(let p of a)d.set(p,m),m+=p.length}return{startPos:e,endPos:r?i:null,pid:l.pid,payload:d,randomAccessIndicator:f}}async readPacketHeader(e){let r=this.reader.requestSlice(e,4);if(r instanceof Promise&&(r=await r),!r)return null;if(oe(r)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let i=jt(r),s=i>>15,a=i>>14&1,c=i>>13&1,l=i&8191,u=oe(r),f=u>>6,d=u>>4&3,h=u&15;return{payloadUnitStartIndicator:a,pid:l,adaptationFieldControl:d}}async readPacket(e){let r=this.reader.requestSlice(e,188);if(r instanceof Promise&&(r=await r),!r)return null;let n=se(r,188);if(n[0]!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let s=(n[1]<<8)+n[2],a=s>>15,c=s>>14&1,l=s>>13&1,u=s&8191,f=n[3],d=f>>6,h=f>>4&3,m=f&15;return{payloadUnitStartIndicator:c,pid:u,adaptationFieldControl:h,body:n.subarray(4)}}},Hl=o(t=>{if(t.payload.byteLength<3)return null;let e=new Te(t.payload);if(e.readBits(24)!==1)return null;let n=e.readBits(8);if(e.skipBits(16),n===188||n===190||n===191||n===240||n===241||n===255||n===242||n===248)return null;e.skipBits(8);let i=e.readBits(2);e.skipBits(14);let s=0;if(i===2||i===3)e.skipBits(4),s+=e.readBits(3)*(1<<30),e.skipBits(1),s+=e.readBits(15)*32768,e.skipBits(1),s+=e.readBits(15);else throw new Error("PES packets without PTS are not currently supported. If you think this file should be supported, please report it.");return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:s,randomAccessIndicator:t.randomAccessIndicator}},"readPesPacketHeader"),Ip=o(t=>{x(t.endPos!==null);let e=Hl(t);if(!e)return null;let r=new Te(t.payload);r.skipBits(32);let n=r.readBits(16),i=6;r.skipBits(16);let s=r.readBits(8),a=r.pos+8*s;r.pos=a;let c=a/8;x(Number.isInteger(c));let l=t.payload.subarray(c,n>0?i+n:t.payload.byteLength);return{...e,data:l}},"readPesPacket"),vk=class t{static{o(this,"MpegTsTrackBacking")}constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let e=this.elementaryStream.demuxer,r=this.elementaryStream.info.type,n=0;for(let i of e.tracks)if(i.type===r&&n++,x(i._backing instanceof t),i._backing.elementaryStream===this.elementaryStream)break;return n}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return Ft}getDisposition(){return jr}getTimeResolution(){return 9e4}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}createEncodedPacket(e,r,n){let i;return this.allPacketsAreKeyPackets()?i="key":i=e.randomAccessIndicator===1?"key":"delta",new je(n.metadataOnly?Wt:e.data,i,e.pts/9e4,Math.max(r/9e4,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let r=this.elementaryStream.firstSection;x(r);let n=Ip(r);x(n);let i=new _p(this.elementaryStream,n),s=new Dp(this,i),a=await s.readNext();if(!a)return null;let c=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(c,s),this.packetSectionStarts.set(c,a.packet.sectionStartPos),c}async getNextPacket(e,r){let n=this.packetBuffers.get(e);if(n){let f=await n.readNext();if(!f)return null;this.packetBuffers.delete(e);let d=this.createEncodedPacket(f.packet,f.duration,r);return this.packetBuffers.set(d,n),this.packetSectionStarts.set(d,f.packet.sectionStartPos),d}let i=this.packetSectionStarts.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");let a=await this.elementaryStream.demuxer.readSection(i,!0);x(a);let c=Ip(a);x(c);let l=new _p(this.elementaryStream,c);n=new Dp(this,l);let u=e.sequenceNumber;for(;;){let f=await n.readNext();if(!f)return null;if(f.packet.sequenceNumber>u){let d=this.createEncodedPacket(f.packet,f.duration,r);return this.packetBuffers.set(d,n),this.packetSectionStarts.set(d,f.packet.sectionStartPos),d}}}async getNextKeyPacket(e,r){let n=e;for(;;){if(n=await this.getNextPacket(n,r),!n)return null;if(n.type==="key")return n}}getPacket(e,r){return this.doPacketLookup(e,!1,r)}getKeyPacket(e,r){return this.doPacketLookup(e,!0,r)}async doPacketLookup(e,r,n){let i=Do(e*9e4),s=this.elementaryStream.demuxer,{reader:a,seekChunkSize:c}=s,l=this.elementaryStream.pid,u=o(async(k,T)=>{let v=k;for(;v<T;){let S=await s.readPacketHeader(v);if(!S)return null;if(S.pid===l&&S.payloadUnitStartIndicator===1){let M=await s.readSection(v,!1);if(!M)return null;let P=Hl(M);if(P)return P}v+=s.packetStride}return null},"findFirstPesPacketHeaderInChunk"),f=this.elementaryStream.firstSection;x(f);let d=Hl(f);if(x(d),i<d.pts)return null;let h,m=this.elementaryStream.referencePesPackets,p=ze(m,i,k=>k.pts),g=p!==-1?m[p]:null;if(g&&i-g.pts<9e4/2)h=g.sectionStartPos;else{let k=0;if(a.fileSize!==null){let T=Math.ceil(a.fileSize/c);if(T>1){let v=0,S=T-1;for(k=v;v<=S;){let M=Math.floor((v+S)/2),P=Sx(M*c,s.packetStride)+d.sectionStartPos,N=P+c,O=await u(P,N);if(!O){S=M-1;continue}O.pts<=i?(k=M,v=M+1):S=M-1}}}h=Sx(k*c,s.packetStride)+d.sectionStartPos}let y=await u(h,a.fileSize??1/0);y||(y=d);let b=this.getReorderSize(),w=o(async(k,T)=>{let v=await s.readSection(k,!0);x(v);let S=Ip(v);x(S);let M=new _p(this.elementaryStream,S),P=new Dp(this,M);for(;!((Ze(P.presentationOrderPackets)?.pts??-1/0)>=i||!await P.readNextPacket()););let N=qf(P.presentationOrderPackets,T);if(N===-1)return null;let O=P.presentationOrderPackets[N],Y=N===0?0:O.pts-P.presentationOrderPackets[N-1].pts;for(;P.decodeOrderPackets[0]!==O;)P.decodeOrderPackets.shift();P.lastDuration=Y;let A=await P.readNext();x(A);let R=this.createEncodedPacket(A.packet,A.duration,n);return this.packetBuffers.set(R,P),this.packetSectionStarts.set(R,A.packet.sectionStartPos),R},"retrieveEncodedPacket");if(!r||this.allPacketsAreKeyPackets()){e:for(;;){let k=y.sectionStartPos+s.packetStride;for(;;){let T=await s.readPacketHeader(k);if(!T)break e;if(T.pid===l&&T.payloadUnitStartIndicator===1){let v=await s.readSection(k,!1);if(v){let S=Hl(v);if(S){if(S.pts>i)break e;y=S,DI(this.elementaryStream,S);break}}}k+=s.packetStride}}e:for(let k=0;k<b;k++){let T=y.sectionStartPos-s.packetStride;for(;T>=s.packetOffset;){let v=await s.readPacketHeader(T);if(!v)break e;if(v.pid===l&&v.payloadUnitStartIndicator===1){let S=await s.readSection(T,!1);if(S){let M=Hl(S);if(M){y=M;break}}}T-=s.packetStride}}return w(y.sectionStartPos,k=>k.pts<=i)}else{let k=h,T=null;for(;;){let v=null,S=k<=d.sectionStartPos,M;S?(M=d,v=d):M=await u(k,a.fileSize??1/0);let P=!1,N=0;e:for(;M&&!(T!==null&&M.sectionStartPos>=T||(M.randomAccessIndicator===1&&M.pts<=i&&(v=M),M.pts>i&&(P=!0),P&&(N++,N>=b)));){let Y=M.sectionStartPos+s.packetStride;for(;;){let A=await s.readPacketHeader(Y);if(!A)break e;if(A.pid===l&&A.payloadUnitStartIndicator===1){let R=await s.readSection(Y,!1);if(R&&(M=Hl(R),M)){DI(this.elementaryStream,M);break}}Y+=s.packetStride}}if(v){let O=v;if(N===0)e:for(let A=0;A<b-1;A++){let R=O.sectionStartPos-s.packetStride;for(;R>=s.packetOffset;){let F=await s.readPacketHeader(R);if(!F)break e;if(F.pid===l&&F.payloadUnitStartIndicator===1){let $=await s.readSection(R,!1);if($){let W=Hl($);if(W){O=W;break}}}R-=s.packetStride}}let Y=await w(O.sectionStartPos,A=>A.pts<=i&&A.randomAccessIndicator===1);return x(Y),Y}x(!S),T=k,k=Math.max(Sx(k-d.sectionStartPos-c,s.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}},II=class extends vk{static{o(this,"MpegTsVideoTrackBacking")}constructor(e){super(e),this.elementaryStream=e,this.decoderConfig={codec:Gf({width:this.elementaryStream.info.width,height:this.elementaryStream.info.height,codec:this.elementaryStream.info.codec,codecDescription:null,colorSpace:this.elementaryStream.info.colorSpace,avcType:1,avcCodecInfo:this.elementaryStream.info.avcCodecInfo,hevcCodecInfo:this.elementaryStream.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:this.elementaryStream.info.width,codedHeight:this.elementaryStream.info.height,colorSpace:this.elementaryStream.info.colorSpace},(this.elementaryStream.info.width!==this.elementaryStream.info.squarePixelWidth||this.elementaryStream.info.height!==this.elementaryStream.info.squarePixelHeight)&&(this.decoderConfig.displayAspectWidth=this.elementaryStream.info.squarePixelWidth,this.decoderConfig.displayAspectHeight=this.elementaryStream.info.squarePixelHeight)}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return this.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},_I=class extends vk{static{o(this,"MpegTsAudioTrackBacking")}constructor(e){super(e),this.elementaryStream=e}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return{codec:Qf({codec:this.elementaryStream.info.codec,codecDescription:null,aacCodecInfo:this.elementaryStream.info.aacCodecInfo}),numberOfChannels:this.elementaryStream.info.numberOfChannels,sampleRate:this.elementaryStream.info.sampleRate}}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 1}},DI=o((t,e)=>{let r=t.referencePesPackets,n=ze(r,e.sectionStartPos,i=>i.sectionStartPos);if(n>=0){let i=r[n];if(e.pts<=i.pts)return!1;let s=t.demuxer.minReferencePointByteDistance;if(e.sectionStartPos-i.sectionStartPos<s)return!1;if(n<r.length-1){let a=r[n+1];if(a.pts<e.pts||a.sectionStartPos-e.sectionStartPos<s)return!1}}return r.splice(n+1,0,e),!0},"maybeInsertReferencePacket"),Lee=o(async t=>{x(!t.suppliedPacket);let e=t.elementaryStream;if(e.info.type==="video"){let r=e.info.codec,n=1024;if(r!=="avc"&&r!=="hevc")throw new Error("Unhandled.");let i=null;for(;;){let s=t.ensureBuffered(n);if(s instanceof Promise&&(s=await s),s===0)break;let a=t.currentPos,c=t.readBytes(s),l=c.byteLength,u=0;for(;u<l;){let f=c.indexOf(0,u);if(f===-1||f>=l)break;u=f;let d=a+u;if(u+4>=l){t.seekTo(d);break}let h=c[u+1],m=c[u+2],p=c[u+3],g=0,y=null;if(h===0&&m===0&&p===1?(g=4,y=c[u+4]):h===0&&m===1&&(g=3,y=p),g===0){u++;continue}let b=d;if(i===null){i=b,u+=g;continue}if(y!==null){let w=r==="avc"?Ao(y):Gs(y);if(r==="avc"?w===Cn.AUD:w===vt.AUD_NUT){let T=b-i;return t.seekTo(i),t.supplyPacket(T,0)}}u+=g}if(s<n)break}if(i!==null){let s=t.endPos-i;return t.seekTo(i),t.supplyPacket(s,0)}}else{let r=e.info.codec,n=128;for(;;){let i=t.ensureBuffered(n);i instanceof Promise&&(i=await i);let s=t.currentPos;for(;t.currentPos-s<i;){let a=t.readU8();if(r==="aac"){if(a!==255)continue;t.skip(-1);let c=t.currentPos,l=t.ensureBuffered(Jn);if(l instanceof Promise&&(l=await l),l<Jn)return;let u=t.readBytes(Jn),f=Dn(xr.tempFromBytes(u));if(f){t.seekTo(c);let d=t.ensureBuffered(f.frameLength);return d instanceof Promise&&(d=await d),t.supplyPacket(d,Math.round(Pp*9e4/e.info.sampleRate))}else t.seekTo(c+1)}else if(r==="mp3"){if(a!==255)continue;t.skip(-1);let c=t.currentPos,l=t.ensureBuffered(4);if(l instanceof Promise&&(l=await l),l<4)return;let u=t.readBytes(4),f=ge(u).getUint32(0),d=Ol(f,null);if(d.header){t.seekTo(c);let h=t.ensureBuffered(d.header.totalSize);h instanceof Promise&&(h=await h);let m=d.header.audioSamplesInFrame*9e4/e.info.sampleRate;return t.supplyPacket(h,Math.round(m))}else t.seekTo(c+1)}else if(r==="ac3"){if(a!==11)continue;t.skip(-1);let c=t.currentPos,l=t.ensureBuffered(5);if(l instanceof Promise&&(l=await l),l<5)return;let u=t.readBytes(5);if(u[0]!==11||u[1]!==119){t.seekTo(c+1);continue}let f=u[4]>>6,d=u[4]&63;if(f===3||d>37){t.seekTo(c+1);continue}let h=eU[3*d+f];x(h!==void 0),t.seekTo(c),l=t.ensureBuffered(h),l instanceof Promise&&(l=await l);let m=Math.round(tU*9e4/e.info.sampleRate);return t.supplyPacket(l,m)}else if(r==="eac3"){if(a!==11)continue;t.skip(-1);let c=t.currentPos,l=t.ensureBuffered(5);if(l instanceof Promise&&(l=await l),l<5)return;let u=t.readBytes(5);if(u[0]!==11||u[1]!==119){t.seekTo(c+1);continue}let d=(((u[2]&7)<<8|u[3])+1)*2,m=u[4]>>6===3?3:u[4]>>4&3,p=QP[m];t.seekTo(c),l=t.ensureBuffered(d),l instanceof Promise&&(l=await l);let g=p*256,y=Math.round(g*9e4/e.info.sampleRate);return t.supplyPacket(l,y)}else throw new Error("Unhandled.")}if(i<n)break}}},"markNextPacket"),_p=class t{static{o(this,"PacketReadingContext")}constructor(e,r){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.nextPts=0,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=r}clone(){let e=new t(this.elementaryStream,this.startingPesPacket);return e.currentPos=this.currentPos,e.pesPackets=[...this.pesPackets],e.currentPesPacketIndex=this.currentPesPacketIndex,e.currentPesPacketPos=this.currentPesPacketPos,e.endPos=this.endPos,e.nextPts=this.nextPts,e}ensureBuffered(e){let r=this.endPos-this.currentPos;return r>=e?e:this.bufferData(e-r).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){let e=this.pesPackets[this.currentPesPacketIndex];return x(e),e}async bufferData(e){let r=this.endPos+e;for(;this.endPos<r;){let n;if(this.pesPackets.length===0)n=this.startingPesPacket;else{let i=Ze(this.pesPackets).sectionEndPos;for(x(i!==null);;){let s=await this.demuxer.readPacketHeader(i);if(!s)return;if(s.pid===this.pid){let a=await this.demuxer.readSection(i,!0);if(!a)return;let c=Ip(a);if(c){n=c;break}}i+=this.demuxer.packetStride}}this.pesPackets.push(n),this.endPos+=n.data.byteLength,this.pesPackets.length===1&&(this.nextPts=n.pts)}}readBytes(e){let r=this.getCurrentPesPacket(),n=this.currentPos-this.currentPesPacketPos,i=n+e;if(this.currentPos+=e,i<=r.data.byteLength)return r.data.subarray(n,i);let s=new Uint8Array(e);s.set(r.data.subarray(n));let a=r.data.byteLength-n;for(;;){this.advanceCurrentPacket();let c=this.getCurrentPesPacket(),l=e-a;if(l<=c.data.byteLength){s.set(c.data.subarray(0,l),a);break}s.set(c.data,a),a+=c.data.byteLength}return s}readU8(){let e=this.getCurrentPesPacket(),r=this.currentPos-this.currentPesPacketPos;return this.currentPos++,r<e.data.byteLength?e.data[r]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;let r=this.getCurrentPesPacket();this.currentPesPacketPos-=r.data.byteLength,this.nextPts=r.pts}else for(;;){let r=this.getCurrentPesPacket(),n=this.currentPesPacketPos+r.data.byteLength;if(e<n)break;this.currentPesPacketPos+=r.data.byteLength,this.currentPesPacketIndex++,this.nextPts=this.getCurrentPesPacket().pts}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++,this.nextPts=this.getCurrentPesPacket().pts}supplyPacket(e,r){let n=this.getCurrentPesPacket();DI(this.elementaryStream,n);let i=this.nextPts;this.nextPts+=r;let s=n.sectionStartPos,a=s+(this.currentPos-this.currentPesPacketPos),c=this.readBytes(e),l=n.randomAccessIndicator;x(this.elementaryStream.firstSection),n.sectionStartPos===this.elementaryStream.firstSection.startPos&&(l=1),this.suppliedPacket={pts:i,data:c,sequenceNumber:a,sectionStartPos:s,randomAccessIndicator:l},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},Dp=class{static{o(this,"PacketBuffer")}constructor(e,r){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=r,this.reorderSize=e.getReorderSize(),x(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let e=this.decodeOrderPackets[0],r=this.presentationOrderPackets.indexOf(e);x(r!==-1);let n;for(r===this.presentationOrderPackets.length-1?n=this.lastDuration:(n=this.presentationOrderPackets[r+1].pts-e.pts,this.lastDuration=n),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let i=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(i))break;this.presentationOrderPackets.shift()}return{packet:e,duration:n}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket?e=this.context.suppliedPacket:(await Lee(this.context),e=this.context.suppliedPacket),this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){let e=this.decodeOrderPackets[0];for(x(e);;){let r=this.presentationOrderPackets.indexOf(e);if(r!==-1&&r<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>=this.reorderSize){let r=0;for(let i=1;i<this.reorderBuffer.length;i++)this.reorderBuffer[i].pts<this.reorderBuffer[r].pts&&(r=i);let n=this.reorderBuffer.splice(r,1)[0];this.presentationOrderPackets.push(n)}}flushReorderBuffer(){this.reorderBuffer.sort((e,r)=>e.pts-r.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}});var Mn,yd,Mp,Op,bd,Rp,Np,Ap,Fp,Lp,Bp,zp,MI,OI,RI,NI,AI,FI,LI,BI,zI,UI,zU,$I=he(()=>{yU();ik();EU();CU();Ka();sc();yI();RU();TI();gd();EI();qt();LU();BU();Tk();Mn=class{static{o(this,"InputFormat")}},yd=class extends Mn{static{o(this,"IsobmffInputFormat")}async _getMajorBrand(e){let r=e._reader.requestSlice(0,12);return r instanceof Promise&&(r=await r),!r||(r.skip(4),It(r,4)!=="ftyp")?null:It(r,4)}_createDemuxer(e){return new Jx(e)}},Mp=class extends yd{static{o(this,"Mp4InputFormat")}async _canReadInput(e){let r=await this._getMajorBrand(e);return!!r&&r!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Op=class extends yd{static{o(this,"QuickTimeInputFormat")}async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},bd=class extends Mn{static{o(this,"MatroskaInputFormat")}async isSupportedEBMLOfDocType(e,r){let n=e._reader.requestSlice(0,ts);if(n instanceof Promise&&(n=await n),!n)return!1;let i=uI(n);if(i===null||i<1||i>8||Oe(n,i)!==I.EBML)return!1;let a=fI(n);if(typeof a!="number")return!1;let c=e._reader.requestSlice(n.filePos,a);if(c instanceof Promise&&(c=await c),!c)return!1;let l=n.filePos;for(;c.filePos<=l+a-In;){let u=rs(c);if(!u)break;let{id:f,size:d}=u,h=c.filePos;if(d===void 0)return!1;switch(f){case I.EBMLVersion:if(Oe(c,d)!==1)return!1;break;case I.EBMLReadVersion:if(Oe(c,d)!==1)return!1;break;case I.DocType:if(ic(c,d)!==r)return!1;break;case I.DocTypeVersion:if(Oe(c,d)>4)return!1;break}c.filePos=h+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new ck(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Rp=class extends bd{static{o(this,"WebMInputFormat")}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},Np=class extends Mn{static{o(this,"Mp3InputFormat")}async _canReadInput(e){let r=0;for(;;){let d=e._reader.requestSlice(r,Xn);if(d instanceof Promise&&(d=await d),!d)break;let h=ns(d);if(!h)break;r=d.filePos+h.size}let n=await vp(e._reader,r,r+4096);if(!n)return!1;let i=n.header,s=Qa(i.mpegVersionId,i.channel),a=e._reader.requestSlice(n.startPos+s,4);if(a instanceof Promise&&(a=await a),!a)return!1;let c=X(a);if(c===Ga||c===Xf)return!0;r=n.startPos+n.header.totalSize;let u=await vp(e._reader,r,r+4);if(!u)return!1;let f=u.header;return!(i.channel!==f.channel||i.sampleRate!==f.sampleRate)}_createDemuxer(e){return new lk(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},Ap=class extends Mn{static{o(this,"WaveInputFormat")}async _canReadInput(e){let r=e._reader.requestSlice(0,12);if(r instanceof Promise&&(r=await r),!r)return!1;let n=It(r,4);return n!=="RIFF"&&n!=="RIFX"&&n!=="RF64"?!1:(r.skip(4),It(r,4)==="WAVE")}_createDemuxer(e){return new gk(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},Fp=class extends Mn{static{o(this,"OggInputFormat")}async _canReadInput(e){let r=e._reader.requestSlice(0,4);return r instanceof Promise&&(r=await r),r?It(r,4)==="OggS":!1}_createDemuxer(e){return new pk(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},Lp=class extends Mn{static{o(this,"FlacInputFormat")}async _canReadInput(e){let r=e._reader.requestSlice(0,4);return r instanceof Promise&&(r=await r),r?It(r,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new kk(e)}},Bp=class extends Mn{static{o(this,"AdtsInputFormat")}async _canReadInput(e){let r=0;for(;;){let a=e._reader.requestSlice(r,Xn);if(a instanceof Promise&&(a=await a),!a)break;let c=ns(a);if(!c)break;r=a.filePos+c.size}let n=e._reader.requestSliceRange(r,Wo,Jn);if(n instanceof Promise&&(n=await n),!n)return!1;let i=Dn(n);if(!i||(r+=i.frameLength,n=e._reader.requestSliceRange(r,Wo,Jn),n instanceof Promise&&(n=await n),!n))return!1;let s=Dn(n);return s?i.objectType===s.objectType&&i.samplingFrequencyIndex===s.samplingFrequencyIndex&&i.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new yk(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},zp=class extends Mn{static{o(this,"MpegTsInputFormat")}async _canReadInput(e){let r=205,n=e._reader.requestSlice(0,r);if(n instanceof Promise&&(n=await n),!n)return!1;let i=se(n,r);return i[0]===71&&i[188]===71||i[0]===71&&i[204]===71?!0:i[4]===71&&i[196]===71}_createDemuxer(e){return new Ek(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}},MI=new Mp,OI=new Op,RI=new bd,NI=new Rp,AI=new Np,FI=new Ap,LI=new Fp,BI=new Bp,zI=new Lp,UI=new zp,zU=[MI,OI,RI,NI,FI,LI,zI,AI,BI,UI]});var HI=ri(()=>{});var UU,Bee,Ci,Ck,Pk,$U,zee,Ik,_k,$p,Dk,VI,Up,WI=he(()=>{Ue();UU=us(HI(),1);od();Bee=typeof UU<"u"?UU:void 0,Ci=class{static{o(this,"Source")}constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new er;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new er;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}},Ck=class extends Ci{static{o(this,"BufferSource")}constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw new TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super(),this._onreadCalled=!1,this._bytes=qe(e),this._view=ge(e)}_retrieveSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this.onread?.(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}},Pk=class extends Ci{static{o(this,"BlobSource")}constructor(e,r={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.maxCacheSize!==void 0&&(!ja(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new Up({maxCacheSize:r.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:VI.fileSystem})}_retrieveSize(){let e=this._blob.size;return this._orchestrator.fileSize=e,e}_read(e,r){return this._orchestrator.read(e,r)}async _runWorker(e){let r=this._readers.get(e);for(r===void 0&&("stream"in this._blob&&!Wa()?r=this._blob.slice(e.currentPos).stream().getReader():r=null,this._readers.set(e,r));e.currentPos<e.targetPos&&!e.aborted;)if(r){let{done:n,value:i}=await r.read();if(n)throw this._orchestrator.forgetWorker(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else{let n=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+n.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(n))}e.running=!1,e.aborted&&await r?.cancel()}_dispose(){this._orchestrator.dispose()}},$U=.5*2**20,zee=o(((t,e,r)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))){let i=null;try{typeof window<"u"&&typeof window.location<"u"&&(i=new URL(r instanceof Request?r.url:r,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&i!==null&&i!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(t-2),16)}),"DEFAULT_RETRY_DELAY"),Ik=class extends Ci{static{o(this,"UrlSource")}constructor(e,r={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.requestInit!==void 0&&(!r.requestInit||typeof r.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(r.getRetryDelay!==void 0&&typeof r.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(r.maxCacheSize!==void 0&&(!ja(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(r.parallelism!==void 0&&(!Number.isInteger(r.parallelism)||r.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(r.fetchFn!==void 0&&typeof r.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=r,this._getRetryDelay=r.getRetryDelay??zee;let n=2;this._orchestrator=new Up({maxCacheSize:r.maxCacheSize??64*2**20,maxWorkerCount:r.parallelism??n,runWorker:this._runWorker.bind(this),prefetchProfile:VI.network})}async _retrieveSize(){let e=new AbortController,r=await UP(this._options.fetchFn??fetch,this._url,zP(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw new Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);let n,i;if(r.status===206)i=this._getTotalLengthFromRangeResponse(r),n=this._orchestrator.createWorker(0,Math.min(i,$U));else{let s=r.headers.get("Content-Length");if(s)i=Number(s),n=this._orchestrator.createWorker(0,i),this._orchestrator.options.maxCacheSize=1/0,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.");else throw new Error(`HTTP response (status ${r.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=i,this._existingResponses.set(n,{response:r,abortController:e}),this._orchestrator.runWorker(n),i}_read(e,r){return this._orchestrator.read(e,r)}async _runWorker(e){for(;;){let r=this._existingResponses.get(e);this._existingResponses.delete(e);let n=r?.abortController,i=r?.response;if(n||(n=new AbortController,i=await UP(this._options.fetchFn??fetch,this._url,zP(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>this._disposed)),x(i),!i.ok)throw new Error(`Error fetching ${String(this._url)}: ${i.status} ${i.statusText}`);if(e.currentPos>0&&i.status!==206)throw new Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!i.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let s=i.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){n.abort(),e.running=!1;return}let a;try{a=await s.read()}catch(u){if(this._disposed)throw u;let f=this._getRetryDelay(1,u,this._url);if(f!==null){console.error("Error while reading response stream. Attempting to resume.",u),await new Promise(d=>setTimeout(d,1e3*f));break}else throw u}if(e.aborted)continue;let{done:c,value:l}=a;if(c){if(e.currentPos>=e.targetPos){this._orchestrator.forgetWorker(e),e.running=!1;return}break}this.onread?.(e.currentPos,e.currentPos+l.length),this._orchestrator.supplyWorkerData(e,l)}}}_getTotalLengthFromRangeResponse(e){let r=e.headers.get("Content-Range");if(r){let i=/\/(\d+)/.exec(r);if(i)return Number(i[1])}let n=e.headers.get("Content-Length");if(n)return Number(n);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}},_k=class extends Ci{static{o(this,"FilePathSource")}constructor(e,r={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.maxCacheSize!==void 0&&(!ja(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._fileHandle=null,this._streamSource=new $p({getSize:o(async()=>(this._fileHandle=await Bee.fs.open(e,"r"),(await this._fileHandle.stat()).size),"getSize"),read:o(async(n,i)=>{x(this._fileHandle);let s=new Uint8Array(i-n);return await this._fileHandle.read(s,0,i-n,n),s},"read"),maxCacheSize:r.maxCacheSize,prefetchProfile:"fileSystem"})}_read(e,r){return this._streamSource._read(e,r)}_retrieveSize(){return this._streamSource._retrieveSize()}_dispose(){this._streamSource._dispose(),this._fileHandle?.close(),this._fileHandle=null}},$p=class extends Ci{static{o(this,"StreamSource")}constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(typeof e.getSize!="function")throw new TypeError("options.getSize must be a function.");if(typeof e.read!="function")throw new TypeError("options.read must be a function.");if(e.dispose!==void 0&&typeof e.dispose!="function")throw new TypeError("options.dispose, when provided, must be a function.");if(e.maxCacheSize!==void 0&&(!ja(e.maxCacheSize)||e.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(e.prefetchProfile&&!["none","fileSystem","network"].includes(e.prefetchProfile))throw new TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super(),this._options=e,this._orchestrator=new Up({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:VI[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this)})}_retrieveSize(){let e=this._options.getSize();if(e instanceof Promise)return e.then(r=>{if(!Number.isInteger(r)||r<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=r,r});if(!Number.isInteger(e)||e<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=e,e}_read(e,r){return this._orchestrator.read(e,r)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){let r=e.currentPos,n=e.targetPos,i=this._options.read(e.currentPos,n);if(i instanceof Promise&&(i=await i),e.aborted)break;if(i instanceof Uint8Array){if(i=qe(i),i.length!==n-e.currentPos)throw new Error(`options.read returned a Uint8Array with unexpected length: Requested ${n-e.currentPos} bytes, but got ${i.length}.`);this.onread?.(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else if(i instanceof ReadableStream){let s=i.getReader();for(;e.currentPos<n&&!e.aborted;){let{done:a,value:c}=await s.read();if(a){if(e.currentPos<n)throw new Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${n-r} bytes, but got ${e.currentPos-r}`);break}if(!(c instanceof Uint8Array))throw new TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if(e.aborted)break;let l=qe(c);this.onread?.(e.currentPos,e.currentPos+l.length),this._orchestrator.supplyWorkerData(e,l)}}else throw new TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.")}e.running=!1}_dispose(){this._orchestrator.dispose(),this._options.dispose?.()}},Dk=class extends Ci{static{o(this,"ReadableStreamSource")}constructor(e,r={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.maxCacheSize!==void 0&&(!ja(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=e,this._maxCacheSize=r.maxCacheSize??16*2**20}_retrieveSize(){return this._endIndex}_read(e,r){if(this._endIndex!==null&&r>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,r);let n=ze(this._cache,e,f=>f.start),i=n!==-1?this._cache[n]:null;if(i&&i.start<=e&&r<=i.end)return{bytes:i.bytes,view:i.view,offset:i.start};let s=e,a=new Uint8Array(r-e);if(n!==-1)for(let f=n;f<this._cache.length;f++){let d=this._cache[f];if(d.start>=r)break;let h=Math.max(e,d.start);h>s&&this._throwDueToCacheMiss();let m=Math.min(r,d.end);h<m&&(a.set(d.bytes.subarray(h-d.start,m-d.start),h-e),s=m)}if(s===r)return{bytes:a,view:ge(a),offset:e};this._currentIndex>s&&this._throwDueToCacheMiss();let{promise:c,resolve:l,reject:u}=ut();return this._pendingSlices.push({start:e,end:r,bytes:a,resolve:l,reject:u}),this._targetIndex=Math.max(this._targetIndex,r),this._pulling||(this._pulling=!0,this._pull().catch(f=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(d=>d.reject(f)),this._pendingSlices.length=0;else throw f})),c}_throwDueToCacheMiss(){throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){let{done:e,value:r}=await this._reader.read();if(e){for(let s of this._pendingSlices)s.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let n=this._currentIndex,i=this._currentIndex+r.byteLength;for(let s=0;s<this._pendingSlices.length;s++){let a=this._pendingSlices[s],c=Math.max(n,a.start),l=Math.min(i,a.end);c<l&&(a.bytes.set(r.subarray(c-n,l-n),c-a.start),l===a.end&&(a.resolve({bytes:a.bytes,view:ge(a.bytes),offset:a.start}),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:n,end:i,bytes:r,view:ge(r),age:0});this._cache.length>0;){let s=this._cache[0];if(this._maxRequestedIndex-s.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=r.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0}},VI={none:o((t,e)=>({start:t,end:e}),"none"),fileSystem:o((t,e)=>(t=Math.floor((t-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:t,end:e}),"fileSystem"),network:o((t,e,r)=>{t=Math.max(0,Math.floor((t-65536)/65536)*65536);for(let i of r){let a=Math.max((i.startPos+i.targetPos)/2,i.targetPos-8388608);if(Tx(t,e,a,i.targetPos)){let c=i.targetPos-i.startPos,l=Math.ceil((c+1)/8388608)*8388608,u=2**Math.ceil(Math.log2(c+1)),f=Math.min(u,l);e=Math.max(e,i.startPos+f)}}return e=Math.max(e,t+$U),{start:t,end:e}},"network")},Up=class{static{o(this,"ReadOrchestrator")}constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,r){x(this.fileSize!==null);let n=this.options.prefetchProfile(e,r,this.workers),i=Math.max(n.start,0),s=Math.min(n.end,this.fileSize);x(i<=e&&r<=s);let a=null,c=ze(this.cache,e,w=>w.start),l=c!==-1?this.cache[c]:null;l&&l.start<=e&&r<=l.end&&(l.age=this.nextAge++,a={bytes:l.bytes,view:l.view,offset:l.start});let u=ze(this.cache,i,w=>w.start),f=a?null:new Uint8Array(r-e),d=0,h=i,m=[];if(u!==-1){for(let w=u;w<this.cache.length;w++){let k=this.cache[w];if(k.start>=s)break;if(k.end<=i)continue;let T=Math.max(i,k.start),v=Math.min(s,k.end);if(x(T<=v),h<T&&m.push({start:h,end:T}),h=v,f){let S=Math.max(e,k.start),M=Math.min(r,k.end);if(S<M){let P=S-e;f.set(k.bytes.subarray(S-k.start,M-k.start),P),P===d&&(d=M-e)}}k.age=this.nextAge++}h<s&&m.push({start:h,end:s})}else m.push({start:i,end:s});if(f&&d>=f.length&&(a={bytes:f,view:ge(f),offset:e}),m.length===0)return x(a),a;let{promise:p,resolve:g,reject:y}=ut(),b=[];for(let w of m){let k=Math.max(e,w.start),T=Math.min(r,w.end);k===w.start&&T===w.end?b.push(w):k<T&&b.push({start:k,end:T})}for(let w of m){let k=f&&{start:e,bytes:f,holes:b,resolve:g,reject:y},T=!1;for(let v of this.workers)if(Tx(w.start-131072,w.start,v.currentPos,v.targetPos)){v.targetPos=Math.max(v.targetPos,w.end),T=!0,k&&!v.pendingSlices.includes(k)&&v.pendingSlices.push(k),v.running||this.runWorker(v);break}if(!T){let v=this.createWorker(w.start,w.end);k&&(v.pendingSlices=[k]),this.runWorker(v)}}return a||(x(f),a=p.then(w=>({bytes:w,view:ge(w),offset:e}))),a}createWorker(e,r){let n={startPos:e,currentPos:e,targetPos:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(n);this.workers.length>this.options.maxWorkerCount;){let i=0,s=this.workers[0];for(let a=1;a<this.workers.length;a++){let c=this.workers[a];c.age<s.age&&(i=a,s=c)}if(s.running&&s.pendingSlices.length>0)break;s.aborted=!0,this.workers.splice(i,1)}return n}runWorker(e){x(!e.running),x(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(r=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(n=>n.reject(r)),e.pendingSlices.length=0;else throw r})}supplyWorkerData(e,r){x(!e.aborted);let n=e.currentPos,i=n+r.length;this.insertIntoCache({start:n,end:i,bytes:r,view:ge(r),age:this.nextAge++}),e.currentPos+=r.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let s=0;s<e.pendingSlices.length;s++){let a=e.pendingSlices[s],c=Math.max(n,a.start),l=Math.min(i,a.start+a.bytes.length);c<l&&a.bytes.set(r.subarray(c-n,l-n),c-a.start);for(let u=0;u<a.holes.length;u++){let f=a.holes[u];n<=f.start&&i>f.start&&(f.start=i),f.end<=f.start&&(a.holes.splice(u,1),u--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(s,1),s--)}for(let s=0;s<this.workers.length;s++){let a=this.workers[s];e===a||a.running||Tx(n,i,a.currentPos,a.targetPos)&&(this.workers.splice(s,1),s--)}}forgetWorker(e){let r=this.workers.indexOf(e);x(r!==-1),this.workers.splice(r,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let r=ze(this.cache,e.start,n=>n.start)+1;if(r>0){let n=this.cache[r-1];if(n.end>=e.end)return;if(n.end>e.start){let i=new Uint8Array(e.end-n.start);i.set(n.bytes,0),i.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=i,n.view=ge(i),n.end=e.end,r--,e=n}else this.cache.splice(r,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(r,0,e),this.currentCacheSize+=e.bytes.length;for(let n=r+1;n<this.cache.length;n++){let i=this.cache[n];if(e.end<=i.start)break;if(e.end>=i.end){this.cache.splice(n,1),this.currentCacheSize-=i.bytes.length,n--;continue}let s=new Uint8Array(i.end-e.start);s.set(e.bytes,0),s.set(i.bytes,i.start-e.start),this.currentCacheSize-=e.end-i.start,e.bytes=s,e.view=ge(s),e.end=i.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let n=0,i=this.cache[0];for(let s=1;s<this.cache.length;s++){let a=this.cache[s];a.age<i.age&&(n=s,i=a)}if(this.currentCacheSize-i.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(n,1),this.currentCacheSize-=i.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}});var wd,er,od=he(()=>{$I();Ue();qt();WI();vx();wd=class{static{o(this,"Input")}get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(r=>!(r instanceof Mn)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Ci))throw new TypeError("options.source must be a Source.");if(e.source._disposed)throw new Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new Mk(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw new Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),x(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getFirstTimestamp(){let e=await this.getTracks();if(e.length===0)return 0;let r=await Promise.all(e.map(n=>n.getFirstTimestamp()));return Math.min(...r)}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(r=>r.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(r=>r.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(r=>r.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(r=>r.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}},er=class extends Error{static{o(this,"InputDisposedError")}constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}});var Mk,xr,On,se,oe,pd,jt,nc,xp,Vo,X,Ul,Bo,Uee,SI,Kn,bU,DU,TU,Zx,It,qt=he(()=>{od();Ue();Mk=class{static{o(this,"Reader")}constructor(e){this.source=e}requestSlice(e,r){if(this.source._disposed)throw new er;if(e<0||this.fileSize!==null&&e+r>this.fileSize)return null;let n=e+r,i=this.source._read(e,n);return i instanceof Promise?i.then(s=>s?new xr(s.bytes,s.view,s.offset,e,n):null):i?new xr(i.bytes,i.view,i.offset,e,n):null}requestSliceRange(e,r,n){if(this.source._disposed)throw new er;if(e<0)return null;if(this.fileSize!==null)return this.requestSlice(e,Ht(this.fileSize-e,r,n));{let i=this.requestSlice(e,n),s=o(a=>{if(a)return a;let c=o(u=>(x(u!==null),this.requestSlice(e,Ht(u-e,r,n))),"handleFileSize"),l=this.source._retrieveSize();return l instanceof Promise?l.then(c):c(l)},"handleAttempt");return i instanceof Promise?i.then(s):s(i)}}},xr=class t{static{o(this,"FileSlice")}constructor(e,r,n,i,s){this.bytes=e,this.view=r,this.offset=n,this.start=i,this.end=s,this.bufferPos=i-n}static tempFromBytes(e){return new t(e,ge(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,r=this.end-e){if(e<this.start||e+r>this.end)throw new RangeError("Slicing outside of original slice.");return new t(this.bytes,this.view,this.offset,e,e+r)}},On=o((t,e)=>{if(t.filePos<t.start||t.filePos+e>t.end)throw new RangeError(`Tried reading [${t.filePos}, ${t.filePos+e}), but slice is [${t.start}, ${t.end}). This is likely an internal error, please report it alongside the file that caused it.`)},"checkIsInRange"),se=o((t,e)=>{On(t,e);let r=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,r},"readBytes"),oe=o(t=>(On(t,1),t.view.getUint8(t.bufferPos++)),"readU8"),pd=o((t,e)=>{On(t,2);let r=t.view.getUint16(t.bufferPos,e);return t.bufferPos+=2,r},"readU16"),jt=o(t=>{On(t,2);let e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e},"readU16Be"),nc=o(t=>{On(t,3);let e=_l(t.view,t.bufferPos,!1);return t.bufferPos+=3,e},"readU24Be"),xp=o(t=>{On(t,2);let e=t.view.getInt16(t.bufferPos,!1);return t.bufferPos+=2,e},"readI16Be"),Vo=o((t,e)=>{On(t,4);let r=t.view.getUint32(t.bufferPos,e);return t.bufferPos+=4,r},"readU32"),X=o(t=>{On(t,4);let e=t.view.getUint32(t.bufferPos,!1);return t.bufferPos+=4,e},"readU32Be"),Ul=o(t=>{On(t,4);let e=t.view.getUint32(t.bufferPos,!0);return t.bufferPos+=4,e},"readU32Le"),Bo=o(t=>{On(t,4);let e=t.view.getInt32(t.bufferPos,!1);return t.bufferPos+=4,e},"readI32Be"),Uee=o(t=>{On(t,4);let e=t.view.getInt32(t.bufferPos,!0);return t.bufferPos+=4,e},"readI32Le"),SI=o((t,e)=>{let r,n;return e?(r=Vo(t,!0),n=Vo(t,!0)):(n=Vo(t,!1),r=Vo(t,!1)),n*4294967296+r},"readU64"),Kn=o(t=>{let e=X(t),r=X(t);return e*4294967296+r},"readU64Be"),bU=o(t=>{let e=Bo(t),r=X(t);return e*4294967296+r},"readI64Be"),DU=o(t=>{let e=Ul(t);return Uee(t)*4294967296+e},"readI64Le"),TU=o(t=>{On(t,4);let e=t.view.getFloat32(t.bufferPos,!1);return t.bufferPos+=4,e},"readF32Be"),Zx=o(t=>{On(t,8);let e=t.view.getFloat64(t.bufferPos,!1);return t.bufferPos+=8,e},"readF64Be"),It=o((t,e)=>{On(t,e);let r="";for(let n=0;n<e;n++)r+=String.fromCharCode(t.bytes[t.bufferPos++]);return r},"readAscii")});var xd,an,Ep,Xn,kd,PU,Sd,ns,dd,jI,ac,sc=he(()=>{Ka();Ue();qt();(function(t){t[t.Unsynchronisation=128]="Unsynchronisation",t[t.ExtendedHeader=64]="ExtendedHeader",t[t.ExperimentalIndicator=32]="ExperimentalIndicator",t[t.Footer=16]="Footer"})(xd||(xd={}));(function(t){t[t.ISO_8859_1=0]="ISO_8859_1",t[t.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",t[t.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",t[t.UTF_8=3]="UTF_8"})(an||(an={}));Ep=128,Xn=10,kd=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],PU=o((t,e)=>{let r=t.filePos;e.raw??={},e.raw.TAG??=se(t,Ep-3),t.filePos=r;let n=Sd(t,30);n&&(e.title??=n);let i=Sd(t,30);i&&(e.artist??=i);let s=Sd(t,30);s&&(e.album??=s);let a=Sd(t,4),c=Number.parseInt(a,10);Number.isInteger(c)&&c>0&&(e.date??=new Date(c,0,1));let l=se(t,30),u;if(l[28]===0&&l[29]!==0){let d=l[29];d>0&&(e.trackNumber??=d),t.skip(-30),u=Sd(t,28),t.skip(2)}else t.skip(-30),u=Sd(t,30);u&&(e.comment??=u);let f=oe(t);f<kd.length&&(e.genre??=kd[f])},"parseId3V1Tag"),Sd=o((t,e)=>{let r=se(t,e),n=Ml(r.indexOf(0),r.length),i=r.subarray(0,n),s="";for(let a=0;a<i.length;a++)s+=String.fromCharCode(i[a]);return s.trimEnd()},"readId3V1String"),ns=o(t=>{let e=t.filePos,r=It(t,3),n=oe(t),i=oe(t),s=oe(t),a=X(t);if(r!=="ID3"||n===255||i===255||(a&2155905152)!==0)return t.filePos=e,null;let c=Mx(a);return{majorVersion:n,revision:i,flags:s,size:c}},"readId3V2Header"),dd=o((t,e,r)=>{if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let n=se(t,e.size),i=new jI(e,n);if(e.flags&xd.Footer&&i.removeFooter(),e.flags&xd.Unsynchronisation&&e.majorVersion===3&&i.ununsynchronizeAll(),e.flags&xd.ExtendedHeader){let s=i.readU32();e.majorVersion===3?i.pos+=s:i.pos+=s-4}for(;i.pos<=i.bytes.length-i.frameHeaderSize();){let s=i.readId3V2Frame();if(!s)break;let a=i.pos,c=i.pos+s.size,l=!1,u=!1,f=!1;if(e.majorVersion===3?(l=!!(s.flags&64),u=!!(s.flags&128)):e.majorVersion===4&&(l=!!(s.flags&4),u=!!(s.flags&8),f=!!(s.flags&2)||!!(e.flags&xd.Unsynchronisation)),l){console.warn(`Skipping encrypted ID3v2 frame ${s.id}`),i.pos=c;continue}if(u){console.warn(`Skipping compressed ID3v2 frame ${s.id}`),i.pos=c;continue}switch(f&&i.ununsynchronizeRegion(i.pos,c),r.raw??={},s.id[0]==="T"?r.raw[s.id]??=i.readId3V2EncodingAndText(c):r.raw[s.id]??=i.readBytes(s.size),i.pos=a,s.id){case"TIT2":case"TT2":r.title??=i.readId3V2EncodingAndText(c);break;case"TIT3":case"TT3":r.description??=i.readId3V2EncodingAndText(c);break;case"TPE1":case"TP1":r.artist??=i.readId3V2EncodingAndText(c);break;case"TALB":case"TAL":r.album??=i.readId3V2EncodingAndText(c);break;case"TPE2":case"TP2":r.albumArtist??=i.readId3V2EncodingAndText(c);break;case"TRCK":case"TRK":{let h=i.readId3V2EncodingAndText(c).split("/"),m=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(m)&&m>0&&(r.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(r.tracksTotal??=p)}break;case"TPOS":case"TPA":{let h=i.readId3V2EncodingAndText(c).split("/"),m=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(m)&&m>0&&(r.discNumber??=m),p&&Number.isInteger(p)&&p>0&&(r.discsTotal??=p)}break;case"TCON":case"TCO":{let d=i.readId3V2EncodingAndText(c),h=/^\((\d+)\)/.exec(d);if(h){let m=Number.parseInt(h[1]);if(kd[m]!==void 0){r.genre??=kd[m];break}}if(h=/^\d+$/.exec(d),h){let m=Number.parseInt(h[0]);if(kd[m]!==void 0){r.genre??=kd[m];break}}r.genre??=d}break;case"TDRC":case"TDAT":{let d=i.readId3V2EncodingAndText(c),h=new Date(d);Number.isNaN(h.getTime())||(r.date??=h)}break;case"TYER":case"TYE":{let d=i.readId3V2EncodingAndText(c),h=Number.parseInt(d,10);Number.isInteger(h)&&(r.date??=new Date(h,0,1))}break;case"USLT":case"ULT":{let d=i.readU8();i.pos+=3,i.readId3V2Text(d,c),r.lyrics??=i.readId3V2Text(d,c)}break;case"COMM":case"COM":{let d=i.readU8();i.pos+=3,i.readId3V2Text(d,c),r.comment??=i.readId3V2Text(d,c)}break;case"APIC":case"PIC":{let d=i.readId3V2TextEncoding(),h;if(e.majorVersion===2){let y=i.readAscii(3);h=y==="PNG"?"image/png":y==="JPG"?"image/jpeg":"image/*"}else h=i.readId3V2Text(d,c);let m=i.readU8(),p=i.readId3V2Text(d,c).trimEnd(),g=c-i.pos;if(g>=0){let y=i.readBytes(g);r.images||(r.images=[]),r.images.push({data:y,mimeType:h,kind:m===3?"coverFront":m===4?"coverBack":"unknown",description:p})}}break;default:i.pos+=s.size;break}i.pos=c}},"parseId3V2Tag"),jI=class{static{o(this,"Id3V2Reader")}constructor(e,r){this.header=e,this.bytes=r,this.pos=0,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let r=0;r<this.bytes.length;r++){let n=this.bytes[r];e.push(n),n===255&&r!==this.bytes.length-1&&this.bytes[r]===0&&r++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,r){let n=[];for(let a=e;a<r;a++){let c=this.bytes[a];n.push(c),c===255&&a!==r-1&&this.bytes[a+1]===0&&a++}let i=this.bytes.subarray(0,e),s=this.bytes.subarray(r);this.bytes=new Uint8Array(i.length+n.length+s.length),this.bytes.set(i,0),this.bytes.set(n,i.length),this.bytes.set(s,i.length+n.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-Xn),this.view=new DataView(this.bytes.buffer)}readBytes(e){let r=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,r}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),r=this.view.getUint8(this.pos+1);return this.pos+=3,e*256+r}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let r="";for(let n=0;n<e;n++)r+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,r}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);if(e==="\0\0\0")return null;let r=this.readU24();return{id:e,size:r,flags:0}}else{let e=this.readAscii(4);if(e==="\0\0\0\0")return null;let r=this.readU32(),n=this.header.majorVersion===4?Mx(r):r,i=this.readU16(),s=this.pos,a=o(c=>{let l=this.pos+c;if(l>this.bytes.length)return!1;if(l<=this.bytes.length-this.frameHeaderSize()){this.pos+=c;let u=this.readAscii(4);if(u!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(u))return!1}return!0},"isSizeValid");if(!a(n)){let c=this.header.majorVersion===4?r:Mx(r);a(c)&&(n=c)}return this.pos=s,{id:e,size:n,flags:i}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,r){let n=this.pos,i=this.readBytes(r-this.pos);switch(e){case an.ISO_8859_1:{let s="";for(let a=0;a<i.length;a++){let c=i[a];if(c===0){this.pos=n+a+1;break}s+=String.fromCharCode(c)}return s}case an.UTF_16_WITH_BOM:if(i[0]===255&&i[1]===254){let s=new TextDecoder("utf-16le"),a=Ml(i.findIndex((c,l)=>c===0&&i[l+1]===0&&l%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(2,a))}else if(i[0]===254&&i[1]===255){let s=new TextDecoder("utf-16be"),a=Ml(i.findIndex((c,l)=>c===0&&i[l+1]===0&&l%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(2,a))}else{let s=Ml(i.findIndex(a=>a===0),i.length);return this.pos=n+Math.min(s+1,i.length),br.decode(i.subarray(0,s))}case an.UTF_16_BE_NO_BOM:{let s=new TextDecoder("utf-16be"),a=Ml(i.findIndex((c,l)=>c===0&&i[l+1]===0&&l%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(0,a))}case an.UTF_8:{let s=Ml(i.findIndex(a=>a===0),i.length);return this.pos=n+Math.min(s+1,i.length),br.decode(i.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let r=this.readId3V2TextEncoding();return this.readId3V2Text(r,e)}},ac=class{static{o(this,"Id3V2Writer")}constructor(e){this.helper=new Uint8Array(8),this.helperView=ge(this.helper),this.writer=e}writeId3V2Tag(e){let r=this.writer.getPos();this.writeAscii("ID3"),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);let n=this.writer.getPos(),i=new Set;for(let{key:c,value:l}of Gi(e))switch(c){case"title":this.writeId3V2TextFrame("TIT2",l),i.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",l),i.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",l),i.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",l),i.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",l),i.add("TPE2");break;case"trackNumber":{let u=e.tracksTotal!==void 0?`${l}/${e.tracksTotal}`:l.toString();this.writeId3V2TextFrame("TRCK",u),i.add("TRCK")}break;case"discNumber":{let u=e.discsTotal!==void 0?`${l}/${e.discsTotal}`:l.toString();this.writeId3V2TextFrame("TPOS",u),i.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",l),i.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",l.toISOString().slice(0,10)),i.add("TDRC");break;case"lyrics":this.writeId3V2LyricsFrame(l),i.add("USLT");break;case"comment":this.writeId3V2CommentFrame(l),i.add("COMM");break;case"images":{let u={coverFront:3,coverBack:4,unknown:0};for(let f of l){let d=u[f.kind]??0,h=f.description??"";this.writeId3V2ApicFrame(f.mimeType,d,h,f.data)}}break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:kt(c)}if(e.raw)for(let c in e.raw){let l=e.raw[c];if(l==null||c.length!==4||i.has(c))continue;let u;if(typeof l=="string"){let f=lt.encode(l);u=new Uint8Array(f.byteLength+2),u[0]=an.UTF_8,u.set(f,1)}else if(l instanceof Uint8Array)u=l;else continue;this.writeAscii(c),this.writeSynchsafeU32(u.byteLength),this.writeU16(0),this.writer.write(u)}let s=this.writer.getPos(),a=s-n;return this.writer.seek(r+6),this.writeSynchsafeU32(a),this.writer.seek(s),a+10}writeU8(e){this.helper[0]=e,this.writer.write(this.helper.subarray(0,1))}writeU16(e){this.helperView.setUint16(0,e,!1),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeAscii(e){for(let r=0;r<e.length;r++)this.helper[r]=e.charCodeAt(r);this.writer.write(this.helper.subarray(0,e.length))}writeSynchsafeU32(e){this.writeU32(Wz(e))}writeIsoString(e){let r=new Uint8Array(e.length+1);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);r[e.length]=0,this.writer.write(r)}writeUtf8String(e){let r=lt.encode(e);this.writer.write(r),this.writeU8(0)}writeId3V2TextFrame(e,r){let n=Va(r),s=1+(n?r.length:lt.encode(r).byteLength)+1;this.writeAscii(e),this.writeSynchsafeU32(s),this.writeU16(0),this.writeU8(n?an.ISO_8859_1:an.UTF_8),n?this.writeIsoString(r):this.writeUtf8String(r)}writeId3V2LyricsFrame(e){let r=Va(e),n="",i=4+n.length+1+e.length+1;this.writeAscii("USLT"),this.writeSynchsafeU32(i),this.writeU16(0),this.writeU8(r?an.ISO_8859_1:an.UTF_8),this.writeAscii("und"),r?(this.writeIsoString(n),this.writeIsoString(e)):(this.writeUtf8String(n),this.writeUtf8String(e))}writeId3V2CommentFrame(e){let r=Va(e),n=r?e.length:lt.encode(e).byteLength,i="",s=4+i.length+1+n+1;this.writeAscii("COMM"),this.writeSynchsafeU32(s),this.writeU16(0),this.writeU8(r?an.ISO_8859_1:an.UTF_8),this.writeU8(117),this.writeU8(110),this.writeU8(100),r?(this.writeIsoString(i),this.writeIsoString(e)):(this.writeUtf8String(i),this.writeUtf8String(e))}writeId3V2ApicFrame(e,r,n,i){let s=Va(e)&&Va(n),a=s?n.length:lt.encode(n).byteLength,c=1+e.length+1+1+a+1+i.byteLength;this.writeAscii("APIC"),this.writeSynchsafeU32(c),this.writeU16(0),this.writeU8(s?an.ISO_8859_1:an.UTF_8),s?this.writeIsoString(e):this.writeUtf8String(e),this.writeU8(r),s?this.writeIsoString(n):this.writeUtf8String(n),this.writer.write(i)}}});var Sr,jo=he(()=>{Ue();Sr=class{static{o(this,"Muxer")}constructor(e){this.mutex=new Tn,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,r,n){if(r+=e.source._timestampOffset,r<0)throw new Error(`Timestamps must be non-negative (got ${r}s).`);let i=this.trackTimestampInfo.get(e);if(i){if(n&&(i.maxTimestampBeforeLastKeyPacket=i.maxTimestamp),i.maxTimestampBeforeLastKeyPacket!==null&&r<i.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${r}s, but largest timestamp is ${i.maxTimestampBeforeLastKeyPacket}s.`);i.maxTimestamp=Math.max(i.maxTimestamp,r)}else{if(!n)throw new Error("First packet must be a key packet.");i={maxTimestamp:r,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,i)}return r}}});var Ok,HU=he(()=>{qs();Zt();sc();lr();Ue();jo();Ok=class extends Sr{static{o(this,"AdtsMuxer")}constructor(e,r){super(e),this.header=null,this.headerBitstream=null,this.inputIsAdts=null,this.format=r,this.writer=e._writer}async start(){Ro(this.output._metadataTags)||new ac(this.writer).writeId3V2Tag(this.output._metadataTags)}async getMimeType(){return"audio/aac"}async addEncodedVideoPacket(){throw new Error("ADTS does not support video.")}async addEncodedAudioPacket(e,r,n){let i=await this.mutex.acquire();try{if(this.validateAndNormalizeTimestamp(e,r.timestamp,r.type==="key"),this.inputIsAdts===null){En(n);let s=n?.decoderConfig?.description;if(this.inputIsAdts=!s,!this.inputIsAdts){let a=js(qe(s)),c=Ex(a);this.header=c.header,this.headerBitstream=c.bitstream}}if(this.inputIsAdts){let s=this.writer.getPos();this.writer.write(r.data),this.format._options.onFrame&&this.format._options.onFrame(r.data,s)}else{x(this.header);let s=r.data.byteLength+this.header.byteLength;Cx(this.headerBitstream,s);let a=this.writer.getPos();if(this.writer.write(this.header),this.writer.write(r.data),this.format._options.onFrame){let c=new Uint8Array(s);c.set(this.header,0),c.set(r.data,this.header.byteLength),this.format._options.onFrame(c,a)}}await this.writer.flush()}finally{i()}}async addSubtitleCue(){throw new Error("ADTS does not support subtitles.")}async finalize(){(await this.mutex.acquire())()}}});var VU,$ee,Hee,Rk,WU=he(()=>{Zt();sn();Ue();jo();qt();lr();CI();Ti();VU=new Uint8Array([102,76,97,67]),$ee=38,Hee=34,Rk=class extends Sr{static{o(this,"FlacMuxer")}constructor(e,r){super(e),this.metadataWritten=!1,this.blockSizes=[],this.frameSizes=[],this.sampleRate=null,this.channels=null,this.bitsPerSample=null,this.writer=e._writer,this.format=r,this.format._options.appendOnly&&(this.writer.ensureMonotonicity=!0)}async start(){this.writer.write(VU)}writeHeader({bitsPerSample:e,minimumBlockSize:r,maximumBlockSize:n,minimumFrameSize:i,maximumFrameSize:s,sampleRate:a,channels:c,totalSamples:l}){x(this.writer.getPos()===4);let u=!Ro(this.output._metadataTags),f=new Te(new Uint8Array(4));f.writeBits(1,+!u),f.writeBits(7,Ei.STREAMINFO),f.writeBits(24,Hee),this.writer.write(f.bytes);let d=new Te(new Uint8Array(18));if(d.writeBits(16,r),d.writeBits(16,n),d.writeBits(24,i),d.writeBits(24,s),d.writeBits(20,a),d.writeBits(3,c-1),d.writeBits(5,e-1),l>=2**32)throw new Error("This muxer only supports writing up to 2 ** 32 samples");d.writeBits(4,0),d.writeBits(32,l),this.writer.write(d.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){let r=32+e.mimeType.length+(e.description?.length??0)+e.data.length,n=new Uint8Array(r),i=0,s=ge(n);s.setUint32(i,e.kind==="coverFront"?3:e.kind==="coverBack"?4:0),i+=4,s.setUint32(i,e.mimeType.length),i+=4,n.set(lt.encode(e.mimeType),8),i+=e.mimeType.length,s.setUint32(i,e.description?.length??0),i+=4,n.set(lt.encode(e.description??""),i),i+=e.description?.length??0,i+=16,s.setUint32(i,e.data.length),i+=4,n.set(e.data,i),i+=e.data.length,x(i===r);let a=new Te(new Uint8Array(4));a.writeBits(1,0),a.writeBits(7,Ei.PICTURE),a.writeBits(24,r),this.writer.write(a.bytes),this.writer.write(n)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek($ee+VU.byteLength),Ro(this.output._metadataTags)){this.metadataWritten=!0;return}let e=this.output._metadataTags.images??[];for(let i of e)this.writePictureBlock(i);let r=op(new Uint8Array(0),this.output._metadataTags,!1),n=new Te(new Uint8Array(4));n.writeBits(1,1),n.writeBits(7,Ei.VORBIS_COMMENT),n.writeBits(24,r.length),this.writer.write(n.bytes),this.writer.write(r),this.metadataWritten=!0}async getMimeType(){return"audio/flac"}async addEncodedVideoPacket(){throw new Error("FLAC does not support video.")}async addEncodedAudioPacket(e,r,n){let i=await this.mutex.acquire();try{if(this.validateAndNormalizeTimestamp(e,r.timestamp,r.type==="key"),this.sampleRate===null){En(n),x(n),x(n.decoderConfig),x(n.decoderConfig.description),this.sampleRate=n.decoderConfig.sampleRate,this.channels=n.decoderConfig.numberOfChannels;let d=new Te(qe(n.decoderConfig.description));d.skipBits(167);let h=d.readBits(5)+1;this.bitsPerSample=h,this.format._options.appendOnly&&this.writeHeader({minimumBlockSize:16,maximumBlockSize:65535,minimumFrameSize:0,maximumFrameSize:0,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:0})}this.metadataWritten||this.writeVorbisCommentAndPictureBlock();let s=xr.tempFromBytes(r.data);s.skip(2);let a=se(s,2),c=new Te(a),l=bk(c.readBits(4));if(l===null)throw new Error("Invalid FLAC frame: Invalid block size.");wk(s);let u=xk(s,l);this.format._options.appendOnly||(this.blockSizes.push(u),this.frameSizes.push(r.data.length));let f=this.writer.getPos();this.writer.write(r.data),this.format._options.onFrame&&this.format._options.onFrame(r.data,f),await this.writer.flush()}finally{i()}}addSubtitleCue(){throw new Error("FLAC does not support subtitles.")}async finalize(){let e=await this.mutex.acquire();if(!this.format._options.appendOnly){let r=1/0,n=0,i=1/0,s=0,a=0;for(let c=0;c<this.blockSizes.length;c++)i=Math.min(i,this.frameSizes[c]),s=Math.max(s,this.frameSizes[c]),n=Math.max(n,this.blockSizes[c]),a+=this.blockSizes[c],c!==this.blockSizes.length-1&&(r=Math.min(r,this.blockSizes[c]));x(this.sampleRate!==null),x(this.channels!==null),x(this.bitsPerSample!==null),this.writer.seek(4),this.writeHeader({minimumBlockSize:r,maximumBlockSize:n,minimumFrameSize:i,maximumFrameSize:s,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:a})}e()}}});var Hp,Vee,Td,Nk,Wee,Ak,Fk,Vp=he(()=>{Hp=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,Vee=/^WEBVTT(.|\n)*?\n{2}/,Td=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Nk=class{static{o(this,"SubtitleParser")}constructor(e){this.preambleText=null,this.preambleEmitted=!1,this.options=e}parse(e){e=e.replaceAll(`\r
|
|
24
24
|
`,`
|
|
25
25
|
`).replaceAll("\r",`
|
|
26
26
|
`),Hp.lastIndex=0;let r;if(!this.preambleText){if(!Vee.test(e))throw new Error("WebVTT preamble incorrect.");r=Hp.exec(e);let n=e.slice(0,r?.index??e.length).trimEnd();if(!n)throw new Error("No WebVTT preamble provided.");this.preambleText=n,r&&(e=e.slice(r.index),Hp.lastIndex=0)}for(;r=Hp.exec(e);){let n=e.slice(0,r.index),i=r[1],s=r.index+r[0].length,a=e.indexOf(`
|
|
27
27
|
`,s)+1,c=e.slice(s,a).trim(),l=e.indexOf(`
|
|
28
28
|
|
|
29
|
-
`,s);l===-1&&(l=e.length);let u=Ak(r[2]),d=Ak(r[3])-u,h=e.slice(a,l).trim();e=e.slice(l).trimStart(),Hp.lastIndex=0;let m={timestamp:u/1e3,duration:d/1e3,text:h,identifier:i,settings:c,notes:n},p={};this.preambleEmitted||(p.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(m,p)}}},Wee=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Ak=o(t=>{let e=Wee.exec(t);if(!e)throw new Error("Expected match.");return 3600*1e3*Number(e[1]||"0")+60*1e3*Number(e[2])+1e3*Number(e[3])+Number(e[4])},"parseSubtitleTimestamp"),Fk=o(t=>{let e=Math.floor(t/36e5),r=Math.floor(t%(3600*1e3)/(60*1e3)),n=Math.floor(t%(60*1e3)/1e3),i=t%1e3;return e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+n.toString().padStart(2,"0")+"."+i.toString().padStart(3,"0")},"formatSubtitleTimestamp")});var Wp,Je,Qs,Lt,Se,qI,jU,J,cc,Vl,qU,qo,YI,GI,qr,QI,YU,GU,QU,ye,et,r6,jp,n6,vd,jee,qee,Yee,Gee,Qee,Kee,Xee,KI,Jee,Zee,ete,tte,rte,nte,ite,ste,ote,ate,cte,lte,ute,fte,dte,KU,hte,mte,XI,lc,pte,gte,yte,bte,Ks,wte,xte,kte,Ste,lPt,Tte,vte,Ete,Cte,Pte,Ite,_te,Dte,Mte,JI,Ote,XU,Rte,Nte,Ate,Fte,i6,Lte,Bte,s6,o6,a6,zte,Ute,Xs,JU,ZU,$te,Hte,is,Vte,Wte,e6,jte,qte,Yte,t6,c6=he(()=>{Ue();Zt();Vp();ZI();sn();lr();Ti();Wp=class{static{o(this,"IsobmffBoxWriter")}constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let r=0;r<e.length;r++)this.helperView.setUint8(r%8,e.charCodeAt(r)),r%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let r=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let s of e.children)s&&this.writeBox(s);let n=this.writer.getPos(),i=e.size??n-r;this.writer.seek(r),this.writeBoxHeader(e,i),this.writer.seek(n)}}writeBoxHeader(e,r){this.writeU32(e.largeSize?1:r),this.writeAscii(e.type),e.largeSize&&this.writeU64(r)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let r=this.offsets.get(e);x(r!==void 0);let n=this.writer.getPos();this.writer.seek(r),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let r=this.measureBoxHeader(e);if(e.contents&&(r+=e.contents.byteLength),e.children)for(let n of e.children)n&&(r+=this.measureBox(n));return r}}},Je=new Uint8Array(8),Qs=new DataView(Je.buffer),Lt=o(t=>[(t%256+256)%256],"u8"),Se=o(t=>(Qs.setUint16(0,t,!1),[Je[0],Je[1]]),"u16"),qI=o(t=>(Qs.setInt16(0,t,!1),[Je[0],Je[1]]),"i16"),jU=o(t=>(Qs.setUint32(0,t,!1),[Je[1],Je[2],Je[3]]),"u24"),J=o(t=>(Qs.setUint32(0,t,!1),[Je[0],Je[1],Je[2],Je[3]]),"u32"),cc=o(t=>(Qs.setInt32(0,t,!1),[Je[0],Je[1],Je[2],Je[3]]),"i32"),Vl=o(t=>(Qs.setUint32(0,Math.floor(t/2**32),!1),Qs.setUint32(4,t,!1),[Je[0],Je[1],Je[2],Je[3],Je[4],Je[5],Je[6],Je[7]]),"u64"),qU=o(t=>(Qs.setInt16(0,2**8*t,!1),[Je[0],Je[1]]),"fixed_8_8"),qo=o(t=>(Qs.setInt32(0,2**16*t,!1),[Je[0],Je[1],Je[2],Je[3]]),"fixed_16_16"),YI=o(t=>(Qs.setInt32(0,2**30*t,!1),[Je[0],Je[1],Je[2],Je[3]]),"fixed_2_30"),GI=o((t,e)=>{let r=[],n=t;do{let i=n&127;n>>=7,r.length>0&&(i|=128),r.push(i),e!==void 0&&e--}while(n>0||e);return r.reverse()},"variableUnsignedInt"),qr=o((t,e=!1)=>{let r=Array(t.length).fill(null).map((n,i)=>t.charCodeAt(i));return e&&r.push(0),r},"ascii"),QI=o(t=>{let e=null;for(let r of t)(!e||r.timestamp>e.timestamp)&&(e=r);return e},"lastPresentedSample"),YU=o(t=>{let e=t*(Math.PI/180),r=Math.round(Math.cos(e)),n=Math.round(Math.sin(e));return[r,n,0,-n,r,0,0,0,1]},"rotationMatrix"),GU=YU(0),QU=o(t=>[qo(t[0]),qo(t[1]),YI(t[2]),qo(t[3]),qo(t[4]),YI(t[5]),qo(t[6]),qo(t[7]),YI(t[8])],"matrixToBytes"),ye=o((t,e,r)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:r}),"box"),et=o((t,e,r,n,i)=>ye(t,[Lt(e),jU(r),n??[]],i),"fullBox"),r6=o(t=>t.isQuickTime?ye("ftyp",[qr("qt "),J(512),qr("qt ")]):t.fragmented?ye("ftyp",[qr("iso5"),J(512),qr("iso5"),qr("iso6"),qr("mp41")]):ye("ftyp",[qr("isom"),J(512),qr("isom"),t.holdsAvc?qr("avc1"):[],qr("mp41")]),"ftyp"),jp=o(t=>({type:"mdat",largeSize:t}),"mdat"),n6=o(t=>({type:"free",size:t}),"free"),vd=o(t=>ye("moov",void 0,[jee(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>qee(e,t.creationTime)),t.isFragmented?Dte(t.trackDatas):null,zte(t)]),"moov"),jee=o((t,e)=>{let r=fr(Math.max(0,...e.filter(a=>a.samples.length>0).map(a=>{let c=QI(a.samples);return c.timestamp+c.duration})),Lk),n=Math.max(0,...e.map(a=>a.track.id))+1,i=!El(t)||!El(r),s=i?Vl:J;return et("mvhd",+i,0,[s(t),s(t),J(Lk),s(r),qo(1),qU(1),Array(10).fill(0),QU(GU),Array(24).fill(0),J(n)])},"mvhd"),qee=o((t,e)=>{let r=l6(t);return ye("trak",void 0,[Yee(t,e),Gee(t,e),r.name!==void 0?ye("udta",void 0,[ye("name",[...lt.encode(r.name)])]):null])},"trak"),Yee=o((t,e)=>{let r=QI(t.samples),n=fr(r?r.timestamp+r.duration:0,Lk),i=!El(e)||!El(n),s=i?Vl:J,a;if(t.type==="video"){let l=t.track.metadata.rotation;a=YU(l??0)}else a=GU;let c=2;return t.track.metadata.disposition?.default!==!1&&(c|=1),et("tkhd",+i,c,[s(e),s(e),J(t.track.id),J(0),s(n),Array(8).fill(0),Se(0),Se(t.track.id),qU(t.type==="audio"?1:0),Se(0),QU(a),qo(t.type==="video"?t.info.width:0),qo(t.type==="video"?t.info.height:0)])},"tkhd"),Gee=o((t,e)=>ye("mdia",void 0,[Qee(t,e),KI(!0,Kee[t.type],Xee[t.type]),Jee(t)]),"mdia"),Qee=o((t,e)=>{let r=QI(t.samples),n=fr(r?r.timestamp+r.duration:0,t.timescale),i=!El(e)||!El(n),s=i?Vl:J;return et("mdhd",+i,0,[s(e),s(e),J(t.timescale),s(n),Se(t6(t.track.metadata.languageCode??Ft)),Se(0)])},"mdhd"),Kee={video:"vide",audio:"soun",subtitle:"text"},Xee={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},KI=o((t,e,r,n="\0\0\0\0")=>et("hdlr",0,0,[t?qr("mhlr"):J(0),qr(e),qr(n),J(0),J(0),qr(r,!0)]),"hdlr"),Jee=o(t=>ye("minf",void 0,[rte[t.type](),nte(),ote(t)]),"minf"),Zee=o(()=>et("vmhd",0,1,[Se(0),Se(0),Se(0),Se(0)]),"vmhd"),ete=o(()=>et("smhd",0,0,[Se(0),Se(0)]),"smhd"),tte=o(()=>et("nmhd",0,0),"nmhd"),rte={video:Zee,audio:ete,subtitle:tte},nte=o(()=>ye("dinf",void 0,[ite()]),"dinf"),ite=o(()=>et("dref",0,0,[J(1)],[ste()]),"dref"),ste=o(()=>et("url ",0,1),"url"),ote=o(t=>{let e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(r=>r.sampleCompositionTimeOffset!==0);return ye("stbl",void 0,[ate(t),Tte(t),e?Ite(t):null,e?_te(t):null,Ete(t),Cte(t),Pte(t),vte(t)])},"stbl"),ate=o(t=>{let e;if(t.type==="video")e=cte(Vte(t.track.source._codec,t.info.decoderConfig.codec),t);else if(t.type==="audio"){let r=e6(t.track.source._codec,t.muxer.isQuickTime);x(r),e=mte(r,t)}else t.type==="subtitle"&&(e=kte(qte[t.track.source._codec],t));return x(e),et("stsd",0,0,[J(1)],[e])},"stsd"),cte=o((t,e)=>ye(t,[Array(6).fill(0),Se(1),Se(0),Se(0),Array(12).fill(0),Se(e.info.width),Se(e.info.height),J(4718592),J(4718592),J(0),Se(1),Array(32).fill(0),Se(24),qI(65535)],[Wte[e.track.source._codec](e),lte(e),kx(e.info.decoderConfig.colorSpace)?ute(e):null]),"videoSampleDescription"),lte=o(t=>t.info.pixelAspectRatio.num===t.info.pixelAspectRatio.den?null:ye("pasp",[J(t.info.pixelAspectRatio.num),J(t.info.pixelAspectRatio.den)]),"pasp"),ute=o(t=>ye("colr",[qr("nclx"),Se(ji[t.info.decoderConfig.colorSpace.primaries]),Se(qi[t.info.decoderConfig.colorSpace.transfer]),Se(Yi[t.info.decoderConfig.colorSpace.matrix]),Lt((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),"colr"),fte=o(t=>t.info.decoderConfig&&ye("avcC",[...qe(t.info.decoderConfig.description)]),"avcC"),dte=o(t=>t.info.decoderConfig&&ye("hvcC",[...qe(t.info.decoderConfig.description)]),"hvcC"),KU=o(t=>{if(!t.info.decoderConfig)return null;let e=t.info.decoderConfig,r=e.codec.split("."),n=Number(r[1]),i=Number(r[2]),s=Number(r[3]),a=r[4]?Number(r[4]):1,c=r[8]?Number(r[8]):Number(e.colorSpace?.fullRange??0),l=(s<<4)+(a<<1)+c,u=r[5]?Number(r[5]):e.colorSpace?.primaries?ji[e.colorSpace.primaries]:2,f=r[6]?Number(r[6]):e.colorSpace?.transfer?qi[e.colorSpace.transfer]:2,d=r[7]?Number(r[7]):e.colorSpace?.matrix?Yi[e.colorSpace.matrix]:2;return et("vpcC",1,0,[Lt(n),Lt(i),Lt(l),Lt(u),Lt(f),Lt(d),Se(0)])},"vpcC"),hte=o(t=>ye("av1C",Px(t.info.decoderConfig.codec)),"av1C"),mte=o((t,e)=>{let r=0,n,i=16,s=ht.includes(e.track.source._codec);if(s){let a=e.track.source._codec,{sampleSize:c}=_r(a);i=8*c,i>16&&(r=1)}if(e.muxer.isQuickTime&&(r=1),r===0)n=[Array(6).fill(0),Se(1),Se(r),Se(0),J(0),Se(e.info.numberOfChannels),Se(i),Se(0),Se(0),Se(e.info.sampleRate<2**16?e.info.sampleRate:0),Se(0)];else{let a=s?0:-2;n=[Array(6).fill(0),Se(1),Se(r),Se(0),J(0),Se(e.info.numberOfChannels),Se(Math.min(i,16)),qI(a),Se(0),Se(e.info.sampleRate<2**16?e.info.sampleRate:0),Se(0),s?[J(1),J(i/8),J(e.info.numberOfChannels*i/8)]:[J(0),J(0),J(0)],J(2)]}return ye(t,n,[jte(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},"soundSampleDescription"),XI=o(t=>{let e;switch(t.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${t.track.source._codec}`)}let r=[...Lt(e),...Lt(21),...jU(0),...J(0),...J(0)];if(t.info.decoderConfig.description){let n=qe(t.info.decoderConfig.description);r=[...r,...Lt(5),...GI(n.byteLength),...n]}return r=[...Se(1),...Lt(0),...Lt(4),...GI(r.length),...r,...Lt(6),...Lt(1),...Lt(2)],r=[...Lt(3),...GI(r.length),...r],et("esds",0,0,r)},"esds"),lc=o(t=>ye("wave",void 0,[pte(t),gte(t),ye("\0\0\0\0")]),"wave"),pte=o(t=>ye("frma",[qr(e6(t.track.source._codec,t.muxer.isQuickTime))]),"frma"),gte=o(t=>{let{littleEndian:e}=_r(t.track.source._codec);return ye("enda",[Se(+e)])},"enda"),yte=o(t=>{let e=t.info.numberOfChannels,r=3840,n=t.info.sampleRate,i=0,s=0,a=new Uint8Array(0),c=t.info.decoderConfig?.description;if(c){x(c.byteLength>=18);let l=qe(c),u=Ja(l);e=u.outputChannelCount,r=u.preSkip,n=u.inputSampleRate,i=u.outputGain,s=u.channelMappingFamily,u.channelMappingTable&&(a=u.channelMappingTable)}return ye("dOps",[Lt(0),Lt(e),Se(r),J(n),qI(i),Lt(s),...a])},"dOps"),bte=o(t=>{let e=t.info.decoderConfig?.description;x(e);let r=qe(e);return et("dfLa",0,0,[...r.subarray(4)])},"dfLa"),Ks=o(t=>{let{littleEndian:e,sampleSize:r}=_r(t.track.source._codec),n=+e;return et("pcmC",0,0,[Lt(n),Lt(8*r)])},"pcmC"),wte=o(t=>{let e=$x(t.info.firstPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");let r=new Uint8Array(3),n=new Te(r);return n.writeBits(2,e.fscod),n.writeBits(5,e.bsid),n.writeBits(3,e.bsmod),n.writeBits(3,e.acmod),n.writeBits(1,e.lfeon),n.writeBits(5,e.bitRateCode),n.writeBits(5,0),ye("dac3",[...r])},"dac3"),xte=o(t=>{let e=Hx(t.info.firstPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let r=16;for(let a of e.substreams)r+=23,a.numDepSub>0?r+=9:r+=1;let n=Math.ceil(r/8),i=new Uint8Array(n),s=new Te(i);s.writeBits(13,e.dataRate),s.writeBits(3,e.substreams.length-1);for(let a of e.substreams)s.writeBits(2,a.fscod),s.writeBits(5,a.bsid),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(3,a.bsmod),s.writeBits(3,a.acmod),s.writeBits(1,a.lfeon),s.writeBits(3,0),s.writeBits(4,a.numDepSub),a.numDepSub>0?s.writeBits(9,a.chanLoc):s.writeBits(1,0);return ye("dec3",[...i])},"dec3"),kte=o((t,e)=>ye(t,[Array(6).fill(0),Se(1)],[Yte[e.track.source._codec](e)]),"subtitleSampleDescription"),Ste=o(t=>ye("vttC",[...lt.encode(t.info.config.description)]),"vttC"),lPt=o(t=>et("txtC",0,0,[...t,0]),"txtC"),Tte=o(t=>et("stts",0,0,[J(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[J(e.sampleCount),J(e.sampleDelta)])]),"stts"),vte=o(t=>{if(t.samples.every(r=>r.type==="key"))return null;let e=[...t.samples.entries()].filter(([,r])=>r.type==="key");return et("stss",0,0,[J(e.length),e.map(([r])=>J(r+1))])},"stss"),Ete=o(t=>et("stsc",0,0,[J(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[J(e.firstChunk),J(e.samplesPerChunk),J(1)])]),"stsc"),Cte=o(t=>{if(t.type==="audio"&&t.info.requiresPcmTransformation){let{sampleSize:e}=_r(t.track.source._codec);return et("stsz",0,0,[J(e*t.info.numberOfChannels),J(t.samples.reduce((r,n)=>r+fr(n.duration,t.timescale),0))])}return et("stsz",0,0,[J(0),J(t.samples.length),t.samples.map(e=>J(e.size))])},"stsz"),Pte=o(t=>t.finalizedChunks.length>0&&Ze(t.finalizedChunks).offset>=2**32?et("co64",0,0,[J(t.finalizedChunks.length),t.finalizedChunks.map(e=>Vl(e.offset))]):et("stco",0,0,[J(t.finalizedChunks.length),t.finalizedChunks.map(e=>J(e.offset))]),"stco"),Ite=o(t=>et("ctts",1,0,[J(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[J(e.sampleCount),cc(e.sampleCompositionTimeOffset)])]),"ctts"),_te=o(t=>{let e=1/0,r=-1/0,n=1/0,i=-1/0;x(t.compositionTimeOffsetTable.length>0),x(t.samples.length>0);for(let a=0;a<t.compositionTimeOffsetTable.length;a++){let c=t.compositionTimeOffsetTable[a];e=Math.min(e,c.sampleCompositionTimeOffset),r=Math.max(r,c.sampleCompositionTimeOffset)}for(let a=0;a<t.samples.length;a++){let c=t.samples[a];n=Math.min(n,fr(c.timestamp,t.timescale)),i=Math.max(i,fr(c.timestamp+c.duration,t.timescale))}let s=Math.max(-e,0);return i>=2**31?null:et("cslg",0,0,[cc(s),cc(e),cc(r),cc(n),cc(i)])},"cslg"),Dte=o(t=>ye("mvex",void 0,t.map(Mte)),"mvex"),Mte=o(t=>et("trex",0,0,[J(t.track.id),J(1),J(0),J(0),J(0)]),"trex"),JI=o((t,e)=>ye("moof",void 0,[Ote(t),...e.map(Rte)]),"moof"),Ote=o(t=>et("mfhd",0,0,[J(t)]),"mfhd"),XU=o(t=>{let e=0,r=0,n=0,i=0,s=t.type==="delta";return r|=+s,s?e|=1:e|=2,e<<24|r<<16|n<<8|i},"fragmentSampleFlags"),Rte=o(t=>ye("traf",void 0,[Nte(t),Ate(t),Fte(t)]),"traf"),Nte=o(t=>{x(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;let r=t.currentChunk.samples[1]??t.currentChunk.samples[0],n={duration:r.timescaleUnitsToNextSample,size:r.size,flags:XU(r)};return et("tfhd",0,e,[J(t.track.id),J(n.duration),J(n.size),J(n.flags)])},"tfhd"),Ate=o(t=>(x(t.currentChunk),et("tfdt",1,0,[Vl(fr(t.currentChunk.startTimestamp,t.timescale))])),"tfdt"),Fte=o(t=>{x(t.currentChunk);let e=t.currentChunk.samples.map(g=>g.timescaleUnitsToNextSample),r=t.currentChunk.samples.map(g=>g.size),n=t.currentChunk.samples.map(XU),i=t.currentChunk.samples.map(g=>fr(g.timestamp-g.decodeTimestamp,t.timescale)),s=new Set(e),a=new Set(r),c=new Set(n),l=new Set(i),u=c.size===2&&n[0]!==n[1],f=s.size>1,d=a.size>1,h=!u&&c.size>1,m=l.size>1||[...l].some(g=>g!==0),p=0;return p|=1,p|=4*+u,p|=256*+f,p|=512*+d,p|=1024*+h,p|=2048*+m,et("trun",1,p,[J(t.currentChunk.samples.length),J(t.currentChunk.offset-t.currentChunk.moofOffset||0),u?J(n[0]):[],t.currentChunk.samples.map((g,y)=>[f?J(e[y]):[],d?J(r[y]):[],h?J(n[y]):[],m?cc(i[y]):[]])])},"trun"),i6=o(t=>ye("mfra",void 0,[...t.map(Lte),Bte()]),"mfra"),Lte=o((t,e)=>et("tfra",1,0,[J(t.track.id),J(63),J(t.finalizedChunks.length),t.finalizedChunks.map(n=>[Vl(fr(n.samples[0].timestamp,t.timescale)),Vl(n.moofOffset),J(e+1),J(1),J(1)])]),"tfra"),Bte=o(()=>et("mfro",0,0,[J(0)]),"mfro"),s6=o(()=>ye("vtte"),"vtte"),o6=o((t,e,r,n,i)=>ye("vttc",void 0,[i!==null?ye("vsid",[cc(i)]):null,r!==null?ye("iden",[...lt.encode(r)]):null,e!==null?ye("ctim",[...lt.encode(Fk(e))]):null,n!==null?ye("sttg",[...lt.encode(n)]):null,ye("payl",[...lt.encode(t)])]),"vttc"),a6=o(t=>ye("vtta",[...lt.encode(t)]),"vtta"),zte=o(t=>{let e=[],r=t.format._options.metadataFormat??"auto",n=t.output._metadataTags;if(r==="mdir"||r==="auto"&&!t.isQuickTime){let i=$te(n);i&&e.push(i)}else if(r==="mdta"){let i=Hte(n);i&&e.push(i)}else(r==="udta"||r==="auto"&&t.isQuickTime)&&Ute(e,t.output._metadataTags);return e.length===0?null:ye("udta",void 0,e)},"udta"),Ute=o((t,e)=>{for(let{key:r,value:n}of Gi(e))switch(r){case"title":t.push(Xs("\xA9nam",n));break;case"description":t.push(Xs("\xA9des",n));break;case"artist":t.push(Xs("\xA9ART",n));break;case"album":t.push(Xs("\xA9alb",n));break;case"albumArtist":t.push(Xs("albr",n));break;case"genre":t.push(Xs("\xA9gen",n));break;case"date":t.push(Xs("\xA9day",n.toISOString().slice(0,10)));break;case"comment":t.push(Xs("\xA9cmt",n));break;case"lyrics":t.push(Xs("\xA9lyr",n));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:kt(r)}if(e.raw)for(let r in e.raw){let n=e.raw[r];n==null||r.length!==4||t.some(i=>i.type===r)||(typeof n=="string"?t.push(Xs(r,n)):n instanceof Uint8Array&&t.push(ye(r,Array.from(n))))}},"addQuickTimeMetadataTagBoxes"),Xs=o((t,e)=>{let r=lt.encode(e);return ye(t,[Se(r.length),Se(t6("und")),Array.from(r)])},"metadataTagStringBoxShort"),JU={"image/jpeg":13,"image/png":14,"image/bmp":27},ZU=o((t,e)=>{let r=[];for(let{key:n,value:i}of Gi(t))switch(n){case"title":r.push({key:e?"title":"\xA9nam",value:is(i)});break;case"description":r.push({key:e?"description":"\xA9des",value:is(i)});break;case"artist":r.push({key:e?"artist":"\xA9ART",value:is(i)});break;case"album":r.push({key:e?"album":"\xA9alb",value:is(i)});break;case"albumArtist":r.push({key:e?"album_artist":"aART",value:is(i)});break;case"comment":r.push({key:e?"comment":"\xA9cmt",value:is(i)});break;case"genre":r.push({key:e?"genre":"\xA9gen",value:is(i)});break;case"lyrics":r.push({key:e?"lyrics":"\xA9lyr",value:is(i)});break;case"date":r.push({key:e?"date":"\xA9day",value:is(i.toISOString().slice(0,10))});break;case"images":for(let s of i)s.kind==="coverFront"&&r.push({key:"covr",value:ye("data",[J(JU[s.mimeType]??0),J(0),Array.from(s.data)])});break;case"trackNumber":if(e){let s=t.tracksTotal!==void 0?`${i}/${t.tracksTotal}`:i.toString();r.push({key:"track",value:is(s)})}else r.push({key:"trkn",value:ye("data",[J(0),J(0),Se(0),Se(i),Se(t.tracksTotal??0),Se(0)])});break;case"discNumber":e||r.push({key:"disc",value:ye("data",[J(0),J(0),Se(0),Se(i),Se(t.discsTotal??0),Se(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:kt(n)}if(t.raw)for(let n in t.raw){let i=t.raw[n];i==null||!e&&n.length!==4||r.some(s=>s.key===n)||(typeof i=="string"?r.push({key:n,value:is(i)}):i instanceof Uint8Array?r.push({key:n,value:ye("data",[J(0),J(0),Array.from(i)])}):i instanceof Gn&&r.push({key:n,value:ye("data",[J(JU[i.mimeType]??0),J(0),Array.from(i.data)])}))}return r},"generateMetadataPairs"),$te=o(t=>{let e=ZU(t,!1);return e.length===0?null:et("meta",0,0,void 0,[KI(!1,"mdir","","appl"),ye("ilst",void 0,e.map(r=>ye(r.key,void 0,[r.value])))])},"metaMdir"),Hte=o(t=>{let e=ZU(t,!0);return e.length===0?null:ye("meta",void 0,[KI(!1,"mdta",""),et("keys",0,0,[J(e.length)],e.map(r=>ye("mdta",[...lt.encode(r.key)]))),ye("ilst",void 0,e.map((r,n)=>{let i=String.fromCharCode(...J(n+1));return ye(i,void 0,[r.value])}))])},"metaMdta"),is=o(t=>ye("data",[J(1),J(0),...lt.encode(t)]),"dataStringBoxLong"),Vte=o((t,e)=>{switch(t){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},"videoCodecToBoxName"),Wte={avc:fte,hevc:dte,vp8:KU,vp9:KU,av1:hte},e6=o((t,e)=>{switch(t){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3"}if(e)switch(t){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(t){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},"audioCodecToBoxName"),jte=o((t,e)=>{switch(t){case"aac":return XI;case"mp3":return XI;case"opus":return yte;case"vorbis":return XI;case"flac":return bte;case"ac3":return wte;case"eac3":return xte}if(e)switch(t){case"pcm-s24":return lc;case"pcm-s24be":return lc;case"pcm-s32":return lc;case"pcm-s32be":return lc;case"pcm-f32":return lc;case"pcm-f32be":return lc;case"pcm-f64":return lc;case"pcm-f64be":return lc}else switch(t){case"pcm-s16":return Ks;case"pcm-s16be":return Ks;case"pcm-s24":return Ks;case"pcm-s24be":return Ks;case"pcm-s32":return Ks;case"pcm-s32be":return Ks;case"pcm-f32":return Ks;case"pcm-f32be":return Ks;case"pcm-f64":return Ks;case"pcm-f64be":return Ks}return null},"audioCodecToConfigurationBox"),qte={webvtt:"wvtt"},Yte={webvtt:Ste},t6=o(t=>{x(t.length===3);let e=0;for(let r=0;r<3;r++)e<<=5,e+=t.charCodeAt(r)-96;return e},"getLanguageCodeInt")});var qp,e_,t_,Ed,Gte,Qte,Bk,zk,r_=he(()=>{Ue();qp=class{static{o(this,"Writer")}constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let r=this.getPos();if(r<this.trackedStart){if(r+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-r),r=0}let n=r+e.byteLength-this.trackedStart,i=this.trackedWrites.byteLength;for(;i<n;)i*=2;if(i!==this.trackedWrites.byteLength){let s=new Uint8Array(i);s.set(this.trackedWrites,0),this.trackedWrites=s}this.trackedWrites.set(e,r-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,r+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");let r={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,r}},e_=2**16,t_=2**32,Ed=class extends qp{static{o(this,"BufferTargetWriter")}constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(e_,{maxByteLength:t_})}catch{this.buffer=new ArrayBuffer(e_),this.supportsResize=!1}else this.buffer=new ArrayBuffer(e_);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let r=this.buffer.byteLength;for(;r<e;)r*=2;if(r!==this.buffer.byteLength){if(r>t_)throw new Error(`ArrayBuffer exceeded maximum size of ${t_} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(r);else{let n=new ArrayBuffer(r),i=new Uint8Array(n);i.set(this.bytes,0),this.buffer=n,this.bytes=i}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,r){return this.bytes.slice(e,r)}},Gte=2**24,Qte=2,Bk=class extends qp{static{o(this,"StreamTargetWriter")}constructor(e){super(),this.pos=0,this.sections=[],this.lastWriteEnd=0,this.lastFlushEnd=0,this.writer=null,this.writeError=null,this.chunks=[],this.target=e,this.chunked=e._options.chunked??!1,this.chunkSize=e._options.chunkSize??Gte}start(){this.writer=this.target._writable.getWriter()}write(e){if(this.pos>this.lastWriteEnd){let r=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(r))}this.maybeTrackWrites(e),this.sections.push({data:e.slice(),start:this.pos}),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.lastWriteEnd=Math.max(this.lastWriteEnd,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){if(this.writeError!==null)throw this.writeError;if(this.pos>this.lastWriteEnd){let n=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(n))}if(x(this.writer),this.sections.length===0)return;let e=[],r=[...this.sections].sort((n,i)=>n.start-i.start);e.push({start:r[0].start,size:r[0].data.byteLength});for(let n=1;n<r.length;n++){let i=e[e.length-1],s=r[n];s.start<=i.start+i.size?i.size=Math.max(i.size,s.start+s.data.byteLength-i.start):e.push({start:s.start,size:s.data.byteLength})}for(let n of e){n.data=new Uint8Array(n.size);for(let i of this.sections)n.start<=i.start&&i.start<n.start+n.size&&n.data.set(i.data,i.start-n.start);if(this.writer.desiredSize!==null&&this.writer.desiredSize<=0&&await this.writer.ready,this.chunked)this.writeDataIntoChunks(n.data,n.start),this.tryToFlushChunks();else{if(this.ensureMonotonicity&&n.start!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:n.data,position:n.start}).catch(i=>{this.writeError??=i}),this.lastFlushEnd=n.start+n.data.byteLength}}this.sections.length=0}writeDataIntoChunks(e,r){let n=this.chunks.findIndex(l=>l.start<=r&&r<l.start+this.chunkSize);n===-1&&(n=this.createChunk(r));let i=this.chunks[n],s=r-i.start,a=e.subarray(0,Math.min(this.chunkSize-s,e.byteLength));i.data.set(a,s);let c={start:s,end:s+a.byteLength};if(this.insertSectionIntoChunk(i,c),i.written[0].start===0&&i.written[0].end===this.chunkSize&&(i.shouldFlush=!0),this.chunks.length>Qte){for(let l=0;l<this.chunks.length-1;l++)this.chunks[l].shouldFlush=!0;this.tryToFlushChunks()}a.byteLength<e.byteLength&&this.writeDataIntoChunks(e.subarray(a.byteLength),r+a.byteLength)}insertSectionIntoChunk(e,r){let n=0,i=e.written.length-1,s=-1;for(;n<=i;){let a=Math.floor(n+(i-n+1)/2);e.written[a].start<=r.start?(n=a+1,s=a):i=a-1}for(e.written.splice(s+1,0,r),(s===-1||e.written[s].end<r.start)&&s++;s<e.written.length-1&&e.written[s].end>=e.written[s+1].start;)e.written[s].end=Math.max(e.written[s].end,e.written[s+1].end),e.written.splice(s+1,1)}createChunk(e){let n={start:Math.floor(e/this.chunkSize)*this.chunkSize,data:new Uint8Array(this.chunkSize),written:[],shouldFlush:!1};return this.chunks.push(n),this.chunks.sort((i,s)=>i.start-s.start),this.chunks.indexOf(n)}tryToFlushChunks(e=!1){x(this.writer);for(let r=0;r<this.chunks.length;r++){let n=this.chunks[r];if(!(!n.shouldFlush&&!e)){for(let i of n.written){let s=n.start+i.start;if(this.ensureMonotonicity&&s!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:n.data.subarray(i.start,i.end),position:s}).catch(a=>{this.writeError??=a}),this.lastFlushEnd=n.start+i.end}this.chunks.splice(r--,1)}}}async finalize(){if(this.chunked&&this.tryToFlushChunks(!0),this.writeError!==null)throw this.writeError;return x(this.writer),await this.writer.ready,this.writer.close()}async close(){return this.writer?.close()}},zk=class extends qp{static{o(this,"NullTargetWriter")}constructor(e){super(),this.target=e,this.pos=0}write(e){this.maybeTrackWrites(e),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength}getPos(){return this.pos}seek(e){this.pos=e}async flush(){}async finalize(){}async close(){}}});var u6,Kte,Js,Cd,Yp,Uk,Pd,Gp=he(()=>{r_();u6=us(HI(),1);Ue();Kte=typeof u6<"u"?u6:void 0,Js=class{static{o(this,"Target")}constructor(){this._output=null,this.onwrite=null}},Cd=class extends Js{static{o(this,"BufferTarget")}constructor(){super(...arguments),this.buffer=null}_createWriter(){return new Ed(this)}},Yp=class extends Js{static{o(this,"StreamTarget")}constructor(e,r={}){if(super(),!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(r!=null&&typeof r!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(r.chunked!==void 0&&typeof r.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(r.chunkSize!==void 0&&(!Number.isInteger(r.chunkSize)||r.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=r}_createWriter(){return new Bk(this)}},Uk=class extends Js{static{o(this,"FilePathTarget")}constructor(e,r={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");super(),this._fileHandle=null;let n=new WritableStream({start:o(async()=>{this._fileHandle=await Kte.fs.open(e,"w")},"start"),write:o(async i=>{x(this._fileHandle),await this._fileHandle.write(i.data,0,i.data.byteLength,i.position)},"write"),close:o(async()=>{this._fileHandle&&(await this._fileHandle.close(),this._fileHandle=null)},"close")});this._streamTarget=new Yp(n,{chunked:!0,...r}),this._streamTarget._output=this._output}_createWriter(){return this._streamTarget._createWriter()}},Pd=class extends Js{static{o(this,"NullTarget")}_createWriter(){return new zk(this)}}});var Lk,Xte,l6,fr,$k,ZI=he(()=>{c6();jo();r_();Ue();Id();Vp();qs();Zt();gd();qt();Gp();sn();nI();iI();Lk=1e3,Xte=2082844800,l6=o(t=>{let e={},r=t.track;return r.metadata.name!==void 0&&(e.name=r.metadata.name),e},"getTrackMetadata"),fr=o((t,e,r=!0)=>{let n=t*e;return r?Math.round(n):n},"intoTimescale"),$k=class extends Sr{static{o(this,"IsobmffMuxer")}constructor(e,r){super(e),this.auxTarget=new Cd,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new Wp(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=ut(),this.creationTime=Math.floor(Date.now()/1e3)+Xte,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=r,this.writer=e._writer,this.boxWriter=new Wp(this.writer),this.isQuickTime=r instanceof Wl;let n=this.writer instanceof Ed?"in-memory":!1;this.fastStart=r._options.fastStart??n,this.isFragmented=this.fastStart==="fragmented",(this.fastStart==="in-memory"||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=r._options.minimumFragmentDuration??1}async start(){let e=await this.mutex.acquire(),r=this.output._tracks.some(n=>n.type==="video"&&n.source._codec==="avc");if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r6({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented})),this.format._options.onFtyp){let{data:n,start:i}=this.writer.stopTrackingWrites();this.format._options.onFtyp(n,i)}if(this.ftypSize=this.writer.getPos(),this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(let n of this.output._tracks)if(n.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=jp(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Gx({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,n){let i=this.trackDatas.find(h=>h.track===e);if(i)return i;Kf(n),x(n),x(n.decoderConfig);let s={...n.decoderConfig};x(s.codedWidth!==void 0),x(s.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!s.description){let h=Jf(r.data);if(!h)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=Kz(h),a=!0}else if(e.source._codec==="hevc"&&!s.description){let h=Zf(r.data);if(!h)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=Xz(h),a=!0}let c=Ez(1/(e.metadata.frameRate??57600),1e6).denominator,l=s.displayAspectWidth,u=s.displayAspectHeight,f=l===void 0||u===void 0?{num:1,den:1}:qa({num:l*s.codedHeight,den:u*s.codedWidth}),d={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:f,decoderConfig:s,requiresAnnexBTransformation:a},timescale:c,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(d),this.trackDatas.sort((h,m)=>h.track.id-m.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,r,n){let i=this.trackDatas.find(l=>l.track===e);if(i)return i;En(n),x(n),x(n.decoderConfig);let s={...n.decoderConfig},a=!1;if(e.source._codec==="aac"&&!s.description){let l=Dn(xr.tempFromBytes(r.data));if(!l)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let u=vi[l.samplingFrequencyIndex],f=Ws[l.channelConfiguration];if(u===void 0||f===void 0)throw new Error("Invalid ADTS frame header.");s.description=Yf({objectType:l.objectType,sampleRate:u,numberOfChannels:f}),a=!0}let c={muxer:this,track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&ht.includes(e.source._codec),requiresAdtsStripping:a,firstPacket:r},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(c),this.trackDatas.sort((l,u)=>l.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Ix(r),x(r),x(r.config);let i={muxer:this,track:e,type:"subtitle",info:{config:r.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(i),this.trackDatas.sort((s,a)=>s.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,r,n){let i=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,n),a=r.data;if(s.info.requiresAnnexBTransformation){let u=[...Xa(a)].map(f=>a.subarray(f.offset,f.offset+f.length));if(u.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=qP(u,4)}let c=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),l=this.createSampleForTrack(s,a,c,r.duration,r.type);await this.registerSample(s,l)}finally{i()}}async addEncodedAudioPacket(e,r,n){let i=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,n),a=r.data;if(s.info.requiresAdtsStripping){let u=Dn(xr.tempFromBytes(a));if(!u)throw new Error("Expected ADTS frame, didn't get one.");let f=u.crcCheck===null?Wo:Jn;a=a.subarray(f)}let c=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),l=this.createSampleForTrack(s,a,c,r.duration,r.type);s.info.requiresPcmTransformation&&await this.maybePadWithSilence(s,c),await this.registerSample(s,l)}finally{i()}}async maybePadWithSilence(e,r){let n=Ze(e.samples),i=n?n.timestamp+n.duration:0,s=r-i,a=fr(s,e.timescale);if(a>0){let{sampleSize:c,silentValue:l}=_r(e.info.decoderConfig.codec),u=a*e.info.numberOfChannels,f=new Uint8Array(c*u).fill(l),d=this.createSampleForTrack(e,new Uint8Array(f.buffer),i,s,"key");await this.registerSample(e,d)}}async addSubtitleCue(e,r,n){let i=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n);this.validateAndNormalizeTimestamp(s.track,r.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(r),await this.processWebVTTCues(s,r.timestamp))}finally{i()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){let n=new Set([]);for(let u of e.cueQueue)x(u.timestamp<=r),x(e.lastCueEndTimestamp<=u.timestamp+u.duration),n.add(Math.max(u.timestamp,e.lastCueEndTimestamp)),n.add(u.timestamp+u.duration);let i=[...n].sort((u,f)=>u-f),s=i[0],a=i[1]??s;if(r<a)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);let u=s6();this.auxBoxWriter.writeBox(u);let f=this.auxWriter.getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,f,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let u=0;u<e.cueQueue.length;u++){let f=e.cueQueue[u];if(f.timestamp>=a)break;Td.lastIndex=0;let d=Td.test(f.text),h=f.timestamp+f.duration,m=e.cueToSourceId.get(f);if(m===void 0&&a<h&&(m=e.nextSourceId++,e.cueToSourceId.set(f,m)),f.notes){let g=a6(f.notes);this.auxBoxWriter.writeBox(g)}let p=o6(f.text,d?s:null,f.identifier??null,f.settings??null,m??null);this.auxBoxWriter.writeBox(p),h===a&&e.cueQueue.splice(u--,1)}let c=this.auxWriter.getSlice(0,this.auxWriter.getPos()),l=this.createSampleForTrack(e,c,s,a-s,"key");await this.registerSample(e,l),e.lastCueEndTimestamp=a}}createSampleForTrack(e,r,n,i,s){return{timestamp:n,decodeTimestamp:n,duration:i,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:fr(i,e.timescale)}}processTimestamps(e,r){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){let i=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){let a=e.timestampProcessingQueue[s],c=fr(a.duration,e.timescale);i+=c}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:i,sampleDelta:1});else{let s=Ze(e.timeToSampleTable);s.sampleCount+=i}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(i=>i.timestamp).sort((i,s)=>i-s);for(let i=0;i<e.timestampProcessingQueue.length;i++){let s=e.timestampProcessingQueue[i];s.decodeTimestamp=n[i],!this.isFragmented&&e.lastTimescaleUnits===null&&(s.decodeTimestamp=0);let a=fr(s.timestamp-s.decodeTimestamp,e.timescale),c=fr(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){x(e.lastSample);let l=fr(s.decodeTimestamp,e.timescale,!1),u=Math.round(l-e.lastTimescaleUnits);if(x(u>=0),e.lastTimescaleUnits+=u,e.lastSample.timescaleUnitsToNextSample=u,!this.isFragmented){let f=Ze(e.timeToSampleTable);if(x(f),f.sampleCount===1){f.sampleDelta=u;let h=e.timeToSampleTable[e.timeToSampleTable.length-2];h&&h.sampleDelta===u&&(h.sampleCount++,e.timeToSampleTable.pop(),f=h)}else f.sampleDelta!==u&&(f.sampleCount--,e.timeToSampleTable.push(f={sampleCount:1,sampleDelta:u}));f.sampleDelta===c?f.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:c});let d=Ze(e.compositionTimeOffsetTable);x(d),d.sampleCompositionTimeOffset===a?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=fr(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:c}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,x(e.lastSample),x(e.lastTimescaleUnits!==null),r!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){x(r.type==="key");let i=fr(r.timestamp,e.timescale,!1),s=Math.round(i-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,r){r.type==="key"&&this.processTimestamps(e,r),e.timestampProcessingQueue.push(r),this.isFragmented?(e.sampleQueue.push(r),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,r):await this.addSampleToTrack(e,r)}async addSampleToTrack(e,r){if(!this.isFragmented&&(e.samples.push(r),this.fastStart==="reserve")){let i=e.track.metadata.maximumPacketCount;if(x(i!==void 0),e.samples.length>i)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${i}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,r.timestamp);let i=r.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let s=this.trackDatas.every(a=>{if(e===a)return r.type==="key";let c=a.sampleQueue[0];return c?c.type==="key":a.track.source._closed});i>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=i>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}),x(e.currentChunk),e.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(e){if(x(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let r=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(r=e.currentChunk.samples.reduce((n,i)=>n+fr(i.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||Ze(e.compactlyCodedChunkTable).samplesPerChunk!==r)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let n of e.currentChunk.samples)x(n.data),this.writer.write(n.data),n.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(x(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let r=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.track.source._closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<n&&(r=s,n=s.sampleQueue[0].timestamp)}if(!r)break;let i=r.sampleQueue.shift();await this.addSampleToTrack(r,i)}}async finalizeFragment(e=!0){x(this.isFragmented);let r=this.nextFragmentNumber++;if(r===1){this.format._options.onMoov&&this.writer.startTrackingWrites();let m=vd(this);if(this.boxWriter.writeBox(m),this.format._options.onMoov){let{data:p,start:g}=this.writer.stopTrackingWrites();this.format._options.onMoov(p,g)}}let n=this.trackDatas.filter(m=>m.currentChunk),i=JI(r,n),s=this.writer.getPos(),a=s+this.boxWriter.measureBox(i),c=a+Ji,l=1/0;for(let m of n){m.currentChunk.offset=c,m.currentChunk.moofOffset=s;for(let p of m.currentChunk.samples)c+=p.size;l=Math.min(l,m.currentChunk.startTimestamp)}let u=c-a,f=u>=2**32;if(f)for(let m of n)m.currentChunk.offset+=zo-Ji;this.format._options.onMoof&&this.writer.startTrackingWrites();let d=JI(r,n);if(this.boxWriter.writeBox(d),this.format._options.onMoof){let{data:m,start:p}=this.writer.stopTrackingWrites();this.format._options.onMoof(m,p,l)}x(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();let h=jp(f);h.size=u,this.boxWriter.writeBox(h),this.writer.seek(a+(f?zo:Ji));for(let m of n)for(let p of m.currentChunk.samples)this.writer.write(p.data),p.data=null;if(this.format._options.onMdat){let{data:m,start:p}=this.writer.stopTrackingWrites();this.format._options.onMdat(m,p)}for(let m of n)m.finalizedChunks.push(m.currentChunk),this.finalizedChunks.push(m.currentChunk),m.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,r){if(this.allTracksAreKnown()){if(!this.mdat){let n=vd(this),s=this.boxWriter.measureBox(n)+this.computeSampleTableSizeUpperBound()+4096;x(this.ftypSize!==null),this.writer.seek(this.ftypSize+s),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=jp(!0),this.boxWriter.writeBox(this.mdat);for(let a of this.trackDatas){for(let c of a.sampleQueue)await this.addSampleToTrack(a,c);a.sampleQueue.length=0}}await this.addSampleToTrack(e,r)}else e.sampleQueue.push(r)}computeSampleTableSizeUpperBound(){x(this.fastStart==="reserve");let e=0;for(let r of this.trackDatas){let n=r.track.metadata.maximumPacketCount;x(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(i=>i.track===e);n&&(n.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let r of this.trackDatas)await this.finalizeCurrentChunk(r);if(this.fastStart==="in-memory"){this.mdat=jp(!1);let r;for(let i=0;i<2;i++){let s=vd(this),a=this.boxWriter.measureBox(s);r=this.boxWriter.measureBox(this.mdat);let c=this.writer.getPos()+a+r;for(let l of this.finalizedChunks){l.offset=c;for(let{data:u}of l.samples)x(u),c+=u.byteLength,r+=u.byteLength}if(c<2**32)break;r>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let n=vd(this);if(this.boxWriter.writeBox(n),this.format._options.onMoov){let{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onMoov(i,s)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(let i of this.finalizedChunks)for(let s of i.samples)x(s.data),this.writer.write(s.data),s.data=null;if(this.format._options.onMdat){let{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(i,s)}}else if(this.isFragmented){let r=this.writer.getPos(),n=i6(this.trackDatas);this.boxWriter.writeBox(n);let i=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(i)}else{x(this.mdat);let r=this.boxWriter.offsets.get(this.mdat);x(r!==void 0);let n=this.writer.getPos()-r;if(this.mdat.size=n,this.mdat.largeSize=n>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,a)}let i=vd(this);if(this.fastStart==="reserve"){x(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);let s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(n6(s))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);if(this.format._options.onMoov){let{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,a)}}e()}}});var Jte,Zte,f6,d6,h6,ere,Hk,m6=he(()=>{Ti();Ue();ik();hI();Id();Vp();qs();Zt();gd();qt();jo();sn();lr();Jte=-(2**15),Zte=2**15-1,f6="Mediabunny",d6=6,h6=5,ere={video:1,audio:2,subtitle:17},Hk=class extends Sr{static{o(this,"MatroskaMuxer")}constructor(e,r){super(e),this.trackDatas=[],this.allTracksKnown=ut(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=new Map,this.duration=0,this.writer=e._writer,this.format=r,this.ebmlWriter=new ek(this.writer),this.format._options.appendOnly&&(this.writer.ensureMonotonicity=!0)}async start(){let e=await this.mutex.acquire();this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();let e={id:I.EBML,data:[{id:I.EBMLVersion,data:1},{id:I.EBMLReadVersion,data:1},{id:I.EBMLMaxIDLength,data:4},{id:I.EBMLMaxSizeLength,data:8},{id:I.DocType,data:this.format instanceof jl?"webm":"matroska"},{id:I.DocTypeVersion,data:2},{id:I.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){let{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(r,n)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;let r=new Uint8Array([28,83,187,107]),n=new Uint8Array([21,73,169,102]),i=new Uint8Array([22,84,174,107]),s=new Uint8Array([25,65,164,105]),a=new Uint8Array([18,84,195,103]),c={id:I.SeekHead,data:[{id:I.Seek,data:[{id:I.SeekID,data:r},{id:I.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:I.Seek,data:[{id:I.SeekID,data:n},{id:I.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:I.Seek,data:[{id:I.SeekID,data:i},{id:I.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:I.Seek,data:[{id:I.SeekID,data:s},{id:I.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:I.Seek,data:[{id:I.SeekID,data:a},{id:I.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=c}createSegmentInfo(){let e={id:I.Duration,data:new cd(0)};this.segmentDuration=e;let r={id:I.Info,data:[{id:I.TimestampScale,data:1e6},{id:I.MuxingApp,data:f6},{id:I.WritingApp,data:f6},this.format._options.appendOnly?null:e]};this.segmentInfo=r}createTracks(){let e={id:I.Tracks,data:[]};this.tracksElement=e;for(let r of this.trackDatas){let n=on[r.track.source._codec];x(n);let i=0;if(r.type==="audio"&&r.track.source._codec==="opus"){i=1e6*80;let s=r.info.decoderConfig.description;if(s){let a=qe(s),c=Ja(a);i=Math.round(1e9*(c.preSkip/Qi))}}e.data.push({id:I.TrackEntry,data:[{id:I.TrackNumber,data:r.track.id},{id:I.TrackUID,data:r.track.id},{id:I.TrackType,data:ere[r.type]},r.track.metadata.disposition?.default===!1?{id:I.FlagDefault,data:0}:null,r.track.metadata.disposition?.forced?{id:I.FlagForced,data:1}:null,r.track.metadata.disposition?.hearingImpaired?{id:I.FlagHearingImpaired,data:1}:null,r.track.metadata.disposition?.visuallyImpaired?{id:I.FlagVisualImpaired,data:1}:null,r.track.metadata.disposition?.original?{id:I.FlagOriginal,data:1}:null,r.track.metadata.disposition?.commentary?{id:I.FlagCommentary,data:1}:null,{id:I.FlagLacing,data:0},{id:I.Language,data:r.track.metadata.languageCode??Ft},{id:I.CodecID,data:n},{id:I.CodecDelay,data:0},{id:I.SeekPreRoll,data:i},r.track.metadata.name!==void 0?{id:I.Name,data:new es(r.track.metadata.name)}:null,r.type==="video"?this.videoSpecificTrackInfo(r):null,r.type==="audio"?this.audioSpecificTrackInfo(r):null,r.type==="subtitle"?this.subtitleSpecificTrackInfo(r):null]})}}videoSpecificTrackInfo(e){let{frameRate:r,rotation:n}=e.track.metadata,i=[e.info.decoderConfig.description?{id:I.CodecPrivate,data:qe(e.info.decoderConfig.description)}:null,r?{id:I.DefaultDuration,data:1e9/r}:null],s=n?Ha(-n):0,a=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,c=e.info.decoderConfig.colorSpace,l={id:I.Video,data:[{id:I.PixelWidth,data:e.info.width},{id:I.PixelHeight,data:e.info.height},a?{id:I.DisplayWidth,data:e.info.aspectRatio.num}:null,a?{id:I.DisplayHeight,data:e.info.aspectRatio.den}:null,a?{id:I.DisplayUnit,data:3}:null,e.info.alphaMode?{id:I.AlphaMode,data:1}:null,kx(c)?{id:I.Colour,data:[{id:I.MatrixCoefficients,data:Yi[c.matrix]},{id:I.TransferCharacteristics,data:qi[c.transfer]},{id:I.Primaries,data:ji[c.primaries]},{id:I.Range,data:c.fullRange?2:1}]}:null,s?{id:I.Projection,data:[{id:I.ProjectionType,data:0},{id:I.ProjectionPoseRoll,data:new ad((s+180)%360-180)}]}:null]};return i.push(l),i}audioSpecificTrackInfo(e){let r=ht.includes(e.track.source._codec)?_r(e.track.source._codec):null;return[e.info.decoderConfig.description?{id:I.CodecPrivate,data:qe(e.info.decoderConfig.description)}:null,{id:I.Audio,data:[{id:I.SamplingFrequency,data:new ad(e.info.sampleRate)},{id:I.Channels,data:e.info.numberOfChannels},r?{id:I.BitDepth,data:8*r.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[{id:I.CodecPrivate,data:lt.encode(e.info.config.description)}]}maybeCreateTags(){let e=[],r=o((s,a)=>{e.push({id:I.SimpleTag,data:[{id:I.TagName,data:new es(s)},typeof a=="string"?{id:I.TagString,data:new es(a)}:{id:I.TagBinary,data:a}]})},"addSimpleTag"),n=this.output._metadataTags,i=new Set;for(let{key:s,value:a}of Gi(n))switch(s){case"title":r("TITLE",a),i.add("TITLE");break;case"description":r("DESCRIPTION",a),i.add("DESCRIPTION");break;case"artist":r("ARTIST",a),i.add("ARTIST");break;case"album":r("ALBUM",a),i.add("ALBUM");break;case"albumArtist":r("ALBUM_ARTIST",a),i.add("ALBUM_ARTIST");break;case"genre":r("GENRE",a),i.add("GENRE");break;case"comment":r("COMMENT",a),i.add("COMMENT");break;case"lyrics":r("LYRICS",a),i.add("LYRICS");break;case"date":r("DATE",a.toISOString().slice(0,10)),i.add("DATE");break;case"trackNumber":{let c=n.tracksTotal!==void 0?`${a}/${n.tracksTotal}`:a.toString();r("PART_NUMBER",c),i.add("PART_NUMBER")}break;case"discNumber":{let c=n.discsTotal!==void 0?`${a}/${n.discsTotal}`:a.toString();r("DISC",c),i.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:kt(s)}if(n.raw)for(let s in n.raw){let a=n.raw[s];a==null||i.has(s)||(typeof a=="string"||a instanceof Uint8Array)&&r(s,a)}e.length!==0&&(this.tagsElement={id:I.Tags,data:[{id:I.Tag,data:[{id:I.Targets,data:[{id:I.TargetTypeValue,data:50},{id:I.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){let e=this.output._metadataTags,r=[],n=new Set,i=e.images??[];for(let s of i){let a=s.name;a===void 0&&(a=(s.kind==="coverFront"?"cover":s.kind==="coverBack"?"back":"image")+(Pz(s.mimeType)??""));let c;for(;;){c=0n;for(let l=0;l<8;l++)c<<=8n,c|=BigInt(Math.floor(Math.random()*256));if(c!==0n&&!n.has(c))break}n.add(c),r.push({id:I.AttachedFile,data:[s.description!==void 0?{id:I.FileDescription,data:new es(s.description)}:null,{id:I.FileName,data:new es(a)},{id:I.FileMediaType,data:s.mimeType},{id:I.FileData,data:s.data},{id:I.FileUID,data:c}]})}for(let[s,a]of Object.entries(e.raw??{}))!(a instanceof Oo)||!/^\d+$/.test(s)||i.find(l=>l.mimeType===a.mimeType&&Dz(l.data,a.data))||r.push({id:I.AttachedFile,data:[a.description!==void 0?{id:I.FileDescription,data:new es(a.description)}:null,{id:I.FileName,data:new es(a.name??"")},{id:I.FileMediaType,data:a.mimeType??""},{id:I.FileData,data:a.data},{id:I.FileUID,data:BigInt(s)}]});r.length!==0&&(this.attachmentsElement={id:I.Attachments,data:r})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);let e={id:I.Segment,size:this.format._options.appendOnly?-1:d6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){let{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(r,n)}}createCues(){this.cues={id:I.Cues,data:[]}}get segmentDataOffset(){return x(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return sk({isWebM:this.format instanceof jl,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,n){let i=this.trackDatas.find(u=>u.track===e);if(i)return i;Kf(n),x(n),x(n.decoderConfig),x(n.decoderConfig.codedWidth!==void 0),x(n.decoderConfig.codedHeight!==void 0);let s=n.decoderConfig.displayAspectWidth,a=n.decoderConfig.displayAspectHeight,c=s===void 0||a===void 0?null:qa({num:s,den:a}),l={track:e,type:"video",info:{width:n.decoderConfig.codedWidth,height:n.decoderConfig.codedHeight,aspectRatio:c,decoderConfig:n.decoderConfig,alphaMode:!!r.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null};return e.source._codec==="vp9"?l.info.decoderConfig={...l.info.decoderConfig,description:new Uint8Array(Uz(l.info.decoderConfig.codec))}:e.source._codec==="av1"&&(l.info.decoderConfig={...l.info.decoderConfig,description:new Uint8Array(Px(l.info.decoderConfig.codec))}),this.trackDatas.push(l),this.trackDatas.sort((u,f)=>u.track.id-f.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),l}getAudioTrackData(e,r,n){let i=this.trackDatas.find(l=>l.track===e);if(i)return i;En(n),x(n),x(n.decoderConfig);let s={...n.decoderConfig},a=!1;if(e.source._codec==="aac"&&!s.description){let l=Dn(xr.tempFromBytes(r.data));if(!l)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let u=vi[l.samplingFrequencyIndex],f=Ws[l.channelConfiguration];if(u===void 0||f===void 0)throw new Error("Invalid ADTS frame header.");s.description=Yf({objectType:l.objectType,sampleRate:u,numberOfChannels:f}),a=!0}let c={track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresAdtsStripping:a},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(c),this.trackDatas.sort((l,u)=>l.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Ix(r),x(r),x(r.config);let i={track:e,type:"subtitle",info:{config:r.config},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(i),this.trackDatas.sort((s,a)=>s.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,r,n){let i=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,n),a=r.type==="key",c=this.validateAndNormalizeTimestamp(s.track,r.timestamp,a),l=r.duration;e.metadata.frameRate!==void 0&&(c=ep(c,1/e.metadata.frameRate),l=ep(l,1/e.metadata.frameRate));let u=s.info.alphaMode?r.sideData.alpha??null:null,f=this.createInternalChunk(r.data,c,l,r.type,u);e.source._codec==="vp9"&&this.fixVP9ColorSpace(s,f),s.chunkQueue.push(f),await this.interleaveChunks()}finally{i()}}async addEncodedAudioPacket(e,r,n){let i=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,n),a=r.data;if(s.info.requiresAdtsStripping){let f=Dn(xr.tempFromBytes(a));if(!f)throw new Error("Expected ADTS frame, didn't get one.");let d=f.crcCheck===null?Wo:Jn;a=a.subarray(d)}let c=r.type==="key",l=this.validateAndNormalizeTimestamp(s.track,r.timestamp,c),u=this.createInternalChunk(a,l,r.duration,r.type);s.chunkQueue.push(u),await this.interleaveChunks()}finally{i()}}async addSubtitleCue(e,r,n){let i=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n),a=this.validateAndNormalizeTimestamp(s.track,r.timestamp,!0),c=r.text,l=Math.round(a*1e3);Td.lastIndex=0,c=c.replace(Td,h=>{let p=Ak(h.slice(1,-1))-l;return`<${Fk(p)}>`});let u=lt.encode(c),f=`${r.settings??""}
|
|
29
|
+
`,s);l===-1&&(l=e.length);let u=Ak(r[2]),d=Ak(r[3])-u,h=e.slice(a,l).trim();e=e.slice(l).trimStart(),Hp.lastIndex=0;let m={timestamp:u/1e3,duration:d/1e3,text:h,identifier:i,settings:c,notes:n},p={};this.preambleEmitted||(p.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(m,p)}}},Wee=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Ak=o(t=>{let e=Wee.exec(t);if(!e)throw new Error("Expected match.");return 3600*1e3*Number(e[1]||"0")+60*1e3*Number(e[2])+1e3*Number(e[3])+Number(e[4])},"parseSubtitleTimestamp"),Fk=o(t=>{let e=Math.floor(t/36e5),r=Math.floor(t%(3600*1e3)/(60*1e3)),n=Math.floor(t%(60*1e3)/1e3),i=t%1e3;return e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+n.toString().padStart(2,"0")+"."+i.toString().padStart(3,"0")},"formatSubtitleTimestamp")});var Wp,Je,Qs,Lt,Se,qI,jU,J,cc,Vl,qU,qo,YI,GI,qr,QI,YU,GU,QU,ye,et,r6,jp,n6,vd,jee,qee,Yee,Gee,Qee,Kee,Xee,KI,Jee,Zee,ete,tte,rte,nte,ite,ste,ote,ate,cte,lte,ute,fte,dte,KU,hte,mte,XI,lc,pte,gte,yte,bte,Ks,wte,xte,kte,Ste,uPt,Tte,vte,Ete,Cte,Pte,Ite,_te,Dte,Mte,JI,Ote,XU,Rte,Nte,Ate,Fte,i6,Lte,Bte,s6,o6,a6,zte,Ute,Xs,JU,ZU,$te,Hte,is,Vte,Wte,e6,jte,qte,Yte,t6,c6=he(()=>{Ue();Zt();Vp();ZI();sn();lr();Ti();Wp=class{static{o(this,"IsobmffBoxWriter")}constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let r=0;r<e.length;r++)this.helperView.setUint8(r%8,e.charCodeAt(r)),r%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let r=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let s of e.children)s&&this.writeBox(s);let n=this.writer.getPos(),i=e.size??n-r;this.writer.seek(r),this.writeBoxHeader(e,i),this.writer.seek(n)}}writeBoxHeader(e,r){this.writeU32(e.largeSize?1:r),this.writeAscii(e.type),e.largeSize&&this.writeU64(r)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let r=this.offsets.get(e);x(r!==void 0);let n=this.writer.getPos();this.writer.seek(r),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let r=this.measureBoxHeader(e);if(e.contents&&(r+=e.contents.byteLength),e.children)for(let n of e.children)n&&(r+=this.measureBox(n));return r}}},Je=new Uint8Array(8),Qs=new DataView(Je.buffer),Lt=o(t=>[(t%256+256)%256],"u8"),Se=o(t=>(Qs.setUint16(0,t,!1),[Je[0],Je[1]]),"u16"),qI=o(t=>(Qs.setInt16(0,t,!1),[Je[0],Je[1]]),"i16"),jU=o(t=>(Qs.setUint32(0,t,!1),[Je[1],Je[2],Je[3]]),"u24"),J=o(t=>(Qs.setUint32(0,t,!1),[Je[0],Je[1],Je[2],Je[3]]),"u32"),cc=o(t=>(Qs.setInt32(0,t,!1),[Je[0],Je[1],Je[2],Je[3]]),"i32"),Vl=o(t=>(Qs.setUint32(0,Math.floor(t/2**32),!1),Qs.setUint32(4,t,!1),[Je[0],Je[1],Je[2],Je[3],Je[4],Je[5],Je[6],Je[7]]),"u64"),qU=o(t=>(Qs.setInt16(0,2**8*t,!1),[Je[0],Je[1]]),"fixed_8_8"),qo=o(t=>(Qs.setInt32(0,2**16*t,!1),[Je[0],Je[1],Je[2],Je[3]]),"fixed_16_16"),YI=o(t=>(Qs.setInt32(0,2**30*t,!1),[Je[0],Je[1],Je[2],Je[3]]),"fixed_2_30"),GI=o((t,e)=>{let r=[],n=t;do{let i=n&127;n>>=7,r.length>0&&(i|=128),r.push(i),e!==void 0&&e--}while(n>0||e);return r.reverse()},"variableUnsignedInt"),qr=o((t,e=!1)=>{let r=Array(t.length).fill(null).map((n,i)=>t.charCodeAt(i));return e&&r.push(0),r},"ascii"),QI=o(t=>{let e=null;for(let r of t)(!e||r.timestamp>e.timestamp)&&(e=r);return e},"lastPresentedSample"),YU=o(t=>{let e=t*(Math.PI/180),r=Math.round(Math.cos(e)),n=Math.round(Math.sin(e));return[r,n,0,-n,r,0,0,0,1]},"rotationMatrix"),GU=YU(0),QU=o(t=>[qo(t[0]),qo(t[1]),YI(t[2]),qo(t[3]),qo(t[4]),YI(t[5]),qo(t[6]),qo(t[7]),YI(t[8])],"matrixToBytes"),ye=o((t,e,r)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:r}),"box"),et=o((t,e,r,n,i)=>ye(t,[Lt(e),jU(r),n??[]],i),"fullBox"),r6=o(t=>t.isQuickTime?ye("ftyp",[qr("qt "),J(512),qr("qt ")]):t.fragmented?ye("ftyp",[qr("iso5"),J(512),qr("iso5"),qr("iso6"),qr("mp41")]):ye("ftyp",[qr("isom"),J(512),qr("isom"),t.holdsAvc?qr("avc1"):[],qr("mp41")]),"ftyp"),jp=o(t=>({type:"mdat",largeSize:t}),"mdat"),n6=o(t=>({type:"free",size:t}),"free"),vd=o(t=>ye("moov",void 0,[jee(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>qee(e,t.creationTime)),t.isFragmented?Dte(t.trackDatas):null,zte(t)]),"moov"),jee=o((t,e)=>{let r=fr(Math.max(0,...e.filter(a=>a.samples.length>0).map(a=>{let c=QI(a.samples);return c.timestamp+c.duration})),Lk),n=Math.max(0,...e.map(a=>a.track.id))+1,i=!El(t)||!El(r),s=i?Vl:J;return et("mvhd",+i,0,[s(t),s(t),J(Lk),s(r),qo(1),qU(1),Array(10).fill(0),QU(GU),Array(24).fill(0),J(n)])},"mvhd"),qee=o((t,e)=>{let r=l6(t);return ye("trak",void 0,[Yee(t,e),Gee(t,e),r.name!==void 0?ye("udta",void 0,[ye("name",[...lt.encode(r.name)])]):null])},"trak"),Yee=o((t,e)=>{let r=QI(t.samples),n=fr(r?r.timestamp+r.duration:0,Lk),i=!El(e)||!El(n),s=i?Vl:J,a;if(t.type==="video"){let l=t.track.metadata.rotation;a=YU(l??0)}else a=GU;let c=2;return t.track.metadata.disposition?.default!==!1&&(c|=1),et("tkhd",+i,c,[s(e),s(e),J(t.track.id),J(0),s(n),Array(8).fill(0),Se(0),Se(t.track.id),qU(t.type==="audio"?1:0),Se(0),QU(a),qo(t.type==="video"?t.info.width:0),qo(t.type==="video"?t.info.height:0)])},"tkhd"),Gee=o((t,e)=>ye("mdia",void 0,[Qee(t,e),KI(!0,Kee[t.type],Xee[t.type]),Jee(t)]),"mdia"),Qee=o((t,e)=>{let r=QI(t.samples),n=fr(r?r.timestamp+r.duration:0,t.timescale),i=!El(e)||!El(n),s=i?Vl:J;return et("mdhd",+i,0,[s(e),s(e),J(t.timescale),s(n),Se(t6(t.track.metadata.languageCode??Ft)),Se(0)])},"mdhd"),Kee={video:"vide",audio:"soun",subtitle:"text"},Xee={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},KI=o((t,e,r,n="\0\0\0\0")=>et("hdlr",0,0,[t?qr("mhlr"):J(0),qr(e),qr(n),J(0),J(0),qr(r,!0)]),"hdlr"),Jee=o(t=>ye("minf",void 0,[rte[t.type](),nte(),ote(t)]),"minf"),Zee=o(()=>et("vmhd",0,1,[Se(0),Se(0),Se(0),Se(0)]),"vmhd"),ete=o(()=>et("smhd",0,0,[Se(0),Se(0)]),"smhd"),tte=o(()=>et("nmhd",0,0),"nmhd"),rte={video:Zee,audio:ete,subtitle:tte},nte=o(()=>ye("dinf",void 0,[ite()]),"dinf"),ite=o(()=>et("dref",0,0,[J(1)],[ste()]),"dref"),ste=o(()=>et("url ",0,1),"url"),ote=o(t=>{let e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(r=>r.sampleCompositionTimeOffset!==0);return ye("stbl",void 0,[ate(t),Tte(t),e?Ite(t):null,e?_te(t):null,Ete(t),Cte(t),Pte(t),vte(t)])},"stbl"),ate=o(t=>{let e;if(t.type==="video")e=cte(Vte(t.track.source._codec,t.info.decoderConfig.codec),t);else if(t.type==="audio"){let r=e6(t.track.source._codec,t.muxer.isQuickTime);x(r),e=mte(r,t)}else t.type==="subtitle"&&(e=kte(qte[t.track.source._codec],t));return x(e),et("stsd",0,0,[J(1)],[e])},"stsd"),cte=o((t,e)=>ye(t,[Array(6).fill(0),Se(1),Se(0),Se(0),Array(12).fill(0),Se(e.info.width),Se(e.info.height),J(4718592),J(4718592),J(0),Se(1),Array(32).fill(0),Se(24),qI(65535)],[Wte[e.track.source._codec](e),lte(e),kx(e.info.decoderConfig.colorSpace)?ute(e):null]),"videoSampleDescription"),lte=o(t=>t.info.pixelAspectRatio.num===t.info.pixelAspectRatio.den?null:ye("pasp",[J(t.info.pixelAspectRatio.num),J(t.info.pixelAspectRatio.den)]),"pasp"),ute=o(t=>ye("colr",[qr("nclx"),Se(ji[t.info.decoderConfig.colorSpace.primaries]),Se(qi[t.info.decoderConfig.colorSpace.transfer]),Se(Yi[t.info.decoderConfig.colorSpace.matrix]),Lt((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),"colr"),fte=o(t=>t.info.decoderConfig&&ye("avcC",[...qe(t.info.decoderConfig.description)]),"avcC"),dte=o(t=>t.info.decoderConfig&&ye("hvcC",[...qe(t.info.decoderConfig.description)]),"hvcC"),KU=o(t=>{if(!t.info.decoderConfig)return null;let e=t.info.decoderConfig,r=e.codec.split("."),n=Number(r[1]),i=Number(r[2]),s=Number(r[3]),a=r[4]?Number(r[4]):1,c=r[8]?Number(r[8]):Number(e.colorSpace?.fullRange??0),l=(s<<4)+(a<<1)+c,u=r[5]?Number(r[5]):e.colorSpace?.primaries?ji[e.colorSpace.primaries]:2,f=r[6]?Number(r[6]):e.colorSpace?.transfer?qi[e.colorSpace.transfer]:2,d=r[7]?Number(r[7]):e.colorSpace?.matrix?Yi[e.colorSpace.matrix]:2;return et("vpcC",1,0,[Lt(n),Lt(i),Lt(l),Lt(u),Lt(f),Lt(d),Se(0)])},"vpcC"),hte=o(t=>ye("av1C",Px(t.info.decoderConfig.codec)),"av1C"),mte=o((t,e)=>{let r=0,n,i=16,s=ht.includes(e.track.source._codec);if(s){let a=e.track.source._codec,{sampleSize:c}=_r(a);i=8*c,i>16&&(r=1)}if(e.muxer.isQuickTime&&(r=1),r===0)n=[Array(6).fill(0),Se(1),Se(r),Se(0),J(0),Se(e.info.numberOfChannels),Se(i),Se(0),Se(0),Se(e.info.sampleRate<2**16?e.info.sampleRate:0),Se(0)];else{let a=s?0:-2;n=[Array(6).fill(0),Se(1),Se(r),Se(0),J(0),Se(e.info.numberOfChannels),Se(Math.min(i,16)),qI(a),Se(0),Se(e.info.sampleRate<2**16?e.info.sampleRate:0),Se(0),s?[J(1),J(i/8),J(e.info.numberOfChannels*i/8)]:[J(0),J(0),J(0)],J(2)]}return ye(t,n,[jte(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},"soundSampleDescription"),XI=o(t=>{let e;switch(t.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${t.track.source._codec}`)}let r=[...Lt(e),...Lt(21),...jU(0),...J(0),...J(0)];if(t.info.decoderConfig.description){let n=qe(t.info.decoderConfig.description);r=[...r,...Lt(5),...GI(n.byteLength),...n]}return r=[...Se(1),...Lt(0),...Lt(4),...GI(r.length),...r,...Lt(6),...Lt(1),...Lt(2)],r=[...Lt(3),...GI(r.length),...r],et("esds",0,0,r)},"esds"),lc=o(t=>ye("wave",void 0,[pte(t),gte(t),ye("\0\0\0\0")]),"wave"),pte=o(t=>ye("frma",[qr(e6(t.track.source._codec,t.muxer.isQuickTime))]),"frma"),gte=o(t=>{let{littleEndian:e}=_r(t.track.source._codec);return ye("enda",[Se(+e)])},"enda"),yte=o(t=>{let e=t.info.numberOfChannels,r=3840,n=t.info.sampleRate,i=0,s=0,a=new Uint8Array(0),c=t.info.decoderConfig?.description;if(c){x(c.byteLength>=18);let l=qe(c),u=Ja(l);e=u.outputChannelCount,r=u.preSkip,n=u.inputSampleRate,i=u.outputGain,s=u.channelMappingFamily,u.channelMappingTable&&(a=u.channelMappingTable)}return ye("dOps",[Lt(0),Lt(e),Se(r),J(n),qI(i),Lt(s),...a])},"dOps"),bte=o(t=>{let e=t.info.decoderConfig?.description;x(e);let r=qe(e);return et("dfLa",0,0,[...r.subarray(4)])},"dfLa"),Ks=o(t=>{let{littleEndian:e,sampleSize:r}=_r(t.track.source._codec),n=+e;return et("pcmC",0,0,[Lt(n),Lt(8*r)])},"pcmC"),wte=o(t=>{let e=$x(t.info.firstPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");let r=new Uint8Array(3),n=new Te(r);return n.writeBits(2,e.fscod),n.writeBits(5,e.bsid),n.writeBits(3,e.bsmod),n.writeBits(3,e.acmod),n.writeBits(1,e.lfeon),n.writeBits(5,e.bitRateCode),n.writeBits(5,0),ye("dac3",[...r])},"dac3"),xte=o(t=>{let e=Hx(t.info.firstPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let r=16;for(let a of e.substreams)r+=23,a.numDepSub>0?r+=9:r+=1;let n=Math.ceil(r/8),i=new Uint8Array(n),s=new Te(i);s.writeBits(13,e.dataRate),s.writeBits(3,e.substreams.length-1);for(let a of e.substreams)s.writeBits(2,a.fscod),s.writeBits(5,a.bsid),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(3,a.bsmod),s.writeBits(3,a.acmod),s.writeBits(1,a.lfeon),s.writeBits(3,0),s.writeBits(4,a.numDepSub),a.numDepSub>0?s.writeBits(9,a.chanLoc):s.writeBits(1,0);return ye("dec3",[...i])},"dec3"),kte=o((t,e)=>ye(t,[Array(6).fill(0),Se(1)],[Yte[e.track.source._codec](e)]),"subtitleSampleDescription"),Ste=o(t=>ye("vttC",[...lt.encode(t.info.config.description)]),"vttC"),uPt=o(t=>et("txtC",0,0,[...t,0]),"txtC"),Tte=o(t=>et("stts",0,0,[J(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[J(e.sampleCount),J(e.sampleDelta)])]),"stts"),vte=o(t=>{if(t.samples.every(r=>r.type==="key"))return null;let e=[...t.samples.entries()].filter(([,r])=>r.type==="key");return et("stss",0,0,[J(e.length),e.map(([r])=>J(r+1))])},"stss"),Ete=o(t=>et("stsc",0,0,[J(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[J(e.firstChunk),J(e.samplesPerChunk),J(1)])]),"stsc"),Cte=o(t=>{if(t.type==="audio"&&t.info.requiresPcmTransformation){let{sampleSize:e}=_r(t.track.source._codec);return et("stsz",0,0,[J(e*t.info.numberOfChannels),J(t.samples.reduce((r,n)=>r+fr(n.duration,t.timescale),0))])}return et("stsz",0,0,[J(0),J(t.samples.length),t.samples.map(e=>J(e.size))])},"stsz"),Pte=o(t=>t.finalizedChunks.length>0&&Ze(t.finalizedChunks).offset>=2**32?et("co64",0,0,[J(t.finalizedChunks.length),t.finalizedChunks.map(e=>Vl(e.offset))]):et("stco",0,0,[J(t.finalizedChunks.length),t.finalizedChunks.map(e=>J(e.offset))]),"stco"),Ite=o(t=>et("ctts",1,0,[J(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[J(e.sampleCount),cc(e.sampleCompositionTimeOffset)])]),"ctts"),_te=o(t=>{let e=1/0,r=-1/0,n=1/0,i=-1/0;x(t.compositionTimeOffsetTable.length>0),x(t.samples.length>0);for(let a=0;a<t.compositionTimeOffsetTable.length;a++){let c=t.compositionTimeOffsetTable[a];e=Math.min(e,c.sampleCompositionTimeOffset),r=Math.max(r,c.sampleCompositionTimeOffset)}for(let a=0;a<t.samples.length;a++){let c=t.samples[a];n=Math.min(n,fr(c.timestamp,t.timescale)),i=Math.max(i,fr(c.timestamp+c.duration,t.timescale))}let s=Math.max(-e,0);return i>=2**31?null:et("cslg",0,0,[cc(s),cc(e),cc(r),cc(n),cc(i)])},"cslg"),Dte=o(t=>ye("mvex",void 0,t.map(Mte)),"mvex"),Mte=o(t=>et("trex",0,0,[J(t.track.id),J(1),J(0),J(0),J(0)]),"trex"),JI=o((t,e)=>ye("moof",void 0,[Ote(t),...e.map(Rte)]),"moof"),Ote=o(t=>et("mfhd",0,0,[J(t)]),"mfhd"),XU=o(t=>{let e=0,r=0,n=0,i=0,s=t.type==="delta";return r|=+s,s?e|=1:e|=2,e<<24|r<<16|n<<8|i},"fragmentSampleFlags"),Rte=o(t=>ye("traf",void 0,[Nte(t),Ate(t),Fte(t)]),"traf"),Nte=o(t=>{x(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;let r=t.currentChunk.samples[1]??t.currentChunk.samples[0],n={duration:r.timescaleUnitsToNextSample,size:r.size,flags:XU(r)};return et("tfhd",0,e,[J(t.track.id),J(n.duration),J(n.size),J(n.flags)])},"tfhd"),Ate=o(t=>(x(t.currentChunk),et("tfdt",1,0,[Vl(fr(t.currentChunk.startTimestamp,t.timescale))])),"tfdt"),Fte=o(t=>{x(t.currentChunk);let e=t.currentChunk.samples.map(g=>g.timescaleUnitsToNextSample),r=t.currentChunk.samples.map(g=>g.size),n=t.currentChunk.samples.map(XU),i=t.currentChunk.samples.map(g=>fr(g.timestamp-g.decodeTimestamp,t.timescale)),s=new Set(e),a=new Set(r),c=new Set(n),l=new Set(i),u=c.size===2&&n[0]!==n[1],f=s.size>1,d=a.size>1,h=!u&&c.size>1,m=l.size>1||[...l].some(g=>g!==0),p=0;return p|=1,p|=4*+u,p|=256*+f,p|=512*+d,p|=1024*+h,p|=2048*+m,et("trun",1,p,[J(t.currentChunk.samples.length),J(t.currentChunk.offset-t.currentChunk.moofOffset||0),u?J(n[0]):[],t.currentChunk.samples.map((g,y)=>[f?J(e[y]):[],d?J(r[y]):[],h?J(n[y]):[],m?cc(i[y]):[]])])},"trun"),i6=o(t=>ye("mfra",void 0,[...t.map(Lte),Bte()]),"mfra"),Lte=o((t,e)=>et("tfra",1,0,[J(t.track.id),J(63),J(t.finalizedChunks.length),t.finalizedChunks.map(n=>[Vl(fr(n.samples[0].timestamp,t.timescale)),Vl(n.moofOffset),J(e+1),J(1),J(1)])]),"tfra"),Bte=o(()=>et("mfro",0,0,[J(0)]),"mfro"),s6=o(()=>ye("vtte"),"vtte"),o6=o((t,e,r,n,i)=>ye("vttc",void 0,[i!==null?ye("vsid",[cc(i)]):null,r!==null?ye("iden",[...lt.encode(r)]):null,e!==null?ye("ctim",[...lt.encode(Fk(e))]):null,n!==null?ye("sttg",[...lt.encode(n)]):null,ye("payl",[...lt.encode(t)])]),"vttc"),a6=o(t=>ye("vtta",[...lt.encode(t)]),"vtta"),zte=o(t=>{let e=[],r=t.format._options.metadataFormat??"auto",n=t.output._metadataTags;if(r==="mdir"||r==="auto"&&!t.isQuickTime){let i=$te(n);i&&e.push(i)}else if(r==="mdta"){let i=Hte(n);i&&e.push(i)}else(r==="udta"||r==="auto"&&t.isQuickTime)&&Ute(e,t.output._metadataTags);return e.length===0?null:ye("udta",void 0,e)},"udta"),Ute=o((t,e)=>{for(let{key:r,value:n}of Gi(e))switch(r){case"title":t.push(Xs("\xA9nam",n));break;case"description":t.push(Xs("\xA9des",n));break;case"artist":t.push(Xs("\xA9ART",n));break;case"album":t.push(Xs("\xA9alb",n));break;case"albumArtist":t.push(Xs("albr",n));break;case"genre":t.push(Xs("\xA9gen",n));break;case"date":t.push(Xs("\xA9day",n.toISOString().slice(0,10)));break;case"comment":t.push(Xs("\xA9cmt",n));break;case"lyrics":t.push(Xs("\xA9lyr",n));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:kt(r)}if(e.raw)for(let r in e.raw){let n=e.raw[r];n==null||r.length!==4||t.some(i=>i.type===r)||(typeof n=="string"?t.push(Xs(r,n)):n instanceof Uint8Array&&t.push(ye(r,Array.from(n))))}},"addQuickTimeMetadataTagBoxes"),Xs=o((t,e)=>{let r=lt.encode(e);return ye(t,[Se(r.length),Se(t6("und")),Array.from(r)])},"metadataTagStringBoxShort"),JU={"image/jpeg":13,"image/png":14,"image/bmp":27},ZU=o((t,e)=>{let r=[];for(let{key:n,value:i}of Gi(t))switch(n){case"title":r.push({key:e?"title":"\xA9nam",value:is(i)});break;case"description":r.push({key:e?"description":"\xA9des",value:is(i)});break;case"artist":r.push({key:e?"artist":"\xA9ART",value:is(i)});break;case"album":r.push({key:e?"album":"\xA9alb",value:is(i)});break;case"albumArtist":r.push({key:e?"album_artist":"aART",value:is(i)});break;case"comment":r.push({key:e?"comment":"\xA9cmt",value:is(i)});break;case"genre":r.push({key:e?"genre":"\xA9gen",value:is(i)});break;case"lyrics":r.push({key:e?"lyrics":"\xA9lyr",value:is(i)});break;case"date":r.push({key:e?"date":"\xA9day",value:is(i.toISOString().slice(0,10))});break;case"images":for(let s of i)s.kind==="coverFront"&&r.push({key:"covr",value:ye("data",[J(JU[s.mimeType]??0),J(0),Array.from(s.data)])});break;case"trackNumber":if(e){let s=t.tracksTotal!==void 0?`${i}/${t.tracksTotal}`:i.toString();r.push({key:"track",value:is(s)})}else r.push({key:"trkn",value:ye("data",[J(0),J(0),Se(0),Se(i),Se(t.tracksTotal??0),Se(0)])});break;case"discNumber":e||r.push({key:"disc",value:ye("data",[J(0),J(0),Se(0),Se(i),Se(t.discsTotal??0),Se(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:kt(n)}if(t.raw)for(let n in t.raw){let i=t.raw[n];i==null||!e&&n.length!==4||r.some(s=>s.key===n)||(typeof i=="string"?r.push({key:n,value:is(i)}):i instanceof Uint8Array?r.push({key:n,value:ye("data",[J(0),J(0),Array.from(i)])}):i instanceof Gn&&r.push({key:n,value:ye("data",[J(JU[i.mimeType]??0),J(0),Array.from(i.data)])}))}return r},"generateMetadataPairs"),$te=o(t=>{let e=ZU(t,!1);return e.length===0?null:et("meta",0,0,void 0,[KI(!1,"mdir","","appl"),ye("ilst",void 0,e.map(r=>ye(r.key,void 0,[r.value])))])},"metaMdir"),Hte=o(t=>{let e=ZU(t,!0);return e.length===0?null:ye("meta",void 0,[KI(!1,"mdta",""),et("keys",0,0,[J(e.length)],e.map(r=>ye("mdta",[...lt.encode(r.key)]))),ye("ilst",void 0,e.map((r,n)=>{let i=String.fromCharCode(...J(n+1));return ye(i,void 0,[r.value])}))])},"metaMdta"),is=o(t=>ye("data",[J(1),J(0),...lt.encode(t)]),"dataStringBoxLong"),Vte=o((t,e)=>{switch(t){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},"videoCodecToBoxName"),Wte={avc:fte,hevc:dte,vp8:KU,vp9:KU,av1:hte},e6=o((t,e)=>{switch(t){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3"}if(e)switch(t){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(t){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},"audioCodecToBoxName"),jte=o((t,e)=>{switch(t){case"aac":return XI;case"mp3":return XI;case"opus":return yte;case"vorbis":return XI;case"flac":return bte;case"ac3":return wte;case"eac3":return xte}if(e)switch(t){case"pcm-s24":return lc;case"pcm-s24be":return lc;case"pcm-s32":return lc;case"pcm-s32be":return lc;case"pcm-f32":return lc;case"pcm-f32be":return lc;case"pcm-f64":return lc;case"pcm-f64be":return lc}else switch(t){case"pcm-s16":return Ks;case"pcm-s16be":return Ks;case"pcm-s24":return Ks;case"pcm-s24be":return Ks;case"pcm-s32":return Ks;case"pcm-s32be":return Ks;case"pcm-f32":return Ks;case"pcm-f32be":return Ks;case"pcm-f64":return Ks;case"pcm-f64be":return Ks}return null},"audioCodecToConfigurationBox"),qte={webvtt:"wvtt"},Yte={webvtt:Ste},t6=o(t=>{x(t.length===3);let e=0;for(let r=0;r<3;r++)e<<=5,e+=t.charCodeAt(r)-96;return e},"getLanguageCodeInt")});var qp,e_,t_,Ed,Gte,Qte,Bk,zk,r_=he(()=>{Ue();qp=class{static{o(this,"Writer")}constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let r=this.getPos();if(r<this.trackedStart){if(r+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-r),r=0}let n=r+e.byteLength-this.trackedStart,i=this.trackedWrites.byteLength;for(;i<n;)i*=2;if(i!==this.trackedWrites.byteLength){let s=new Uint8Array(i);s.set(this.trackedWrites,0),this.trackedWrites=s}this.trackedWrites.set(e,r-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,r+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");let r={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,r}},e_=2**16,t_=2**32,Ed=class extends qp{static{o(this,"BufferTargetWriter")}constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(e_,{maxByteLength:t_})}catch{this.buffer=new ArrayBuffer(e_),this.supportsResize=!1}else this.buffer=new ArrayBuffer(e_);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let r=this.buffer.byteLength;for(;r<e;)r*=2;if(r!==this.buffer.byteLength){if(r>t_)throw new Error(`ArrayBuffer exceeded maximum size of ${t_} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(r);else{let n=new ArrayBuffer(r),i=new Uint8Array(n);i.set(this.bytes,0),this.buffer=n,this.bytes=i}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,r){return this.bytes.slice(e,r)}},Gte=2**24,Qte=2,Bk=class extends qp{static{o(this,"StreamTargetWriter")}constructor(e){super(),this.pos=0,this.sections=[],this.lastWriteEnd=0,this.lastFlushEnd=0,this.writer=null,this.writeError=null,this.chunks=[],this.target=e,this.chunked=e._options.chunked??!1,this.chunkSize=e._options.chunkSize??Gte}start(){this.writer=this.target._writable.getWriter()}write(e){if(this.pos>this.lastWriteEnd){let r=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(r))}this.maybeTrackWrites(e),this.sections.push({data:e.slice(),start:this.pos}),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.lastWriteEnd=Math.max(this.lastWriteEnd,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){if(this.writeError!==null)throw this.writeError;if(this.pos>this.lastWriteEnd){let n=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(n))}if(x(this.writer),this.sections.length===0)return;let e=[],r=[...this.sections].sort((n,i)=>n.start-i.start);e.push({start:r[0].start,size:r[0].data.byteLength});for(let n=1;n<r.length;n++){let i=e[e.length-1],s=r[n];s.start<=i.start+i.size?i.size=Math.max(i.size,s.start+s.data.byteLength-i.start):e.push({start:s.start,size:s.data.byteLength})}for(let n of e){n.data=new Uint8Array(n.size);for(let i of this.sections)n.start<=i.start&&i.start<n.start+n.size&&n.data.set(i.data,i.start-n.start);if(this.writer.desiredSize!==null&&this.writer.desiredSize<=0&&await this.writer.ready,this.chunked)this.writeDataIntoChunks(n.data,n.start),this.tryToFlushChunks();else{if(this.ensureMonotonicity&&n.start!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:n.data,position:n.start}).catch(i=>{this.writeError??=i}),this.lastFlushEnd=n.start+n.data.byteLength}}this.sections.length=0}writeDataIntoChunks(e,r){let n=this.chunks.findIndex(l=>l.start<=r&&r<l.start+this.chunkSize);n===-1&&(n=this.createChunk(r));let i=this.chunks[n],s=r-i.start,a=e.subarray(0,Math.min(this.chunkSize-s,e.byteLength));i.data.set(a,s);let c={start:s,end:s+a.byteLength};if(this.insertSectionIntoChunk(i,c),i.written[0].start===0&&i.written[0].end===this.chunkSize&&(i.shouldFlush=!0),this.chunks.length>Qte){for(let l=0;l<this.chunks.length-1;l++)this.chunks[l].shouldFlush=!0;this.tryToFlushChunks()}a.byteLength<e.byteLength&&this.writeDataIntoChunks(e.subarray(a.byteLength),r+a.byteLength)}insertSectionIntoChunk(e,r){let n=0,i=e.written.length-1,s=-1;for(;n<=i;){let a=Math.floor(n+(i-n+1)/2);e.written[a].start<=r.start?(n=a+1,s=a):i=a-1}for(e.written.splice(s+1,0,r),(s===-1||e.written[s].end<r.start)&&s++;s<e.written.length-1&&e.written[s].end>=e.written[s+1].start;)e.written[s].end=Math.max(e.written[s].end,e.written[s+1].end),e.written.splice(s+1,1)}createChunk(e){let n={start:Math.floor(e/this.chunkSize)*this.chunkSize,data:new Uint8Array(this.chunkSize),written:[],shouldFlush:!1};return this.chunks.push(n),this.chunks.sort((i,s)=>i.start-s.start),this.chunks.indexOf(n)}tryToFlushChunks(e=!1){x(this.writer);for(let r=0;r<this.chunks.length;r++){let n=this.chunks[r];if(!(!n.shouldFlush&&!e)){for(let i of n.written){let s=n.start+i.start;if(this.ensureMonotonicity&&s!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:n.data.subarray(i.start,i.end),position:s}).catch(a=>{this.writeError??=a}),this.lastFlushEnd=n.start+i.end}this.chunks.splice(r--,1)}}}async finalize(){if(this.chunked&&this.tryToFlushChunks(!0),this.writeError!==null)throw this.writeError;return x(this.writer),await this.writer.ready,this.writer.close()}async close(){return this.writer?.close()}},zk=class extends qp{static{o(this,"NullTargetWriter")}constructor(e){super(),this.target=e,this.pos=0}write(e){this.maybeTrackWrites(e),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength}getPos(){return this.pos}seek(e){this.pos=e}async flush(){}async finalize(){}async close(){}}});var u6,Kte,Js,Cd,Yp,Uk,Pd,Gp=he(()=>{r_();u6=us(HI(),1);Ue();Kte=typeof u6<"u"?u6:void 0,Js=class{static{o(this,"Target")}constructor(){this._output=null,this.onwrite=null}},Cd=class extends Js{static{o(this,"BufferTarget")}constructor(){super(...arguments),this.buffer=null}_createWriter(){return new Ed(this)}},Yp=class extends Js{static{o(this,"StreamTarget")}constructor(e,r={}){if(super(),!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(r!=null&&typeof r!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(r.chunked!==void 0&&typeof r.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(r.chunkSize!==void 0&&(!Number.isInteger(r.chunkSize)||r.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=r}_createWriter(){return new Bk(this)}},Uk=class extends Js{static{o(this,"FilePathTarget")}constructor(e,r={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");super(),this._fileHandle=null;let n=new WritableStream({start:o(async()=>{this._fileHandle=await Kte.fs.open(e,"w")},"start"),write:o(async i=>{x(this._fileHandle),await this._fileHandle.write(i.data,0,i.data.byteLength,i.position)},"write"),close:o(async()=>{this._fileHandle&&(await this._fileHandle.close(),this._fileHandle=null)},"close")});this._streamTarget=new Yp(n,{chunked:!0,...r}),this._streamTarget._output=this._output}_createWriter(){return this._streamTarget._createWriter()}},Pd=class extends Js{static{o(this,"NullTarget")}_createWriter(){return new zk(this)}}});var Lk,Xte,l6,fr,$k,ZI=he(()=>{c6();jo();r_();Ue();Id();Vp();qs();Zt();gd();qt();Gp();sn();nI();iI();Lk=1e3,Xte=2082844800,l6=o(t=>{let e={},r=t.track;return r.metadata.name!==void 0&&(e.name=r.metadata.name),e},"getTrackMetadata"),fr=o((t,e,r=!0)=>{let n=t*e;return r?Math.round(n):n},"intoTimescale"),$k=class extends Sr{static{o(this,"IsobmffMuxer")}constructor(e,r){super(e),this.auxTarget=new Cd,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new Wp(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=ut(),this.creationTime=Math.floor(Date.now()/1e3)+Xte,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=r,this.writer=e._writer,this.boxWriter=new Wp(this.writer),this.isQuickTime=r instanceof Wl;let n=this.writer instanceof Ed?"in-memory":!1;this.fastStart=r._options.fastStart??n,this.isFragmented=this.fastStart==="fragmented",(this.fastStart==="in-memory"||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=r._options.minimumFragmentDuration??1}async start(){let e=await this.mutex.acquire(),r=this.output._tracks.some(n=>n.type==="video"&&n.source._codec==="avc");if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r6({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented})),this.format._options.onFtyp){let{data:n,start:i}=this.writer.stopTrackingWrites();this.format._options.onFtyp(n,i)}if(this.ftypSize=this.writer.getPos(),this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(let n of this.output._tracks)if(n.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=jp(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Gx({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,n){let i=this.trackDatas.find(h=>h.track===e);if(i)return i;Kf(n),x(n),x(n.decoderConfig);let s={...n.decoderConfig};x(s.codedWidth!==void 0),x(s.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!s.description){let h=Jf(r.data);if(!h)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=Kz(h),a=!0}else if(e.source._codec==="hevc"&&!s.description){let h=Zf(r.data);if(!h)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=Xz(h),a=!0}let c=Ez(1/(e.metadata.frameRate??57600),1e6).denominator,l=s.displayAspectWidth,u=s.displayAspectHeight,f=l===void 0||u===void 0?{num:1,den:1}:qa({num:l*s.codedHeight,den:u*s.codedWidth}),d={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:f,decoderConfig:s,requiresAnnexBTransformation:a},timescale:c,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(d),this.trackDatas.sort((h,m)=>h.track.id-m.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,r,n){let i=this.trackDatas.find(l=>l.track===e);if(i)return i;En(n),x(n),x(n.decoderConfig);let s={...n.decoderConfig},a=!1;if(e.source._codec==="aac"&&!s.description){let l=Dn(xr.tempFromBytes(r.data));if(!l)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let u=vi[l.samplingFrequencyIndex],f=Ws[l.channelConfiguration];if(u===void 0||f===void 0)throw new Error("Invalid ADTS frame header.");s.description=Yf({objectType:l.objectType,sampleRate:u,numberOfChannels:f}),a=!0}let c={muxer:this,track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&ht.includes(e.source._codec),requiresAdtsStripping:a,firstPacket:r},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(c),this.trackDatas.sort((l,u)=>l.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Ix(r),x(r),x(r.config);let i={muxer:this,track:e,type:"subtitle",info:{config:r.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(i),this.trackDatas.sort((s,a)=>s.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,r,n){let i=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,n),a=r.data;if(s.info.requiresAnnexBTransformation){let u=[...Xa(a)].map(f=>a.subarray(f.offset,f.offset+f.length));if(u.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=qP(u,4)}let c=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),l=this.createSampleForTrack(s,a,c,r.duration,r.type);await this.registerSample(s,l)}finally{i()}}async addEncodedAudioPacket(e,r,n){let i=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,n),a=r.data;if(s.info.requiresAdtsStripping){let u=Dn(xr.tempFromBytes(a));if(!u)throw new Error("Expected ADTS frame, didn't get one.");let f=u.crcCheck===null?Wo:Jn;a=a.subarray(f)}let c=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),l=this.createSampleForTrack(s,a,c,r.duration,r.type);s.info.requiresPcmTransformation&&await this.maybePadWithSilence(s,c),await this.registerSample(s,l)}finally{i()}}async maybePadWithSilence(e,r){let n=Ze(e.samples),i=n?n.timestamp+n.duration:0,s=r-i,a=fr(s,e.timescale);if(a>0){let{sampleSize:c,silentValue:l}=_r(e.info.decoderConfig.codec),u=a*e.info.numberOfChannels,f=new Uint8Array(c*u).fill(l),d=this.createSampleForTrack(e,new Uint8Array(f.buffer),i,s,"key");await this.registerSample(e,d)}}async addSubtitleCue(e,r,n){let i=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n);this.validateAndNormalizeTimestamp(s.track,r.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(r),await this.processWebVTTCues(s,r.timestamp))}finally{i()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){let n=new Set([]);for(let u of e.cueQueue)x(u.timestamp<=r),x(e.lastCueEndTimestamp<=u.timestamp+u.duration),n.add(Math.max(u.timestamp,e.lastCueEndTimestamp)),n.add(u.timestamp+u.duration);let i=[...n].sort((u,f)=>u-f),s=i[0],a=i[1]??s;if(r<a)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);let u=s6();this.auxBoxWriter.writeBox(u);let f=this.auxWriter.getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,f,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let u=0;u<e.cueQueue.length;u++){let f=e.cueQueue[u];if(f.timestamp>=a)break;Td.lastIndex=0;let d=Td.test(f.text),h=f.timestamp+f.duration,m=e.cueToSourceId.get(f);if(m===void 0&&a<h&&(m=e.nextSourceId++,e.cueToSourceId.set(f,m)),f.notes){let g=a6(f.notes);this.auxBoxWriter.writeBox(g)}let p=o6(f.text,d?s:null,f.identifier??null,f.settings??null,m??null);this.auxBoxWriter.writeBox(p),h===a&&e.cueQueue.splice(u--,1)}let c=this.auxWriter.getSlice(0,this.auxWriter.getPos()),l=this.createSampleForTrack(e,c,s,a-s,"key");await this.registerSample(e,l),e.lastCueEndTimestamp=a}}createSampleForTrack(e,r,n,i,s){return{timestamp:n,decodeTimestamp:n,duration:i,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:fr(i,e.timescale)}}processTimestamps(e,r){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){let i=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){let a=e.timestampProcessingQueue[s],c=fr(a.duration,e.timescale);i+=c}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:i,sampleDelta:1});else{let s=Ze(e.timeToSampleTable);s.sampleCount+=i}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(i=>i.timestamp).sort((i,s)=>i-s);for(let i=0;i<e.timestampProcessingQueue.length;i++){let s=e.timestampProcessingQueue[i];s.decodeTimestamp=n[i],!this.isFragmented&&e.lastTimescaleUnits===null&&(s.decodeTimestamp=0);let a=fr(s.timestamp-s.decodeTimestamp,e.timescale),c=fr(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){x(e.lastSample);let l=fr(s.decodeTimestamp,e.timescale,!1),u=Math.round(l-e.lastTimescaleUnits);if(x(u>=0),e.lastTimescaleUnits+=u,e.lastSample.timescaleUnitsToNextSample=u,!this.isFragmented){let f=Ze(e.timeToSampleTable);if(x(f),f.sampleCount===1){f.sampleDelta=u;let h=e.timeToSampleTable[e.timeToSampleTable.length-2];h&&h.sampleDelta===u&&(h.sampleCount++,e.timeToSampleTable.pop(),f=h)}else f.sampleDelta!==u&&(f.sampleCount--,e.timeToSampleTable.push(f={sampleCount:1,sampleDelta:u}));f.sampleDelta===c?f.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:c});let d=Ze(e.compositionTimeOffsetTable);x(d),d.sampleCompositionTimeOffset===a?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=fr(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:c}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,x(e.lastSample),x(e.lastTimescaleUnits!==null),r!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){x(r.type==="key");let i=fr(r.timestamp,e.timescale,!1),s=Math.round(i-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,r){r.type==="key"&&this.processTimestamps(e,r),e.timestampProcessingQueue.push(r),this.isFragmented?(e.sampleQueue.push(r),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,r):await this.addSampleToTrack(e,r)}async addSampleToTrack(e,r){if(!this.isFragmented&&(e.samples.push(r),this.fastStart==="reserve")){let i=e.track.metadata.maximumPacketCount;if(x(i!==void 0),e.samples.length>i)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${i}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,r.timestamp);let i=r.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let s=this.trackDatas.every(a=>{if(e===a)return r.type==="key";let c=a.sampleQueue[0];return c?c.type==="key":a.track.source._closed});i>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=i>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}),x(e.currentChunk),e.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(e){if(x(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let r=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(r=e.currentChunk.samples.reduce((n,i)=>n+fr(i.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||Ze(e.compactlyCodedChunkTable).samplesPerChunk!==r)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let n of e.currentChunk.samples)x(n.data),this.writer.write(n.data),n.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(x(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let r=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.track.source._closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<n&&(r=s,n=s.sampleQueue[0].timestamp)}if(!r)break;let i=r.sampleQueue.shift();await this.addSampleToTrack(r,i)}}async finalizeFragment(e=!0){x(this.isFragmented);let r=this.nextFragmentNumber++;if(r===1){this.format._options.onMoov&&this.writer.startTrackingWrites();let m=vd(this);if(this.boxWriter.writeBox(m),this.format._options.onMoov){let{data:p,start:g}=this.writer.stopTrackingWrites();this.format._options.onMoov(p,g)}}let n=this.trackDatas.filter(m=>m.currentChunk),i=JI(r,n),s=this.writer.getPos(),a=s+this.boxWriter.measureBox(i),c=a+Ji,l=1/0;for(let m of n){m.currentChunk.offset=c,m.currentChunk.moofOffset=s;for(let p of m.currentChunk.samples)c+=p.size;l=Math.min(l,m.currentChunk.startTimestamp)}let u=c-a,f=u>=2**32;if(f)for(let m of n)m.currentChunk.offset+=zo-Ji;this.format._options.onMoof&&this.writer.startTrackingWrites();let d=JI(r,n);if(this.boxWriter.writeBox(d),this.format._options.onMoof){let{data:m,start:p}=this.writer.stopTrackingWrites();this.format._options.onMoof(m,p,l)}x(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();let h=jp(f);h.size=u,this.boxWriter.writeBox(h),this.writer.seek(a+(f?zo:Ji));for(let m of n)for(let p of m.currentChunk.samples)this.writer.write(p.data),p.data=null;if(this.format._options.onMdat){let{data:m,start:p}=this.writer.stopTrackingWrites();this.format._options.onMdat(m,p)}for(let m of n)m.finalizedChunks.push(m.currentChunk),this.finalizedChunks.push(m.currentChunk),m.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,r){if(this.allTracksAreKnown()){if(!this.mdat){let n=vd(this),s=this.boxWriter.measureBox(n)+this.computeSampleTableSizeUpperBound()+4096;x(this.ftypSize!==null),this.writer.seek(this.ftypSize+s),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=jp(!0),this.boxWriter.writeBox(this.mdat);for(let a of this.trackDatas){for(let c of a.sampleQueue)await this.addSampleToTrack(a,c);a.sampleQueue.length=0}}await this.addSampleToTrack(e,r)}else e.sampleQueue.push(r)}computeSampleTableSizeUpperBound(){x(this.fastStart==="reserve");let e=0;for(let r of this.trackDatas){let n=r.track.metadata.maximumPacketCount;x(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(i=>i.track===e);n&&(n.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let r of this.trackDatas)await this.finalizeCurrentChunk(r);if(this.fastStart==="in-memory"){this.mdat=jp(!1);let r;for(let i=0;i<2;i++){let s=vd(this),a=this.boxWriter.measureBox(s);r=this.boxWriter.measureBox(this.mdat);let c=this.writer.getPos()+a+r;for(let l of this.finalizedChunks){l.offset=c;for(let{data:u}of l.samples)x(u),c+=u.byteLength,r+=u.byteLength}if(c<2**32)break;r>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let n=vd(this);if(this.boxWriter.writeBox(n),this.format._options.onMoov){let{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onMoov(i,s)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(let i of this.finalizedChunks)for(let s of i.samples)x(s.data),this.writer.write(s.data),s.data=null;if(this.format._options.onMdat){let{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(i,s)}}else if(this.isFragmented){let r=this.writer.getPos(),n=i6(this.trackDatas);this.boxWriter.writeBox(n);let i=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(i)}else{x(this.mdat);let r=this.boxWriter.offsets.get(this.mdat);x(r!==void 0);let n=this.writer.getPos()-r;if(this.mdat.size=n,this.mdat.largeSize=n>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,a)}let i=vd(this);if(this.fastStart==="reserve"){x(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);let s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(n6(s))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);if(this.format._options.onMoov){let{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,a)}}e()}}});var Jte,Zte,f6,d6,h6,ere,Hk,m6=he(()=>{Ti();Ue();ik();hI();Id();Vp();qs();Zt();gd();qt();jo();sn();lr();Jte=-(2**15),Zte=2**15-1,f6="Mediabunny",d6=6,h6=5,ere={video:1,audio:2,subtitle:17},Hk=class extends Sr{static{o(this,"MatroskaMuxer")}constructor(e,r){super(e),this.trackDatas=[],this.allTracksKnown=ut(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=new Map,this.duration=0,this.writer=e._writer,this.format=r,this.ebmlWriter=new ek(this.writer),this.format._options.appendOnly&&(this.writer.ensureMonotonicity=!0)}async start(){let e=await this.mutex.acquire();this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();let e={id:I.EBML,data:[{id:I.EBMLVersion,data:1},{id:I.EBMLReadVersion,data:1},{id:I.EBMLMaxIDLength,data:4},{id:I.EBMLMaxSizeLength,data:8},{id:I.DocType,data:this.format instanceof jl?"webm":"matroska"},{id:I.DocTypeVersion,data:2},{id:I.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){let{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(r,n)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;let r=new Uint8Array([28,83,187,107]),n=new Uint8Array([21,73,169,102]),i=new Uint8Array([22,84,174,107]),s=new Uint8Array([25,65,164,105]),a=new Uint8Array([18,84,195,103]),c={id:I.SeekHead,data:[{id:I.Seek,data:[{id:I.SeekID,data:r},{id:I.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:I.Seek,data:[{id:I.SeekID,data:n},{id:I.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:I.Seek,data:[{id:I.SeekID,data:i},{id:I.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:I.Seek,data:[{id:I.SeekID,data:s},{id:I.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:I.Seek,data:[{id:I.SeekID,data:a},{id:I.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=c}createSegmentInfo(){let e={id:I.Duration,data:new cd(0)};this.segmentDuration=e;let r={id:I.Info,data:[{id:I.TimestampScale,data:1e6},{id:I.MuxingApp,data:f6},{id:I.WritingApp,data:f6},this.format._options.appendOnly?null:e]};this.segmentInfo=r}createTracks(){let e={id:I.Tracks,data:[]};this.tracksElement=e;for(let r of this.trackDatas){let n=on[r.track.source._codec];x(n);let i=0;if(r.type==="audio"&&r.track.source._codec==="opus"){i=1e6*80;let s=r.info.decoderConfig.description;if(s){let a=qe(s),c=Ja(a);i=Math.round(1e9*(c.preSkip/Qi))}}e.data.push({id:I.TrackEntry,data:[{id:I.TrackNumber,data:r.track.id},{id:I.TrackUID,data:r.track.id},{id:I.TrackType,data:ere[r.type]},r.track.metadata.disposition?.default===!1?{id:I.FlagDefault,data:0}:null,r.track.metadata.disposition?.forced?{id:I.FlagForced,data:1}:null,r.track.metadata.disposition?.hearingImpaired?{id:I.FlagHearingImpaired,data:1}:null,r.track.metadata.disposition?.visuallyImpaired?{id:I.FlagVisualImpaired,data:1}:null,r.track.metadata.disposition?.original?{id:I.FlagOriginal,data:1}:null,r.track.metadata.disposition?.commentary?{id:I.FlagCommentary,data:1}:null,{id:I.FlagLacing,data:0},{id:I.Language,data:r.track.metadata.languageCode??Ft},{id:I.CodecID,data:n},{id:I.CodecDelay,data:0},{id:I.SeekPreRoll,data:i},r.track.metadata.name!==void 0?{id:I.Name,data:new es(r.track.metadata.name)}:null,r.type==="video"?this.videoSpecificTrackInfo(r):null,r.type==="audio"?this.audioSpecificTrackInfo(r):null,r.type==="subtitle"?this.subtitleSpecificTrackInfo(r):null]})}}videoSpecificTrackInfo(e){let{frameRate:r,rotation:n}=e.track.metadata,i=[e.info.decoderConfig.description?{id:I.CodecPrivate,data:qe(e.info.decoderConfig.description)}:null,r?{id:I.DefaultDuration,data:1e9/r}:null],s=n?Ha(-n):0,a=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,c=e.info.decoderConfig.colorSpace,l={id:I.Video,data:[{id:I.PixelWidth,data:e.info.width},{id:I.PixelHeight,data:e.info.height},a?{id:I.DisplayWidth,data:e.info.aspectRatio.num}:null,a?{id:I.DisplayHeight,data:e.info.aspectRatio.den}:null,a?{id:I.DisplayUnit,data:3}:null,e.info.alphaMode?{id:I.AlphaMode,data:1}:null,kx(c)?{id:I.Colour,data:[{id:I.MatrixCoefficients,data:Yi[c.matrix]},{id:I.TransferCharacteristics,data:qi[c.transfer]},{id:I.Primaries,data:ji[c.primaries]},{id:I.Range,data:c.fullRange?2:1}]}:null,s?{id:I.Projection,data:[{id:I.ProjectionType,data:0},{id:I.ProjectionPoseRoll,data:new ad((s+180)%360-180)}]}:null]};return i.push(l),i}audioSpecificTrackInfo(e){let r=ht.includes(e.track.source._codec)?_r(e.track.source._codec):null;return[e.info.decoderConfig.description?{id:I.CodecPrivate,data:qe(e.info.decoderConfig.description)}:null,{id:I.Audio,data:[{id:I.SamplingFrequency,data:new ad(e.info.sampleRate)},{id:I.Channels,data:e.info.numberOfChannels},r?{id:I.BitDepth,data:8*r.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[{id:I.CodecPrivate,data:lt.encode(e.info.config.description)}]}maybeCreateTags(){let e=[],r=o((s,a)=>{e.push({id:I.SimpleTag,data:[{id:I.TagName,data:new es(s)},typeof a=="string"?{id:I.TagString,data:new es(a)}:{id:I.TagBinary,data:a}]})},"addSimpleTag"),n=this.output._metadataTags,i=new Set;for(let{key:s,value:a}of Gi(n))switch(s){case"title":r("TITLE",a),i.add("TITLE");break;case"description":r("DESCRIPTION",a),i.add("DESCRIPTION");break;case"artist":r("ARTIST",a),i.add("ARTIST");break;case"album":r("ALBUM",a),i.add("ALBUM");break;case"albumArtist":r("ALBUM_ARTIST",a),i.add("ALBUM_ARTIST");break;case"genre":r("GENRE",a),i.add("GENRE");break;case"comment":r("COMMENT",a),i.add("COMMENT");break;case"lyrics":r("LYRICS",a),i.add("LYRICS");break;case"date":r("DATE",a.toISOString().slice(0,10)),i.add("DATE");break;case"trackNumber":{let c=n.tracksTotal!==void 0?`${a}/${n.tracksTotal}`:a.toString();r("PART_NUMBER",c),i.add("PART_NUMBER")}break;case"discNumber":{let c=n.discsTotal!==void 0?`${a}/${n.discsTotal}`:a.toString();r("DISC",c),i.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:kt(s)}if(n.raw)for(let s in n.raw){let a=n.raw[s];a==null||i.has(s)||(typeof a=="string"||a instanceof Uint8Array)&&r(s,a)}e.length!==0&&(this.tagsElement={id:I.Tags,data:[{id:I.Tag,data:[{id:I.Targets,data:[{id:I.TargetTypeValue,data:50},{id:I.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){let e=this.output._metadataTags,r=[],n=new Set,i=e.images??[];for(let s of i){let a=s.name;a===void 0&&(a=(s.kind==="coverFront"?"cover":s.kind==="coverBack"?"back":"image")+(Pz(s.mimeType)??""));let c;for(;;){c=0n;for(let l=0;l<8;l++)c<<=8n,c|=BigInt(Math.floor(Math.random()*256));if(c!==0n&&!n.has(c))break}n.add(c),r.push({id:I.AttachedFile,data:[s.description!==void 0?{id:I.FileDescription,data:new es(s.description)}:null,{id:I.FileName,data:new es(a)},{id:I.FileMediaType,data:s.mimeType},{id:I.FileData,data:s.data},{id:I.FileUID,data:c}]})}for(let[s,a]of Object.entries(e.raw??{}))!(a instanceof Oo)||!/^\d+$/.test(s)||i.find(l=>l.mimeType===a.mimeType&&Dz(l.data,a.data))||r.push({id:I.AttachedFile,data:[a.description!==void 0?{id:I.FileDescription,data:new es(a.description)}:null,{id:I.FileName,data:new es(a.name??"")},{id:I.FileMediaType,data:a.mimeType??""},{id:I.FileData,data:a.data},{id:I.FileUID,data:BigInt(s)}]});r.length!==0&&(this.attachmentsElement={id:I.Attachments,data:r})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);let e={id:I.Segment,size:this.format._options.appendOnly?-1:d6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){let{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(r,n)}}createCues(){this.cues={id:I.Cues,data:[]}}get segmentDataOffset(){return x(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return sk({isWebM:this.format instanceof jl,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,n){let i=this.trackDatas.find(u=>u.track===e);if(i)return i;Kf(n),x(n),x(n.decoderConfig),x(n.decoderConfig.codedWidth!==void 0),x(n.decoderConfig.codedHeight!==void 0);let s=n.decoderConfig.displayAspectWidth,a=n.decoderConfig.displayAspectHeight,c=s===void 0||a===void 0?null:qa({num:s,den:a}),l={track:e,type:"video",info:{width:n.decoderConfig.codedWidth,height:n.decoderConfig.codedHeight,aspectRatio:c,decoderConfig:n.decoderConfig,alphaMode:!!r.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null};return e.source._codec==="vp9"?l.info.decoderConfig={...l.info.decoderConfig,description:new Uint8Array(Uz(l.info.decoderConfig.codec))}:e.source._codec==="av1"&&(l.info.decoderConfig={...l.info.decoderConfig,description:new Uint8Array(Px(l.info.decoderConfig.codec))}),this.trackDatas.push(l),this.trackDatas.sort((u,f)=>u.track.id-f.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),l}getAudioTrackData(e,r,n){let i=this.trackDatas.find(l=>l.track===e);if(i)return i;En(n),x(n),x(n.decoderConfig);let s={...n.decoderConfig},a=!1;if(e.source._codec==="aac"&&!s.description){let l=Dn(xr.tempFromBytes(r.data));if(!l)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let u=vi[l.samplingFrequencyIndex],f=Ws[l.channelConfiguration];if(u===void 0||f===void 0)throw new Error("Invalid ADTS frame header.");s.description=Yf({objectType:l.objectType,sampleRate:u,numberOfChannels:f}),a=!0}let c={track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresAdtsStripping:a},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(c),this.trackDatas.sort((l,u)=>l.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Ix(r),x(r),x(r.config);let i={track:e,type:"subtitle",info:{config:r.config},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(i),this.trackDatas.sort((s,a)=>s.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,r,n){let i=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,n),a=r.type==="key",c=this.validateAndNormalizeTimestamp(s.track,r.timestamp,a),l=r.duration;e.metadata.frameRate!==void 0&&(c=ep(c,1/e.metadata.frameRate),l=ep(l,1/e.metadata.frameRate));let u=s.info.alphaMode?r.sideData.alpha??null:null,f=this.createInternalChunk(r.data,c,l,r.type,u);e.source._codec==="vp9"&&this.fixVP9ColorSpace(s,f),s.chunkQueue.push(f),await this.interleaveChunks()}finally{i()}}async addEncodedAudioPacket(e,r,n){let i=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,n),a=r.data;if(s.info.requiresAdtsStripping){let f=Dn(xr.tempFromBytes(a));if(!f)throw new Error("Expected ADTS frame, didn't get one.");let d=f.crcCheck===null?Wo:Jn;a=a.subarray(d)}let c=r.type==="key",l=this.validateAndNormalizeTimestamp(s.track,r.timestamp,c),u=this.createInternalChunk(a,l,r.duration,r.type);s.chunkQueue.push(u),await this.interleaveChunks()}finally{i()}}async addSubtitleCue(e,r,n){let i=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n),a=this.validateAndNormalizeTimestamp(s.track,r.timestamp,!0),c=r.text,l=Math.round(a*1e3);Td.lastIndex=0,c=c.replace(Td,h=>{let p=Ak(h.slice(1,-1))-l;return`<${Fk(p)}>`});let u=lt.encode(c),f=`${r.settings??""}
|
|
30
30
|
${r.identifier??""}
|
|
31
31
|
${r.notes??""}`,d=this.createInternalChunk(u,a,r.duration,"key",f.trim()?lt.encode(f):null);s.chunkQueue.push(d),await this.interleaveChunks()}finally{i()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let r=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.chunkQueue.length===0&&!s.track.source._closed)break e;s.chunkQueue.length>0&&s.chunkQueue[0].timestamp<n&&(r=s,n=s.chunkQueue[0].timestamp)}if(!r)break;let i=r.chunkQueue.shift();this.writeBlock(r,i)}e||await this.writer.flush()}}fixVP9ColorSpace(e,r){if(r.type!=="key"||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;let n=new Te(r.data);n.skipBits(2);let i=n.readBits(1),a=(n.readBits(1)<<1)+i;if(a===3&&n.skipBits(1),n.readBits(1)||n.readBits(1)!==0||(n.skipBits(2),n.readBits(24)!==4817730))return;a>=2&&n.skipBits(1);let f={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];bz(r.data,n.pos,n.pos+3,f)}createInternalChunk(e,r,n,i,s=null){return{data:e,type:i,timestamp:r,duration:n,additions:s}}writeBlock(e,r){this.segment||this.createSegment();let n=Math.round(1e3*r.timestamp),i=this.trackDatas.every(f=>{if(e===f)return r.type==="key";let d=f.chunkQueue[0];return d?d.type==="key":f.track.source._closed}),s=!1;if(!this.currentCluster)s=!0;else{x(this.currentClusterStartMsTimestamp!==null),x(this.currentClusterMaxMsTimestamp!==null);let f=n-this.currentClusterStartMsTimestamp;s=i&&n>this.currentClusterMaxMsTimestamp&&f>=1e3*(this.format._options.minimumClusterDuration??1)||f>Zte}s&&this.createNewCluster(n);let a=n-this.currentClusterStartMsTimestamp;if(a<Jte)return;let c=new Uint8Array(4),l=new DataView(c.buffer);l.setUint8(0,128|e.track.id),l.setInt16(1,a,!1);let u=Math.round(1e3*r.duration);if(r.additions){let f={id:I.BlockGroup,data:[{id:I.Block,data:[c,r.data]},r.type==="delta"?{id:I.ReferenceBlock,data:new kp(e.lastWrittenMsTimestamp-n)}:null,r.additions?{id:I.BlockAdditions,data:[{id:I.BlockMore,data:[{id:I.BlockAddID,data:1},{id:I.BlockAdditional,data:r.additions}]}]}:null,u>0?{id:I.BlockDuration,data:u}:null]};this.ebmlWriter.writeEBML(f)}else{l.setUint8(3,+(r.type==="key")<<7);let f={id:I.SimpleBlock,data:[c,r.data]};this.ebmlWriter.writeEBML(f)}this.duration=Math.max(this.duration,n+u),e.lastWrittenMsTimestamp=n,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:n}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,n)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:I.Cluster,size:this.format._options.appendOnly?-1:h6,data:[{id:I.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(x(this.currentCluster),!this.format._options.appendOnly){let i=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),s=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(i,h6),this.writer.seek(s)}if(this.format._options.onCluster){x(this.currentClusterStartMsTimestamp!==null);let{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onCluster(i,s,this.currentClusterStartMsTimestamp/1e3)}let e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,r=new Map;for(let[i,{firstMsTimestamp:s}]of this.trackDatasInCurrentCluster)r.has(s)||r.set(s,[]),r.get(s).push(i);let n=[...r.entries()].sort((i,s)=>i[0]-s[0]);for(let[i,s]of n)x(this.cues),this.cues.data.push({id:I.CuePoint,data:[{id:I.CueTime,data:i},...s.map(a=>({id:I.CueTrackPositions,data:[{id:I.CueTrack,data:a.track.id},{id:I.CueClusterPosition,data:e}]}))]})}async onTrackClose(){let e=await this.mutex.acquire();this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),e()}async finalize(){let e=await this.mutex.acquire();if(this.allTracksKnown.resolve(),this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),x(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let r=this.writer.getPos(),n=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(n,d6),this.segmentDuration.data=new cd(this.duration),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),x(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead),this.writer.seek(r)}e()}}});var Vk,p6=he(()=>{Ka();Vk=class{static{o(this,"Mp3Writer")}constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(e){let r=this.writer.getPos(),n=255,i=224|e.mpegVersionId<<3|e.layer<<1,s;e.mpegVersionId&2?s=e.mpegVersionId&1?0:1:s=1;let a=0,c=155,l=-1,u=s*16*4+e.layer*16;for(let y=0;y<16;y++){let b=_x[u+y];if(Dx(s,e.layer,1e3*b,e.sampleRate,a)>=c){l=y;break}}if(l===-1)throw new Error("No suitable bitrate found.");let f=l<<4|e.frequencyIndex<<2|a<<1,d=e.channel<<6|e.modeExtension<<4|e.copyright<<3|e.original<<2|e.emphasis;this.helper[0]=n,this.helper[1]=i,this.helper[2]=f,this.helper[3]=d,this.writer.write(this.helper.subarray(0,4));let h=Qa(e.mpegVersionId,e.channel);this.writer.seek(r+h),this.writeU32(Ga);let m=0;e.frameCount!==null&&(m|=1),e.fileSize!==null&&(m|=2),e.toc!==null&&(m|=4),this.writeU32(m),this.writeU32(e.frameCount??0),this.writeU32(e.fileSize??0),this.writer.write(e.toc??new Uint8Array(100));let p=_x[u+l],g=Dx(s,e.layer,1e3*p,e.sampleRate,a);this.writer.seek(r+g)}}});var Wk,g6=he(()=>{Ue();lr();jo();Ka();p6();sc();Wk=class extends Sr{static{o(this,"Mp3Muxer")}constructor(e,r){super(e),this.xingFrameData=null,this.frameCount=0,this.framePositions=[],this.xingFramePos=null,this.format=r,this.writer=e._writer,this.mp3Writer=new Vk(e._writer)}async start(){Ro(this.output._metadataTags)||new ac(this.writer).writeId3V2Tag(this.output._metadataTags)}async getMimeType(){return"audio/mpeg"}async addEncodedVideoPacket(){throw new Error("MP3 does not support video.")}async addEncodedAudioPacket(e,r){let n=await this.mutex.acquire();try{let i=this.format._options.xingHeader!==!1;if(!this.xingFrameData&&i){let s=ge(r.data);if(s.byteLength<4)throw new Error("Invalid MP3 header in sample.");let a=s.getUint32(0,!1),c=Ol(a,null).header;if(!c)throw new Error("Invalid MP3 header in sample.");let l=Qa(c.mpegVersionId,c.channel);if(s.byteLength>=l+4){let u=s.getUint32(l,!1);if(u===Ga||u===Xf)return}this.xingFrameData={mpegVersionId:c.mpegVersionId,layer:c.layer,frequencyIndex:c.frequencyIndex,sampleRate:c.sampleRate,channel:c.channel,modeExtension:c.modeExtension,copyright:c.copyright,original:c.original,emphasis:c.emphasis,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.validateAndNormalizeTimestamp(e,r.timestamp,r.type==="key"),this.writer.write(r.data),this.frameCount++,await this.writer.flush(),i&&this.framePositions.push(this.writer.getPos())}finally{n()}}async addSubtitleCue(){throw new Error("MP3 does not support subtitles.")}async finalize(){if(!this.xingFrameData||this.xingFramePos===null)return;let e=await this.mutex.acquire(),r=this.writer.getPos();this.writer.seek(this.xingFramePos);let n=new Uint8Array(100);for(let i=0;i<100;i++){let s=Math.floor(this.framePositions.length*(i/100));x(s!==-1&&s<this.framePositions.length);let a=this.framePositions[s];n[i]=256*(a/r)}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=r,this.xingFrameData.toc=n,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){let{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(i,s)}this.writer.seek(r),e()}}});var tre,jk,y6=he(()=>{Zt();sn();Ue();jo();hk();wI();tre=8192,jk=class extends Sr{static{o(this,"OggMuxer")}constructor(e,r){super(e),this.trackDatas=[],this.bosPagesWritten=!1,this.allTracksKnown=ut(),this.pageBytes=new Uint8Array(mk),this.pageView=new DataView(this.pageBytes.buffer),this.format=r,this.writer=e._writer,this.writer.ensureMonotonicity=!0}async start(){}async getMimeType(){return await this.allTracksKnown.promise,dk({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(e,r){let n=this.trackDatas.find(a=>a.track===e);if(n)return n;let i;do i=Math.floor(2**32*Math.random());while(this.trackDatas.some(a=>a.serialNumber===i));x(e.source._codec==="vorbis"||e.source._codec==="opus"),En(r),x(r),x(r.decoderConfig);let s={track:e,serialNumber:i,internalSampleRate:e.source._codec==="opus"?Qi:r.decoderConfig.sampleRate,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],currentTimestampInSamples:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0};return this.queueHeaderPackets(s,r),this.trackDatas.push(s),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}queueHeaderPackets(e,r){if(x(r.decoderConfig),e.track.source._codec==="vorbis"){x(r.decoderConfig.description);let n=qe(r.decoderConfig.description);if(n[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let i=1,s=o(()=>{let g=0;for(;;){let y=n[i++];if(y===void 0)throw new TypeError("Vorbis decoder description is too short.");if(g+=y,y<255)return g}},"readPacketLength"),a=s(),c=s();if(n.length-i<=0)throw new TypeError("Vorbis decoder description is too short.");let u=n.subarray(i,i+=a);i+=c;let f=n.subarray(i),d=new Uint8Array(7);d[0]=3,d[1]=118,d[2]=111,d[3]=114,d[4]=98,d[5]=105,d[6]=115;let h=op(d,this.output._metadataTags,!0);e.packetQueue.push({data:u,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:h,timestampInSamples:0,durationInSamples:0,forcePageFlush:!1},{data:f,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0});let p=ge(u).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(p&15),1<<(p>>4)],modeBlockflags:zx(f).modeBlockflags}}else if(e.track.source._codec==="opus"){if(!r.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");let n=qe(r.decoderConfig.description),i=new Uint8Array(8),s=ge(i);s.setUint32(0,1332770163,!1),s.setUint32(4,1415669619,!1);let a=op(i,this.output._metadataTags,!0);e.packetQueue.push({data:n,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:a,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:Ja(n).preSkip}}}async addEncodedAudioPacket(e,r,n){let i=await this.mutex.acquire();try{let s=this.getTrackData(e,n);this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key");let a=s.currentTimestampInSamples,{durationInSamples:c,vorbisBlockSize:l}=fk(r.data,s.codecInfo,s.vorbisLastBlocksize);s.currentTimestampInSamples+=c,s.vorbisLastBlocksize=l,s.packetQueue.push({data:r.data,timestampInSamples:a,durationInSamples:c,forcePageFlush:!1}),await this.interleavePages()}finally{i()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown()&&!e)return;for(let r of this.trackDatas)for(;r.packetQueue.length>0;){let n=r.packetQueue.shift();if(this.writePacket(r,n,!1),n.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let r=null,n=1/0;for(let a of this.trackDatas){if(!e&&a.packetQueue.length<=1&&!a.track.source._closed)break e;a.packetQueue.length>0&&a.packetQueue[0].timestampInSamples<n&&(r=a,n=a.packetQueue[0].timestampInSamples)}if(!r)break;let i=r.packetQueue.shift(),s=r.packetQueue.length===0;this.writePacket(r,i,s)}e||await this.writer.flush()}writePacket(e,r,n){let i=r.timestampInSamples+r.durationInSamples;if(this.format._options.maximumPageDuration!==void 0){let u=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&i-e.currentPageStartTimestampInSamples>u&&this.writePage(e,!1)}let s=r.data.length,a=0,c=0;for(;;){e.currentLacingValues.length===0&&a>0&&(e.currentPageStartsWithFreshPacket=!1);let u=Math.min(255,s);e.currentLacingValues.push(u),e.currentPageSize++,c+=u;let f=s<255;if(e.currentLacingValues.length===255){let d=r.data.subarray(a,c);if(a=c,e.currentPageData.push(d),e.currentPageSize+=d.length,this.writePage(e,n&&f),f)return}if(f)break;s-=255}let l=r.data.subarray(a);e.currentPageData.push(l),e.currentPageSize+=l.length,e.currentGranulePosition=i,(e.currentPageSize>=tre||r.forcePageFlush)&&this.writePage(e,n)}writePage(e,r){this.pageView.setUint32(0,Cp,!0),this.pageView.setUint8(4,0);let n=0;e.currentPageStartsWithFreshPacket||(n|=1),e.pagesWritten===0&&(n|=2),r&&(n|=4),this.pageView.setUint8(5,n);let i=e.currentLacingValues.every(l=>l===255)?-1:e.currentGranulePosition;Tz(this.pageView,6,i,!0),this.pageView.setUint32(14,e.serialNumber,!0),this.pageView.setUint32(18,e.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,e.currentLacingValues.length),this.pageBytes.set(e.currentLacingValues,27);let s=27+e.currentLacingValues.length;for(let l of e.currentPageData)this.pageBytes.set(l,s),s+=l.length;let a=this.pageBytes.subarray(0,s),c=uk(a);if(this.pageView.setUint32(22,c,!0),e.pagesWritten++,e.currentLacingValues.length=0,e.currentPageData.length=0,e.currentPageSize=27,e.currentPageStartsWithFreshPacket=!0,e.currentPageStartTimestampInSamples=e.currentGranulePosition,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(a),this.format._options.onPage){let{data:l,start:u}=this.writer.stopTrackingWrites();this.format._options.onPage(l,u,e.track.source)}}async onTrackClose(){let e=await this.mutex.acquire();this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages(),e()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),await this.interleavePages(!0);for(let r of this.trackDatas)r.currentLacingValues.length>0&&this.writePage(r,!0);e()}}});var rre,b6,w6,nre,x6,k6,S6,qk,ire,T6,v6,ql,sre,E6=he(()=>{qs();Zt();sn();Ti();Ue();jo();Tk();rre=0,b6=4096,w6=256,nre=224,x6=192,k6=new Uint8Array([9,240]),S6=new Uint8Array([70,1]),qk=class extends Sr{static{o(this,"MpegTsMuxer")}constructor(e,r){super(e),this.trackDatas=[],this.tablesWritten=!1,this.continuityCounters=new Map,this.packetBuffer=new Uint8Array(188),this.packetView=ge(this.packetBuffer),this.allTracksKnown=ut(),this.videoTrackIndex=0,this.audioTrackIndex=0,this.adaptationFieldBuffer=new Uint8Array(184),this.payloadBuffer=new Uint8Array(184),this.format=r,this.writer=e._writer,this.writer.ensureMonotonicity=!0}async start(){}async getMimeType(){return await this.allTracksKnown.promise,Sk(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,r){let n=this.trackDatas.find(u=>u.track===e);if(n)return n;Kf(r),x(r?.decoderConfig);let i=e.source._codec;x(i==="avc"||i==="hevc");let s=i==="avc"?27:36,a=w6+this.trackDatas.length,c=nre+this.videoTrackIndex++,l={track:e,pid:a,streamType:s,streamId:c,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1};return this.trackDatas.push(l),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),l}getAudioTrackData(e,r){let n=this.trackDatas.find(u=>u.track===e);if(n)return n;En(r),x(r?.decoderConfig);let i=e.source._codec;x(i==="aac"||i==="mp3"||i==="ac3"||i==="eac3");let s,a;switch(i){case"aac":s=15,a=x6+this.audioTrackIndex++;break;case"mp3":s=3,a=x6+this.audioTrackIndex++;break;case"ac3":s=129,a=189;break;case"eac3":s=135,a=189;break}let c=w6+this.trackDatas.length,l={track:e,pid:c,streamType:s,streamId:a,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1};return this.trackDatas.push(l),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),l}async addEncodedVideoPacket(e,r,n){let i=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,n),a=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),c=this.prepareVideoPacket(s,r,n);r.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:c,presentationTimestamp:a,decodeTimestamp:null,isKeyframe:r.type==="key"})}finally{i()}}async addEncodedAudioPacket(e,r,n){let i=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,n),a=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),c=this.prepareAudioPacket(s,r,n);r.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:c,presentationTimestamp:a,decodeTimestamp:null,isKeyframe:r.type==="key"})}finally{i()}}async addSubtitleCue(){throw new Error("MPEG-TS does not support subtitles.")}prepareVideoPacket(e,r,n){let i=e.track.source._codec;if(e.inputIsAnnexB===null){let s=n?.decoderConfig?.description;if(e.inputIsAnnexB=!s,!e.inputIsAnnexB){let a=qe(s);i==="avc"?e.avcDecoderConfig=Fx(a):e.hevcDecoderConfig=Jz(a)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(r.data,i):this.prepareLengthPrefixedVideoPacket(e,r,i)}prepareAnnexBVideoPacket(e,r){let n=[];for(let s of Xa(e)){let a=e.subarray(s.offset,s.offset+s.length);(r==="avc"?Ao(a[0])===Cn.AUD:Gs(a[0])===vt.AUD_NUT)||n.push(a)}let i=r==="avc"?k6:S6;return n.unshift(i),Ax(n)}prepareLengthPrefixedVideoPacket(e,r,n){let i=r.data,s=n==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,a=[];for(let l of Nx(i,s)){let u=i.subarray(l.offset,l.offset+l.length);(n==="avc"?Ao(u[0])===Cn.AUD:Gs(u[0])===vt.AUD_NUT)||a.push(u)}if(r.type==="key")if(n==="avc"){let l=e.avcDecoderConfig;for(let u of l.pictureParameterSets)a.unshift(u);for(let u of l.sequenceParameterSets)a.unshift(u)}else{let l=e.hevcDecoderConfig;for(let u of l.arrays)if(u.nalUnitType===vt.PPS_NUT)for(let f of u.nalUnits)a.unshift(f);for(let u of l.arrays)if(u.nalUnitType===vt.SPS_NUT)for(let f of u.nalUnits)a.unshift(f);for(let u of l.arrays)if(u.nalUnitType===vt.VPS_NUT)for(let f of u.nalUnits)a.unshift(f)}let c=n==="avc"?k6:S6;return a.unshift(c),Ax(a)}prepareAudioPacket(e,r,n){let i=e.track.source._codec;if(i==="mp3"||i==="ac3"||i==="eac3")return r.data;if(e.inputIsAdts===null){let l=n?.decoderConfig?.description;if(e.inputIsAdts=!l,!e.inputIsAdts){let u=js(qe(l)),f=Ex(u);e.adtsHeader=f.header,e.adtsHeaderBitstream=f.bitstream}}if(e.inputIsAdts)return r.data;x(e.adtsHeader),x(e.adtsHeaderBitstream);let s=e.adtsHeader,a=r.data.byteLength+s.byteLength;Cx(e.adtsHeaderBitstream,a);let c=new Uint8Array(a);return c.set(s,0),c.set(r.data,s.byteLength),c}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async flushTimestampQueue(e,r=!0){if(e.timestampProcessingQueue.length===0)return;let n=e.timestampProcessingQueue.map(i=>i.presentationTimestamp).sort((i,s)=>i-s);for(let i=0;i<e.timestampProcessingQueue.length;i++){let s=e.timestampProcessingQueue[i];s.decodeTimestamp=n[i],e.packetQueue.push(s)}e.timestampProcessingQueue.length=0,r&&await this.interleavePackets()}async interleavePackets(e=!1){if(!this.tablesWritten){if(!this.allTracksAreKnown()&&!e)return;this.writeTables()}e:for(;;){let r=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.packetQueue.length===0&&!s.track.source._closed)break e;s.packetQueue.length>0&&s.packetQueue[0].presentationTimestamp<n&&(r=s,n=s.packetQueue[0].presentationTimestamp)}if(!r)break;let i=r.packetQueue.shift();this.writePesPacket(r,i)}e||await this.writer.flush()}writeTables(){x(!this.tablesWritten),this.writePsiSection(rre,ql),this.writePsiSection(b6,sre(this.trackDatas)),this.tablesWritten=!0}writePsiSection(e,r){let n=0,i=!0;for(;n<r.length;){let a=184-(i?1:0),c=r.length-n,l=Math.min(a,c),u;i?(u=this.payloadBuffer.subarray(0,1+l),u[0]=0,u.set(r.subarray(n,n+l),1)):u=r.subarray(n,n+l),this.writeTsPacket(e,i,null,u),n+=l,i=!1}}writePesPacket(e,r){let n=e.track.type==="video",i=n?10:5,s=new Uint8Array(9+i),a=ge(s),c=new Te(s.subarray(9));Dl(a,0,1,!1),s[3]=e.streamId;let l=e.track.type==="video"?0:Math.min(8+r.data.length,65535);a.setUint16(4,l,!1),a.setUint8(6,132),a.setUint8(7,n?192:128),a.setUint8(8,i);let u=Math.round(r.presentationTimestamp*9e4);if(c.pos=0,c.writeBits(4,n?3:2),c.writeBits(3,u>>>30&7),c.writeBits(1,1),c.writeBits(15,u>>>15&32767),c.writeBits(1,1),c.writeBits(15,u&32767),c.writeBits(1,1),n){x(r.decodeTimestamp!==null);let m=Math.round(r.decodeTimestamp*9e4);c.writeBits(4,1),c.writeBits(3,m>>>30&7),c.writeBits(1,1),c.writeBits(15,m>>>15&32767),c.writeBits(1,1),c.writeBits(15,m&32767),c.writeBits(1,1)}let f=s.length+r.data.length,d=0,h=!0;for(;d<f;){let m=h,p=f-d,g=h&&r.isKeyframe,y=h&&!e.firstPacketWritten,b=Math.max(0,184-p),w;g||y?w=Math.max(2,b):w=b;let k=null;if(w>0){let N=this.adaptationFieldBuffer;w===1?N[0]=0:(N[0]=w-1,N[1]=Number(y)<<7|Number(g)<<6,N.fill(255,2,w)),k=N.subarray(0,w)}let T=Math.min(184-w,p),v=this.payloadBuffer.subarray(0,T),S=0;if(d<s.length){let N=Math.min(s.length-d,T);v.set(s.subarray(d,d+N),0),S=N}let M=Math.max(0,d-s.length),P=M+(T-S);S<T&&v.set(r.data.subarray(M,P),S),this.writeTsPacket(e.pid,m,k,v),d+=T,h=!1}e.firstPacketWritten=!0}writeTsPacket(e,r,n,i){let s=this.continuityCounters.get(e)??0,a=i.length>0,c=n?a?3:2:a?1:0;this.packetBuffer[0]=71,this.packetView.setUint16(1,(r?16384:0)|e&8191,!1),this.packetBuffer[3]=c<<4|s&15,a&&this.continuityCounters.set(e,s+1&15);let l=4;n&&(this.packetBuffer.set(n,l),l+=n.length),this.packetBuffer.set(i,l),l+=i.length,l<188&&this.packetBuffer.fill(255,l);let u=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),u)}async onTrackClose(e){let r=await this.mutex.acquire();this.allTracksAreKnown()&&this.allTracksKnown.resolve();let n=this.trackDatas.find(i=>i.track===e);n&&await this.flushTimestampQueue(n,!1),await this.interleavePackets(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)await this.flushTimestampQueue(r,!1);await this.interleavePackets(!0),e()}},ire=79764919,T6=new Uint32Array(256);for(let t=0;t<256;t++){let e=t<<24;for(let r=0;r<8;r++)e=e&2147483648?e<<1^ire:e<<1;T6[t]=e>>>0&4294967295}v6=o(t=>{let e=4294967295;for(let r=0;r<t.length;r++){let n=t[r];e=(e<<8^T6[e>>>24^n])>>>0}return e},"computeMpegTsCrc32"),ql=new Uint8Array(16);{let t=ge(ql);ql[0]=0,t.setUint16(1,45069,!1),t.setUint16(3,1,!1),ql[5]=193,ql[6]=0,ql[7]=0,t.setUint16(8,1,!1),t.setUint16(10,57344|b6&8191,!1),t.setUint32(12,v6(ql.subarray(0,12)),!1)}sre=o(t=>{let e=0;for(let l of t)e+=5,l.streamType===129?e+=cp.length:l.streamType===135&&(e+=lp.length);let r=9+e+4,n=new Uint8Array(3+r-4),i=ge(n);n[0]=2,i.setUint16(1,45056|r&4095,!1),i.setUint16(3,1,!1),n[5]=193,n[6]=0,n[7]=0,i.setUint16(8,65535,!1),i.setUint16(10,61440,!1);let s=12;for(let l of t)n[s++]=l.streamType,i.setUint16(s,57344|l.pid&8191,!1),s+=2,l.streamType===129?(i.setUint16(s,61440|cp.length,!1),s+=2,n.set(cp,s),s+=cp.length):l.streamType===135?(i.setUint16(s,61440|lp.length,!1),s+=2,n.set(lp,s),s+=lp.length):(i.setUint16(s,61440,!1),s+=2);let a=v6(n),c=new Uint8Array(n.length+4);return c.set(n,0),ge(c).setUint32(n.length,a,!1),c},"buildPmt")});var Yk,C6=he(()=>{Yk=class{static{o(this,"RiffWriter")}constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU16(e){this.helperView.setUint16(0,e,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,e,!0),this.helperView.setUint32(4,Math.floor(e/2**32),!0),this.writer.write(this.helper)}writeAscii(e){this.writer.write(new TextEncoder().encode(e))}}});var Gk,P6=he(()=>{jo();Zt();TI();C6();Ue();lr();sc();Gk=class extends Sr{static{o(this,"WaveMuxer")}constructor(e,r){super(e),this.headerWritten=!1,this.dataSize=0,this.sampleRate=null,this.sampleCount=0,this.riffSizePos=null,this.dataSizePos=null,this.ds64RiffSizePos=null,this.ds64DataSizePos=null,this.ds64SampleCountPos=null,this.format=r,this.writer=e._writer,this.riffWriter=new Yk(e._writer),this.isRf64=!!r._options.large}async start(){}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,r,n){let i=await this.mutex.acquire();try{if(this.headerWritten||(En(n),x(n),x(n.decoderConfig),this.writeHeader(e,n.decoderConfig),this.sampleRate=n.decoderConfig.sampleRate,this.headerWritten=!0),this.validateAndNormalizeTimestamp(e,r.timestamp,r.type==="key"),!this.isRf64&&this.writer.getPos()+r.data.byteLength>=2**32)throw new Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(r.data),this.dataSize+=r.data.byteLength,this.sampleCount+=Math.round(r.duration*this.sampleRate),await this.writer.flush()}finally{i()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,r){this.format._options.onHeader&&this.writer.startTrackingWrites();let n,i=e.source._codec,s=_r(i);s.dataType==="ulaw"?n=_n.MULAW:s.dataType==="alaw"?n=_n.ALAW:s.dataType==="float"?n=_n.IEEE_FLOAT:n=_n.PCM;let a=r.numberOfChannels,c=r.sampleRate,l=s.sampleSize*a;if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64DataSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(n),this.riffWriter.writeU16(a),this.riffWriter.writeU32(c),this.riffWriter.writeU32(c*l),this.riffWriter.writeU16(l),this.riffWriter.writeU16(8*s.sampleSize),!Ro(this.output._metadataTags)){let u=this.format._options.metadataFormat??"info";u==="info"?this.writeInfoChunk(this.output._metadataTags):u==="id3"?this.writeId3Chunk(this.output._metadataTags):kt(u)}if(this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.format._options.onHeader){let{data:u,start:f}=this.writer.stopTrackingWrites();this.format._options.onHeader(u,f)}}writeInfoChunk(e){let r=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");let n=new Set,i=o((c,l)=>{if(!Va(l)){console.warn(`Didn't write tag '${c}' because '${l}' is not ISO 8859-1-compatible.`);return}let u=l.length+1,f=new Uint8Array(u);for(let d=0;d<l.length;d++)f[d]=l.charCodeAt(d);this.riffWriter.writeAscii(c),this.riffWriter.writeU32(u),this.writer.write(f),u&1&&this.writer.write(new Uint8Array(1)),n.add(c)},"writeInfoTag");for(let{key:c,value:l}of Gi(e))switch(c){case"title":i("INAM",l),n.add("INAM");break;case"artist":i("IART",l),n.add("IART");break;case"album":i("IPRD",l),n.add("IPRD");break;case"trackNumber":{let u=e.tracksTotal!==void 0?`${l}/${e.tracksTotal}`:l.toString();i("ITRK",u),n.add("ITRK")}break;case"genre":i("IGNR",l),n.add("IGNR");break;case"date":i("ICRD",l.toISOString().slice(0,10)),n.add("ICRD");break;case"comment":i("ICMT",l),n.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"description":case"lyrics":case"images":break;case"raw":break;default:kt(c)}if(e.raw)for(let c in e.raw){let l=e.raw[c];l==null||c.length!==4||n.has(c)||typeof l=="string"&&i(c,l)}let s=this.writer.getPos(),a=s-r-8;this.writer.seek(r+4),this.riffWriter.writeU32(a),this.writer.seek(s),a&1&&this.writer.write(new Uint8Array(1))}writeId3Chunk(e){let r=this.writer.getPos();this.riffWriter.writeAscii("ID3 "),this.riffWriter.writeU32(0);let i=new ac(this.writer).writeId3V2Tag(e),s=this.writer.getPos();this.writer.seek(r+4),this.riffWriter.writeU32(i),this.writer.seek(s),i&1&&this.writer.write(new Uint8Array(1))}async finalize(){let e=await this.mutex.acquire(),r=this.writer.getPos();this.isRf64?(x(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(r-8),x(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),x(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(x(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(r-8),x(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize)),this.writer.seek(r),e()}}});var Rn,_d,Yl,Wl,Dd,jl,Qk,Kk,Xk,Jk,Zk,eS,Id=he(()=>{HU();Zt();WU();ZI();m6();g6();y6();E6();P6();Rn=class{static{o(this,"OutputFormat")}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Vt.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Jt.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>vn.includes(e))}_codecUnsupportedHint(e){return""}},_d=class extends Rn{static{o(this,"IsobmffOutputFormat")}constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:1,max:4294967295}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new $k(e,this)}},Yl=class extends _d{static{o(this,"Mp4OutputFormat")}constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Vt,...Ys,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...vn]}_codecUnsupportedHint(e){return new Wl().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}},Wl=class extends _d{static{o(this,"MovOutputFormat")}constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Vt,...Jt]}_codecUnsupportedHint(e){return new Yl().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}},Dd=class extends Rn{static{o(this,"MkvOutputFormat")}constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(e.minimumClusterDuration!==void 0&&(!Number.isFinite(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(e.onCluster!==void 0&&typeof e.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Hk(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:1,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...Vt,...Ys,...ht.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...vn]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}},jl=class extends Dd{static{o(this,"WebMOutputFormat")}constructor(e){super(e)}getSupportedCodecs(){return[...Vt.filter(e=>["vp8","vp9","av1"].includes(e)),...Jt.filter(e=>["opus","vorbis"].includes(e)),...vn]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new Dd().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}},Qk=class extends Rn{static{o(this,"Mp3OutputFormat")}constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.xingHeader!==void 0&&typeof e.xingHeader!="boolean")throw new TypeError("options.xingHeader, when provided, must be a boolean.");if(e.onXingFrame!==void 0&&typeof e.onXingFrame!="function")throw new TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Wk(e,this)}get _name(){return"MP3"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".mp3"}get mimeType(){return"audio/mpeg"}getSupportedCodecs(){return["mp3"]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}},Kk=class extends Rn{static{o(this,"WavOutputFormat")}constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.large!==void 0&&typeof e.large!="boolean")throw new TypeError("options.large, when provided, must be a boolean.");if(e.metadataFormat!==void 0&&!["info","id3"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if(e.onHeader!==void 0&&typeof e.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Gk(e,this)}get _name(){return"WAVE"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".wav"}get mimeType(){return"audio/wav"}getSupportedCodecs(){return[...ht.filter(e=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-u8","ulaw","alaw"].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}},Xk=class extends Rn{static{o(this,"OggOutputFormat")}constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.maximumPageDuration!==void 0&&(!Number.isFinite(e.maximumPageDuration)||e.maximumPageDuration<=0))throw new TypeError("options.maximumPageDuration, when provided, must be a positive number.");if(e.onPage!==void 0&&typeof e.onPage!="function")throw new TypeError("options.onPage, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new jk(e,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:4294967296},subtitle:{min:0,max:0},total:{min:1,max:4294967296}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...Jt.filter(e=>["vorbis","opus"].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}},Jk=class extends Rn{static{o(this,"AdtsOutputFormat")}constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onFrame!==void 0&&typeof e.onFrame!="function")throw new TypeError("options.onFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Ok(e,this)}get _name(){return"ADTS"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".aac"}get mimeType(){return"audio/aac"}getSupportedCodecs(){return["aac"]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}},Zk=class extends Rn{static{o(this,"FlacOutputFormat")}constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");super(),this._options=e}_createMuxer(e){return new Rk(e,this)}get _name(){return"FLAC"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".flac"}get mimeType(){return"audio/flac"}getSupportedCodecs(){return["flac"]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}},eS=class extends Rn{static{o(this,"MpegTsOutputFormat")}constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onPacket!==void 0&&typeof e.onPacket!="function")throw new TypeError("options.onPacket, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new qk(e,this)}get _name(){return"MPEG-TS"}getSupportedTrackCounts(){return{video:{min:0,max:16},audio:{min:0,max:32},subtitle:{min:0,max:0},total:{min:1,max:48}}}get fileExtension(){return".ts"}get mimeType(){return"video/MP2T"}getSupportedCodecs(){return[...Vt.filter(e=>["avc","hevc"].includes(e)),...Jt.filter(e=>["aac","mp3","ac3","eac3"].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}}});var nS,I6,tS,iS,_6,rS,Tr,D6,M6,O6,Jp,R6,N6,Qp,Kp,Xp,A6,n_,Md,i_,sS,F6,L6,oS=he(()=>{Zt();rd();Ue();nS=o(t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!Vt.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${Vt.join(", ")}.`);if(!(t.bitrate instanceof Tr)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(t.keyFrameInterval!==void 0&&(!Number.isFinite(t.keyFrameInterval)||t.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(t.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(t.onEncoderConfig!==void 0&&typeof t.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");I6(t.codec,t)},"validateVideoEncodingConfig"),I6=o((t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&HP(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},"validateVideoEncodingAdditionalOptions"),tS=o(t=>{let e=t.bitrate instanceof Tr?t.bitrate._toVideoBitrate(t.codec,t.width,t.height):t.bitrate;return{codec:t.fullCodecString??zz(t.codec,t.width,t.height,e),width:t.width,height:t.height,displayWidth:t.squarePixelWidth,displayHeight:t.squarePixelHeight,bitrate:e,bitrateMode:t.bitrateMode,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...Hz(t.codec)}},"buildVideoEncoderConfig"),iS=o(t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!Jt.includes(t.codec))throw new TypeError(`Invalid audio codec '${t.codec}'. Must be one of: ${Jt.join(", ")}.`);if(t.bitrate===void 0&&(!ht.includes(t.codec)||t.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(t.bitrate!==void 0&&!(t.bitrate instanceof Tr)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(t.onEncoderConfig!==void 0&&typeof t.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");_6(t.codec,t)},"validateAudioEncodingConfig"),_6=o((t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&HP(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`)},"validateAudioEncodingAdditionalOptions"),rS=o(t=>{let e=t.bitrate instanceof Tr?t.bitrate._toAudioBitrate(t.codec):t.bitrate;return{codec:t.fullCodecString??$z(t.codec,t.numberOfChannels,t.sampleRate),numberOfChannels:t.numberOfChannels,sampleRate:t.sampleRate,bitrate:e,bitrateMode:t.bitrateMode,...Vz(t.codec)}},"buildAudioEncoderConfig"),Tr=class{static{o(this,"Quality")}constructor(e){this._factor=e}_toVideoBitrate(e,r,n){let i=r*n,s={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},a=1920*1080,c=3e6,l=Math.pow(i/a,.95),d=c*l*s[e]*this._factor;return Math.ceil(d/1e3)*1e3}_toAudioBitrate(e){if(ht.includes(e)||e==="flac")return;let n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[e];if(!n)throw new Error(`Unhandled codec: ${e}`);let i=n*this._factor;return e==="aac"?i=[96e3,128e3,16e4,192e3].reduce((a,c)=>Math.abs(c-i)<Math.abs(a-i)?c:a):e==="opus"||e==="vorbis"?i=Math.max(6e3,i):e==="mp3"&&(i=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,c)=>Math.abs(c-i)<Math.abs(a-i)?c:a)),Math.round(i/1e3)*1e3}},D6=new Tr(.3),M6=new Tr(.6),O6=new Tr(1),Jp=new Tr(2),R6=new Tr(4),N6=o(t=>{if(Vt.includes(t))return Qp(t);if(Jt.includes(t))return Kp(t);if(vn.includes(t))return Xp(t);throw new TypeError(`Unknown codec '${t}'.`)},"canEncode"),Qp=o(async(t,e={})=>{let{width:r=1280,height:n=720,bitrate:i=1e6,...s}=e;if(!Vt.includes(t))return!1;if(!Number.isInteger(r)||r<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(n)||n<=0)throw new TypeError("height must be a positive integer.");if(!(i instanceof Tr)&&(!Number.isInteger(i)||i<=0))throw new TypeError("bitrate must be a positive integer or a quality.");I6(t,s);let a=null;return Nl.length>0&&(a??=tS({codec:t,width:r,height:n,bitrate:i,framerate:void 0,...s}),Nl.some(u=>u.supports(t,a)))?!0:typeof VideoEncoder>"u"||(r%2===1||n%2===1)&&(t==="avc"||t==="hevc")||(a??=tS({codec:t,width:r,height:n,bitrate:i,framerate:void 0,...s,alpha:"discard"}),!(await VideoEncoder.isConfigSupported(a)).supported)?!1:Vs()?new Promise(async u=>{try{let f=new VideoEncoder({output:o(()=>{},"output"),error:o(()=>u(!1),"error")});f.configure(a);let d=new Uint8Array(r*n*4),h=new VideoFrame(d,{format:"RGBA",codedWidth:r,codedHeight:n,timestamp:0});f.encode(h),h.close(),await f.flush(),u(!0)}catch{u(!1)}}):!0},"canEncodeVideo"),Kp=o(async(t,e={})=>{let{numberOfChannels:r=2,sampleRate:n=48e3,bitrate:i=128e3,...s}=e;if(!Jt.includes(t))return!1;if(!Number.isInteger(r)||r<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(n)||n<=0)throw new TypeError("sampleRate must be a positive integer.");if(!(i instanceof Tr)&&(!Number.isInteger(i)||i<=0))throw new TypeError("bitrate must be a positive integer.");_6(t,s);let a=null;return Al.length>0&&(a??=rS({codec:t,numberOfChannels:r,sampleRate:n,bitrate:i,...s}),Al.some(l=>l.supports(t,a)))||ht.includes(t)?!0:typeof AudioEncoder>"u"?!1:(a??=rS({codec:t,numberOfChannels:r,sampleRate:n,bitrate:i,...s}),(await AudioEncoder.isConfigSupported(a)).supported===!0)},"canEncodeAudio"),Xp=o(async t=>!!vn.includes(t),"canEncodeSubtitles"),A6=o(async()=>{let[t,e,r]=await Promise.all([n_(),Md(),i_()]);return[...t,...e,...r]},"getEncodableCodecs"),n_=o(async(t=Vt,e)=>{let r=await Promise.all(t.map(n=>Qp(n,e)));return t.filter((n,i)=>r[i])},"getEncodableVideoCodecs"),Md=o(async(t=Jt,e)=>{let r=await Promise.all(t.map(n=>Kp(n,e)));return t.filter((n,i)=>r[i])},"getEncodableAudioCodecs"),i_=o(async(t=vn)=>{let e=await Promise.all(t.map(Xp));return t.filter((r,n)=>e[n])},"getEncodableSubtitleCodecs"),sS=o(async(t,e)=>{for(let r of t)if(await Qp(r,e))return r;return null},"getFirstEncodableVideoCodec"),F6=o(async(t,e)=>{for(let r of t)if(await Kp(r,e))return r;return null},"getFirstEncodableAudioCodec"),L6=o(async t=>{for(let e of t)if(await Xp(e))return e;return null},"getFirstEncodableSubtitleCodec")});var Gl,Zs,Od,Zp,s_,Kl,aS,cS,eo,Rd,eg,Xl,lS,uS,ore,are,Pi,cre,o_,lre,a_,Ql,fS,dS=he(()=>{qs();Zt();Ue();Vp();KP();rd();Qn();bp();oS();Gl=class{static{o(this,"MediaSource")}constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},Zs=class extends Gl{static{o(this,"VideoSource")}constructor(e){if(super(),this._connectedTrack=null,!Vt.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${Vt.join(", ")}.`);this._codec=e}},Od=class extends Zs{static{o(this,"EncodedVideoPacketSource")}constructor(e){super(e)}add(e,r){if(!(e instanceof je))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(r!==void 0&&(!r||typeof r!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,r)}},Zp=class{static{o(this,"VideoEncoderWrapper")}constructor(e,r){this.source=e,this.encodingConfig=r,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.codedWidth=null,this.codedHeight=null,this.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new $a,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null}async add(e,r,n){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.codedWidth!==null&&this.codedHeight!==null){if(e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight){let c=this.encodingConfig.sizeChangeBehavior??"deny";if(c!=="passThrough"){if(c==="deny")throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'strict' in the encoding options.`);{let l=!1;this.resizeCanvas||(typeof document<"u"?(this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),l=!0);let u=this.resizeCanvas.getContext("2d",{alpha:Vs()});x(u),l||(Vs()?(u.fillStyle="black",u.fillRect(0,0,this.codedWidth,this.codedHeight)):u.clearRect(0,0,this.codedWidth,this.codedHeight)),e.drawWithFit(u,{fit:c}),r&&e.close(),e=new ur(this.resizeCanvas,{timestamp:e.timestamp,duration:e.duration,rotation:e.rotation}),r=!0}}}}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),x(this.encoderInitialized);let i=this.encodingConfig.keyFrameInterval??5,s=Math.floor(e.timestamp/i),a={...n,keyFrame:n?.keyFrame||i===0||s!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=s,this.customEncoder){this.customEncoderQueueSize++;let c=e.clone(),l=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(c,a)).then(()=>this.customEncoderQueueSize--).catch(u=>this.error??=u).finally(()=>{c.close()});this.customEncoderQueueSize>=4&&await l}else{x(this.encoder);let c=e.toVideoFrame();if(!this.alphaEncoder)this.encoder.encode(c,a),c.close();else if(!!c.format&&!c.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(c,a),c.close();else{let u=c.displayWidth,f=c.displayHeight;if(!this.splitter)try{this.splitter=new s_(u,f)}catch(d){console.error("Due to an error, only color data will be encoded.",d),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(c,a),c.close()}if(this.splitter){let d=this.splitter.extractColor(c),h=this.splitter.extractAlpha(c);this.alphaFrameQueue.push(h),this.encoder.encode(d,a),d.close(),c.close()}}r&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(l=>this.encoder.addEventListener("dequeue",l,{once:!0}))}await this.muxer.mutex.currentPromise}finally{r&&e.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let r=tS({width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(r);let n=Nl.find(i=>i.supports(this.encodingConfig.codec,r));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=r,this.customEncoder.onPacket=(i,s)=>{if(!(i instanceof je))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(s!==void 0&&(!s||typeof s!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(i,s),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,i,s).catch(a=>{this.error??=a})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(r.alpha="discard",this.encodingConfig.alpha==="keep"&&(r.latencyMode="quality"),(r.width%2===1||r.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${r.width}x${r.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(r)).supported)throw new Error(`This specific encoder configuration (${r.codec}, ${r.bitrate} bps, ${r.width}x${r.height}, hardware acceleration: ${r.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let a=[],c=[],l=0,u=0,f=o((h,m,p)=>{let g={};if(m){let b=new Uint8Array(m.byteLength);m.copyTo(b),g.alpha=b}let y=je.fromEncodedChunk(h,g);this.encodingConfig.onEncodedPacket?.(y,p),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,y,p).catch(b=>{this.error??=b})},"addPacket"),d=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:o((h,m)=>{if(!this.alphaEncoder){f(h,null,m);return}let p=this.alphaFrameQueue.shift();x(p!==void 0),p?(this.alphaEncoder.encode(p,{keyFrame:h.type==="key"}),u++,p.close(),a.push({chunk:h,meta:m})):u===0?f(h,null,m):(c.push(l+u),a.push({chunk:h,meta:m}))},"output"),error:o(h=>{h.stack=d,this.error??=h},"error")}),this.encoder.configure(r),this.encodingConfig.alpha==="keep"){let h=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:o((m,p)=>{u--;let g=a.shift();for(x(g!==void 0),f(g.chunk,m,g.meta),l++;c.length>0&&c[0]===l;){c.shift();let y=a.shift();x(y!==void 0),f(y.chunk,null,y.meta)}},"output"),error:o(m=>{m.stack=h,this.error??=m},"error")}),this.alphaEncoder.configure(r)}}x(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(r=>r?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},s_=class{static{o(this,"ColorAlphaSplitter")}constructor(e,r){this.lastFrame=null,typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,r):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=r);let n=this.canvas.getContext("webgl2",{alpha:!0});if(!n)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=n,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
32
32
|
in vec2 a_position;
|