polotno-node 2.14.0 → 2.14.3

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.
@@ -1,65 +0,0 @@
1
- import{K as Vn}from"./index-CeWB3Frt.js";function g(t){if(!t)throw new Error("Assertion failed.")}const vr=t=>{const e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},$=t=>t&&t[t.length-1],We=t=>t>=0&&t<2**32;class K{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),r=this.bytes[e]??0,n=7-(this.pos&7),a=(r&1<<n)>>n;return this.pos++,a}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){const n=this.pos+e;for(let a=this.pos;a<n;a++){const s=Math.floor(a/8);let i=this.bytes[s];const o=7-(a&7);i&=~(1<<o),i|=(r&1<<n-a-1)>>n-a-1<<o,this.bytes[s]=i}this.pos=n}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const 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(){const e=new K(this.bytes);return e.pos=this.pos,e}}const v=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)},ge=t=>{const e=v(t);return(e&1)===0?-(e>>1):e+1>>1},re=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),Y=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),et=new TextDecoder,oe=new TextEncoder,qt=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),nt={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Pr=qt(nt),it={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},_r=qt(it),st={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Er=qt(st),Un=t=>!!t&&!!t.primaries&&!!t.transfer&&!!t.matrix&&t.fullRange!==void 0,pt=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t);class Fr{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e;const r=new Promise(a=>{e=a}),n=this.currentPromise;return this.currentPromise=r,await n,e}}const ir=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),sr=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),Ir=(t,e,r)=>{let n=0,a=t.length-1,s=-1;for(;n<=a;){const i=n+a>>1,o=r(t[i]);o===e?(s=i,a=i-1):o<e?n=i+1:a=i-1}return s},U=(t,e,r)=>{let n=0,a=t.length-1,s=-1;for(;n<=a;){const i=n+(a-n+1)/2|0;r(t[i])<=e?(s=i,n=i+1):a=i-1}return s},Ne=()=>{let t,e;return{promise:new Promise((n,a)=>{t=n,e=a}),resolve:t,reject:e}},Ar=(t,e)=>{for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1},at=t=>{throw new Error(`Unexpected value: ${t}`)},Br=(t,e,r)=>{const n=t.getUint8(e),a=t.getUint8(e+1),s=t.getUint8(e+2);return n<<16|a<<8|s},Or=(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))},Wn=(t,e,r,n)=>{r=q(r,-8388608,8388607),r<0&&(r=r+16777216&16777215),Or(t,e,r,n)},q=(t,e,r)=>Math.max(e,Math.min(r,t)),Pe="und",zr=t=>{const e=Math.round(t);return Math.abs(t/e-1)<10*Number.EPSILON?e:t},Hn=(t,e)=>Math.round(t/e)*e,$n=/^[a-z]{3}$/,jt=t=>$n.test(t),ye=1e6*(1+Number.EPSILON),ar=(t,e)=>{const r={...t,...e};if(t.headers||e.headers){const n=t.headers?or(t.headers):{},a=e.headers?or(e.headers):{},s={...n};Object.entries(a).forEach(([i,o])=>{const c=Object.keys(s).find(l=>l.toLowerCase()===i.toLowerCase());c&&delete s[c],s[i]=o}),r.headers=s}return r},or=t=>{if(t instanceof Headers){const e={};return t.forEach((r,n)=>{e[n]=r}),e}if(Array.isArray(t)){const e={};return t.forEach(([r,n])=>{e[r]=n}),e}return t},cr=async(t,e,r,n,a)=>{let s=0;for(;;)try{return await t(e,r)}catch(i){if(a())throw i;s++;const o=n(s,i,e);if(o===null)throw i;if(console.error("Retrying failed fetch. Error:",i),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await new Promise(c=>setTimeout(c,1e3*o)),a())throw i}},Ln=(t,e)=>{const r=t<0?-1:1;t=Math.abs(t);let n=0,a=1,s=1,i=0,o=t;for(;;){const c=Math.floor(o),l=c*s+n,u=c*i+a;if(u>e)return{numerator:r*s,denominator:i};if(n=s,a=i,s=l,i=u,o=1/(o-c),!isFinite(o))break}return{numerator:r*s,denominator:i}};class Rr{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let gt=null;const qn=()=>gt!==null?gt:gt=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let kt=null;const dt=()=>kt!==null?kt:kt=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox");let bt=null;const jn=()=>bt!==null?bt:bt=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent)));let Tt=null;const Kn=()=>{if(Tt!==null)return Tt;if(typeof navigator>"u")return null;const t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?Tt=Number(t[1]):null},Ot=(t,e,r,n)=>t<=n&&r<=e,Dr=function*(t){for(const e in t){const r=t[e];r!==void 0&&(yield{key:e,value:r})}},Mr=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Kt=t=>typeof t=="number"&&!Number.isNaN(t);class Ve{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.")}}class Nr{constructor(e,r,n,a){if(this.data=e,this.mimeType=r,this.name=n,this.description=a,!(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(a!==void 0&&typeof a!="string")throw new TypeError("description, when provided, must be a string.")}}const Qn=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(const 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(const e of Object.values(t.raw))if(e!==null&&typeof e!="string"&&!(e instanceof Uint8Array)&&!(e instanceof Ve)&&!(e instanceof Nr))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}},Vr={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},Xn=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.")};const Se=["avc","hevc","vp9","av1","vp8"],X=["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"],Ur=["aac","opus","mp3","vorbis","flac"],Be=[...Ur,...X],ft=["webvtt"],lr=[{maxMacroblocks:99,maxBitrate:64e3,level:10},{maxMacroblocks:396,maxBitrate:192e3,level:11},{maxMacroblocks:396,maxBitrate:384e3,level:12},{maxMacroblocks:396,maxBitrate:768e3,level:13},{maxMacroblocks:396,maxBitrate:2e6,level:20},{maxMacroblocks:792,maxBitrate:4e6,level:21},{maxMacroblocks:1620,maxBitrate:4e6,level:22},{maxMacroblocks:1620,maxBitrate:1e7,level:30},{maxMacroblocks:3600,maxBitrate:14e6,level:31},{maxMacroblocks:5120,maxBitrate:2e7,level:32},{maxMacroblocks:8192,maxBitrate:2e7,level:40},{maxMacroblocks:8192,maxBitrate:5e7,level:41},{maxMacroblocks:8704,maxBitrate:5e7,level:42},{maxMacroblocks:22080,maxBitrate:135e6,level:50},{maxMacroblocks:36864,maxBitrate:24e7,level:51},{maxMacroblocks:36864,maxBitrate:24e7,level:52},{maxMacroblocks:139264,maxBitrate:24e7,level:60},{maxMacroblocks:139264,maxBitrate:48e7,level:61},{maxMacroblocks:139264,maxBitrate:8e8,level:62}],ur=[{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}],Ce=[{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}],dr=[{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}],fr=".01.01.01.01.00",hr=".0.110.01.01.01.0",Gn=(t,e,r,n)=>{if(t==="avc"){const s=Math.ceil(e/16)*Math.ceil(r/16),i=lr.find(d=>s<=d.maxMacroblocks&&n<=d.maxBitrate)??$(lr),o=i?i.level:0,c="64".padStart(2,"0"),l="00",u=o.toString(16).padStart(2,"0");return`avc1.${c}${l}${u}`}else if(t==="hevc"){const o=e*r,c=ur.find(u=>o<=u.maxPictureSize&&n<=u.maxBitrate)??$(ur);return`hev1.1.6.${c.tier}${c.level}.B0`}else{if(t==="vp8")return"vp8";if(t==="vp9"){const s=e*r;return`vp09.00.${(Ce.find(c=>s<=c.maxPictureSize&&n<=c.maxBitrate)??$(Ce)).level.toString().padStart(2,"0")}.08`}else if(t==="av1"){const s=e*r,i=dr.find(l=>s<=l.maxPictureSize&&n<=l.maxBitrate)??$(dr);return`av01.0.${i.level.toString().padStart(2,"0")}${i.tier}.08`}}throw new TypeError(`Unhandled codec '${t}'.`)},Yn=t=>{const e=t.split("."),a=(1<<7)+1,s=Number(e[1]),i=e[2],o=Number(i.slice(0,-1)),c=(s<<5)+o,l=i.slice(-1)==="H"?1:0,d=Number(e[3])===8?0:1,f=0,h=e[4]?Number(e[4]):0,m=e[5]?Number(e[5][0]):1,p=e[5]?Number(e[5][1]):1,T=e[5]?Number(e[5][2]):0,k=(l<<7)+(d<<6)+(f<<5)+(h<<4)+(m<<3)+(p<<2)+T;return[a,c,k,0]},Wr=t=>{const{codec:e,codecDescription:r,colorSpace:n,avcCodecInfo:a,hevcCodecInfo:s,vp9CodecInfo:i,av1CodecInfo:o}=t;if(e==="avc"){if(g(t.avcType!==null),a){const c=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc${t.avcType}.${ir(c)}`}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}.${ir(r.subarray(1,4))}`}else if(e==="hevc"){let c,l,u,d,f,h;if(s)c=s.generalProfileSpace,l=s.generalProfileIdc,u=sr(s.generalProfileCompatibilityFlags),d=s.generalTierFlag,f=s.generalLevelIdc,h=[...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.");const p=Y(r),T=p.getUint8(1);c=T>>6&3,l=T&31,u=sr(p.getUint32(2)),d=T>>5&1,f=p.getUint8(12),h=[];for(let k=0;k<6;k++)h.push(p.getUint8(6+k))}let m="hev1.";for(m+=["","A","B","C"][c]+l,m+=".",m+=u.toString(16).toUpperCase(),m+=".",m+=d===0?"L":"H",m+=f;h.length>0&&h[h.length-1]===0;)h.pop();return h.length>0&&(m+=".",m+=h.map(p=>p.toString(16).toUpperCase()).join(".")),m}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!i){const k=t.width*t.height;let b=$(Ce).level;for(const y of Ce)if(k<=y.maxPictureSize){b=y.level;break}return`vp09.00.${b.toString().padStart(2,"0")}.08`}const c=i.profile.toString().padStart(2,"0"),l=i.level.toString().padStart(2,"0"),u=i.bitDepth.toString().padStart(2,"0"),d=i.chromaSubsampling.toString().padStart(2,"0"),f=i.colourPrimaries.toString().padStart(2,"0"),h=i.transferCharacteristics.toString().padStart(2,"0"),m=i.matrixCoefficients.toString().padStart(2,"0"),p=i.videoFullRangeFlag.toString().padStart(2,"0");let T=`vp09.${c}.${l}.${u}.${d}`;return T+=`.${f}.${h}.${m}.${p}`,T.endsWith(fr)&&(T=T.slice(0,-fr.length)),T}else if(e==="av1"){if(!o){const y=t.width*t.height;let S=$(Ce).level;for(const P of Ce)if(y<=P.maxPictureSize){S=P.level;break}return`av01.0.${S.toString().padStart(2,"0")}M.08`}const c=o.profile,l=o.level.toString().padStart(2,"0"),u=o.tier?"H":"M",d=o.bitDepth.toString().padStart(2,"0"),f=o.monochrome?"1":"0",h=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),m=n?.primaries?nt[n.primaries]:1,p=n?.transfer?it[n.transfer]:1,T=n?.matrix?st[n.matrix]:1,k=n?.fullRange?1:0;let b=`av01.${c}.${l}${u}.${d}`;return b+=`.${f}.${h.toString().padStart(3,"0")}`,b+=`.${m.toString().padStart(2,"0")}`,b+=`.${p.toString().padStart(2,"0")}`,b+=`.${T.toString().padStart(2,"0")}`,b+=`.${k}`,b.endsWith(hr)&&(b=b.slice(0,-hr.length)),b}}throw new TypeError(`Unhandled codec '${e}'.`)},Zn=(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(X.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},Hr=t=>{const{codec:e,codecDescription:r,aacCodecInfo:n}=t;if(e==="aac"){if(!n)throw new TypeError("AAC codec info must be provided.");return n.isMpeg2?"mp4a.67":`mp4a.40.${Qt(r).objectType}`}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e&&X.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},zt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],$r=[-1,1,2,3,4,5,6,8],Qt=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new K(t);let r=e.readBits(5);r===31&&(r=32+e.readBits(6));const n=e.readBits(4);let a=null;n===15?a=e.readBits(24):n<zt.length&&(a=zt[n]);const s=e.readBits(4);let i=null;return s>=1&&s<=7&&(i=$r[s]),{objectType:r,frequencyIndex:n,sampleRate:a,channelConfiguration:s,numberOfChannels:i}},Jn=t=>{let e=zt.indexOf(t.sampleRate),r=null;e===-1&&(e=15,r=t.sampleRate);const n=$r.indexOf(t.numberOfChannels);if(n===-1)throw new TypeError(`Unsupported number of channels: ${t.numberOfChannels}`);let a=13;t.objectType>=32&&(a+=6),e===15&&(a+=24);const s=Math.ceil(a/8),i=new Uint8Array(s),o=new K(i);return t.objectType<32?o.writeBits(5,t.objectType):(o.writeBits(5,31),o.writeBits(6,t.objectType-32)),o.writeBits(4,e),e===15&&o.writeBits(24,r),o.writeBits(4,n),i},Lr=48e3,qr=/^pcm-([usf])(\d+)+(be)?$/,ze=t=>{if(g(X.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};const e=qr.exec(t);g(e);let r;e[1]==="u"?r="unsigned":e[1]==="s"?r="signed":r="float";const n=Number(e[2])/8,a=e[3]!=="be",s=t==="pcm-u8"?2**7:0;return{dataType:r,sampleSize:n,littleEndian:a,silentValue:s}},jr=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==="ulaw"?"ulaw":t==="alaw"?"alaw":qr.test(t)?t:t==="webvtt"?"webvtt":null,ei=t=>t==="avc"?{avc:{format:"avc"}}:t==="hevc"?{hevc:{format:"hevc"}}:{},ti=t=>t==="aac"?{aac:{format:"aac"}}:t==="opus"?{opus:{format:"opus"}}:{},ri=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],ni=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,ii=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,si=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,ai=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,oi=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(!ri.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 WebCodecs 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&&!pt(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){const{colorSpace:e}=t.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const r=Object.keys(nt);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(", ")}.`);const n=Object.keys(it);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(", ")}.`);const a=Object.keys(st);if(e.matrix!=null&&!a.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.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(!ni.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(!ii.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(!si.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")&&!ai.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/.')},ci=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],li=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(!ci.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 WebCodecs 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&&!pt(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/.");if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}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("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!X.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${X.join(", ")}).`)},ui=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.")};class di{constructor(e){this.mutex=new Fr,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,r,n){r+=e.source._timestampOffset;let a=this.trackTimestampInfo.get(e);if(!a){if(!n)throw new Error("First packet must be a key packet.");a={maxTimestamp:r,maxTimestampBeforeLastKeyPacket:r},this.trackTimestampInfo.set(e,a)}if(r<0)throw new Error(`Timestamps must be non-negative (got ${r}s).`);if(n&&(a.maxTimestampBeforeLastKeyPacket=a.maxTimestamp),r<a.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 ${a.maxTimestampBeforeLastKeyPacket}s.`);return a.maxTimestamp=Math.max(a.maxTimestamp,r),r}}var Ae;(function(t){t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.SPS_EXT=13]="SPS_EXT"})(Ae||(Ae={}));var G;(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.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(G||(G={}));const ot=t=>{const e=[];let r=0;for(;r<t.length;){let n=-1,a=0;for(let s=r;s<t.length-3;s++){if(t[s]===0&&t[s+1]===0&&t[s+2]===1){n=s,a=3;break}if(s<t.length-4&&t[s]===0&&t[s+1]===0&&t[s+2]===0&&t[s+3]===1){n=s,a=4;break}}if(n===-1)break;if(r>0&&n>r){const s=t.subarray(r,n);s.length>0&&e.push(s)}r=n+a}if(r<t.length){const n=t.subarray(r);n.length>0&&e.push(n)}return e},Kr=(t,e)=>{const r=[];let n=0;const a=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;n+e<=t.length;){let s;e===1?s=a.getUint8(n):e===2?s=a.getUint16(n,!1):e===3?s=Br(a,n):e===4?s=a.getUint32(n,!1):(at(e),g(!1)),n+=e;const i=t.subarray(n,n+s);r.push(i),n+=s}return r},ht=t=>{const 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)},fi=t=>{const r=ot(t);if(r.length===0)return null;let n=0;for(const o of r)n+=4+o.byteLength;const a=new Uint8Array(n),s=new DataView(a.buffer);let i=0;for(const o of r){const c=o.byteLength;s.setUint32(i,c,!1),i+=4,a.set(o,i),i+=o.byteLength}return a},hi=(t,e)=>{if(e.description){const a=(re(e.description)[4]&3)+1;return Kr(t,a)}else return ot(t)},Ze=t=>t[0]&31,Qr=t=>{try{const e=ot(t),r=e.filter(c=>Ze(c)===Ae.SPS),n=e.filter(c=>Ze(c)===Ae.PPS),a=e.filter(c=>Ze(c)===Ae.SPS_EXT);if(r.length===0||n.length===0)return null;const s=r[0],i=pi(s);g(i!==null);const o=i.profileIdc===100||i.profileIdc===110||i.profileIdc===122||i.profileIdc===144;return{configurationVersion:1,avcProfileIndication:i.profileIdc,profileCompatibility:i.constraintFlags,avcLevelIndication:i.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:r,pictureParameterSets:n,chromaFormat:o?i.chromaFormatIdc:null,bitDepthLumaMinus8:o?i.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?i.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?a:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},mi=t=>{const 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(const r of t.sequenceParameterSets){const n=r.byteLength;e.push(n>>8),e.push(n&255);for(let a=0;a<n;a++)e.push(r[a])}e.push(t.pictureParameterSets.length);for(const r of t.pictureParameterSets){const n=r.byteLength;e.push(n>>8),e.push(n&255);for(let a=0;a<n;a++)e.push(r[a])}if(t.avcProfileIndication===100||t.avcProfileIndication===110||t.avcProfileIndication===122||t.avcProfileIndication===144){g(t.chromaFormat!==null),g(t.bitDepthLumaMinus8!==null),g(t.bitDepthChromaMinus8!==null),g(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(const r of t.sequenceParameterSetExt){const n=r.byteLength;e.push(n>>8),e.push(n&255);for(let a=0;a<n;a++)e.push(r[a])}}return new Uint8Array(e)},pi=t=>{try{const e=new K(ht(t));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;const n=e.readAlignedByte(),a=e.readAlignedByte(),s=e.readAlignedByte();v(e);let i=null,o=null,c=null;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(i=v(e),i===3&&e.skipBits(1),o=v(e),c=v(e),e.skipBits(1),e.readBits(1))){for(let f=0;f<(i!==3?8:12);f++)if(e.readBits(1)){const m=f<6?16:64;let p=8,T=8;for(let k=0;k<m;k++){if(T!==0){const b=ge(e);T=(p+b+256)%256}p=T===0?p:T}}}v(e);const l=v(e);if(l===0)v(e);else if(l===1){e.skipBits(1),ge(e),ge(e);const d=v(e);for(let f=0;f<d;f++)ge(e)}v(e),e.skipBits(1),v(e),v(e);const u=e.readBits(1);return{profileIdc:n,constraintFlags:a,levelIdc:s,frameMbsOnlyFlag:u,chromaFormatIdc:i,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},gi=(t,e)=>{if(e.description){const a=(re(e.description)[21]&3)+1;return Kr(t,a)}else return ot(t)},ve=t=>t[0]>>1&63,Xr=t=>{try{const e=ot(t),r=e.filter(M=>ve(M)===G.VPS_NUT),n=e.filter(M=>ve(M)===G.SPS_NUT),a=e.filter(M=>ve(M)===G.PPS_NUT),s=e.filter(M=>ve(M)===G.PREFIX_SEI_NUT||ve(M)===G.SUFFIX_SEI_NUT);if(n.length===0||a.length===0)return null;const i=n[0],o=new K(ht(i));o.skipBits(16),o.readBits(4);const c=o.readBits(3),l=o.readBits(1),{general_profile_space:u,general_tier_flag:d,general_profile_idc:f,general_profile_compatibility_flags:h,general_constraint_indicator_flags:m,general_level_idc:p}=ki(o,c);v(o);const T=v(o);T===3&&o.skipBits(1),v(o),v(o),o.readBits(1)&&(v(o),v(o),v(o),v(o));const k=v(o),b=v(o);v(o);const S=o.readBits(1)?0:c;for(let M=S;M<=c;M++)v(o),v(o),v(o);v(o),v(o),v(o),v(o),v(o),v(o),o.readBits(1)&&o.readBits(1)&&bi(o),o.skipBits(1),o.skipBits(1),o.readBits(1)&&(o.skipBits(4),o.skipBits(4),v(o),v(o),o.skipBits(1));const P=v(o);if(Ti(o,P),o.readBits(1)){const M=v(o);for(let O=0;O<M;O++)v(o),o.skipBits(1)}o.skipBits(1),o.skipBits(1);let B=0;o.readBits(1)&&(B=yi(o,c));let I=0;if(a.length>0){const M=a[0],O=new K(ht(M));O.skipBits(16),v(O),v(O),O.skipBits(1),O.skipBits(1),O.skipBits(3),O.skipBits(1),O.skipBits(1),v(O),v(O),ge(O),O.skipBits(1),O.skipBits(1),O.readBits(1)&&v(O),ge(O),ge(O),O.skipBits(1),O.skipBits(1),O.skipBits(1),O.skipBits(1);const ue=O.readBits(1),Le=O.readBits(1);!ue&&!Le?I=0:ue&&!Le?I=2:!ue&&Le?I=3:I=0}const E=[...r.length?[{arrayCompleteness:1,nalUnitType:G.VPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:G.SPS_NUT,nalUnits:n}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:G.PPS_NUT,nalUnits:a}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:ve(s[0]),nalUnits:s}]:[]];return{configurationVersion:1,generalProfileSpace:u,generalTierFlag:d,generalProfileIdc:f,generalProfileCompatibilityFlags:h,generalConstraintIndicatorFlags:m,generalLevelIdc:p,minSpatialSegmentationIdc:B,parallelismType:I,chromaFormatIdc:T,bitDepthLumaMinus8:k,bitDepthChromaMinus8:b,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:l,lengthSizeMinusOne:3,arrays:E}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},ki=(t,e)=>{const r=t.readBits(2),n=t.readBits(1),a=t.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|t.readBits(1);const i=new Uint8Array(6);for(let u=0;u<6;u++)i[u]=t.readBits(8);const o=t.readBits(8),c=[],l=[];for(let u=0;u<e;u++)c.push(t.readBits(1)),l.push(t.readBits(1));if(e>0)for(let u=e;u<8;u++)t.skipBits(2);for(let u=0;u<e;u++)c[u]&&t.skipBits(88),l[u]&&t.skipBits(8);return{general_profile_space:r,general_tier_flag:n,general_profile_idc:a,general_profile_compatibility_flags:s,general_constraint_indicator_flags:i,general_level_idc:o}},bi=t=>{for(let e=0;e<4;e++)for(let r=0;r<(e===3?2:6);r++)if(!t.readBits(1))v(t);else{const a=Math.min(64,1<<4+(e<<1));e>1&&ge(t);for(let s=0;s<a;s++)ge(t)}},Ti=(t,e)=>{const r=[];for(let n=0;n<e;n++)r[n]=wi(t,n,e,r)},wi=(t,e,r,n)=>{let a=0,s=0,i=0;if(e!==0&&(s=t.readBits(1)),s){if(e===r){const c=v(t);i=e-(c+1)}else i=e-1;t.readBits(1),v(t);const o=n[i]??0;for(let c=0;c<=o;c++)t.readBits(1)||t.readBits(1);a=n[i]}else{const o=v(t),c=v(t);for(let l=0;l<o;l++)v(t),t.readBits(1);for(let l=0;l<c;l++)v(t),t.readBits(1);a=o+c}return a},yi=(t,e)=>{if(t.readBits(1)&&t.readBits(8)===255&&(t.readBits(16),t.readBits(16)),t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),t.readBits(1),t.readBits(1)&&(t.readBits(8),t.readBits(8),t.readBits(8))),t.readBits(1)&&(v(t),v(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(v(t),v(t),v(t),v(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&v(t),t.readBits(1)&&Ci(t,!0,e)),t.readBits(1)){t.readBits(1),t.readBits(1),t.readBits(1);const r=v(t);return v(t),v(t),v(t),v(t),r}return 0},Ci=(t,e,r)=>{let n=!1,a=!1,s=!1;n=t.readBits(1)===1,a=t.readBits(1)===1,(n||a)&&(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 i=0;i<=r;i++){const o=t.readBits(1)===1;let c=!0;o||(c=t.readBits(1)===1);let l=!1;c?v(t):l=t.readBits(1)===1;let u=1;l||(u=v(t)+1),n&&mr(t,u,s),a&&mr(t,u,s)}},mr=(t,e,r)=>{for(let n=0;n<e;n++)v(t),v(t),r&&(v(t),v(t)),t.readBits(1)},Si=t=>{const 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(const 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(const n of r.nalUnits){e.push(n.length>>8&255),e.push(n.length&255);for(let a=0;a<n.length;a++)e.push(n[a])}}return new Uint8Array(e)},Gr=t=>{const e=new K(t);if(e.readBits(2)!==2)return null;const 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 l=8;s>=2&&(l=e.readBits(1)?12:10);const u=e.readBits(3);let d=0,f=0;if(u!==7)if(f=e.readBits(1),s===1||s===3){const I=e.readBits(1),E=e.readBits(1);d=!I&&!E?3:I&&!E?2:1,e.skipBits(1)}else d=1;else d=3,f=1;const h=e.readBits(16),m=e.readBits(16),p=h+1,T=m+1,k=p*T;let b=$(Ce).level;for(const B of Ce)if(k<=B.maxPictureSize){b=B.level;break}return{profile:s,level:b,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:u===2?1:u===1?6:2,transferCharacteristics:u===2?1:u===1?6:2,matrixCoefficients:u===7?0:u===2?1:u===1?6:2}},Yr=function*(t){const e=new K(t),r=()=>{let n=0;for(let a=0;a<8;a++){const s=e.readAlignedByte();if(n|=(s&127)<<a*7,!(s&128))break;if(a===7&&s&128)return null}return n>=2**32-1?null:n};for(;e.getBitsLeft()>=8;){e.skipBits(1);const n=e.readBits(4),a=e.readBits(1),s=e.readBits(1);e.skipBits(1),a&&e.skipBits(8);let i;if(s){const o=r();if(o===null)return;i=o}else i=Math.floor(e.getBitsLeft()/8);g(e.pos%8===0),yield{type:n,data:t.subarray(e.pos/8,e.pos/8+i)},e.skipBits(i*8)}},Zr=t=>{for(const{type:e,data:r}of Yr(t)){if(e!==1)continue;const n=new K(r),a=n.readBits(3);n.readBits(1);const s=n.readBits(1);let i=0,o=0,c=0;if(s)i=n.readBits(5);else{if(n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.readBits(1)))return null;const P=n.readBits(1);P&&(c=n.readBits(5),n.skipBits(32),n.skipBits(5),n.skipBits(5));const B=n.readBits(5);for(let I=0;I<=B;I++){n.skipBits(12);const E=n.readBits(5);if(I===0&&(i=E),E>7){const M=n.readBits(1);I===0&&(o=M)}if(P&&n.readBits(1)){const O=c+1;n.skipBits(O),n.skipBits(O),n.skipBits(1)}n.readBits(1)&&n.skipBits(4)}}const l=n.readBits(4),u=n.readBits(4),d=l+1;n.skipBits(d);const f=u+1;n.skipBits(f);let h=0;if(s?h=0:h=n.readBits(1),h&&(n.skipBits(4),n.skipBits(3)),n.skipBits(1),n.skipBits(1),n.skipBits(1),!s){n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);const S=n.readBits(1);S&&(n.skipBits(1),n.skipBits(1));const P=n.readBits(1);let B=0;P?B=2:B=n.readBits(1),B>0&&(n.readBits(1)||n.skipBits(1)),S&&n.skipBits(3)}n.skipBits(1),n.skipBits(1),n.skipBits(1);const m=n.readBits(1);let p=8;a===2&&m?p=n.readBits(1)?12:10:a<=2&&(p=m?10:8);let T=0;a!==1&&(T=n.readBits(1));let k=1,b=1,y=0;return T||(a===0?(k=1,b=1):a===1?(k=0,b=0):p===12&&(k=n.readBits(1),k&&(b=n.readBits(1))),k&&b&&(y=n.readBits(2))),{profile:a,level:i,tier:o,bitDepth:p,monochrome:T,chromaSubsamplingX:k,chromaSubsamplingY:b,chromaSamplePosition:y}}return null},xi=t=>{const e=Y(t),r=e.getUint8(9),n=e.getUint16(10,!0),a=e.getUint32(12,!0),s=e.getInt16(16,!0),i=e.getUint8(18);let o=null;return i&&(o=t.subarray(19,21+r)),{outputChannelCount:r,preSkip:n,inputSampleRate:a,outputGain:s,channelMappingFamily:i,channelMappingTable:o}},vi=(t,e,r)=>{switch(t){case"avc":{const n=hi(r,e);let a=n.some(s=>Ze(s)===Ae.IDR);if(!a&&(!jn()||Kn()>=144))for(const s of n){if(Ze(s)!==Ae.SEI)continue;const o=ht(s);let c=1;do{let l=0;for(;;){const f=o[c++];if(f===void 0||(l+=f,f<255))break}let u=0;for(;;){const f=o[c++];if(f===void 0||(u+=f,f<255))break}if(l===6){const f=new K(o);f.pos=8*c;const h=v(f),m=f.readBits(1);if(h===0&&m===1){a=!0;break}}c+=u}while(c<o.length-1)}return a?"key":"delta"}case"hevc":return gi(r,e).some(s=>{const i=ve(s);return G.BLA_W_LP<=i&&i<=G.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return(r[0]&1)===0?"key":"delta";case"vp9":{const n=new K(r);if(n.readBits(2)!==2)return null;const a=n.readBits(1);return(n.readBits(1)<<1)+a===3&&n.skipBits(1),n.readBits(1)?null:n.readBits(1)===0?"key":"delta"}case"av1":{let n=!1;for(const{type:a,data:s}of Yr(r))if(a===1){const i=new K(s);i.skipBits(4),n=!!i.readBits(1)}else if(a===3||a===6||a===7){if(n)return"key";const i=new K(s);return i.readBits(1)?null:i.readBits(2)===0?"key":"delta"}return null}default:at(t),g(!1)}};var Rt;(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(Rt||(Rt={}));class Jr{constructor(e){this.input=e}}const Pi=[],_i=[],Dt=[],Mt=[];const He=new Uint8Array(0);class L{constructor(e,r,n,a,s=-1,i,o){if(this.data=e,this.type=r,this.timestamp=n,this.duration=a,this.sequenceNumber=s,e===He&&i===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(i===void 0&&(i=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(a)||a<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(i)||i<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=i,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===He}get microsecondTimestamp(){return Math.trunc(ye*this.timestamp)}get microsecondDuration(){return Math.trunc(ye*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.");const n=new Uint8Array(e.byteLength);return e.copyTo(n),new L(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?.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.");return new L(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}}const Ei=t=>{let n=t,a=4096,s=0,i=12,o=0;for(n<0&&(n=-n,s=128),n+=33,n>8191&&(n=8191);(n&a)!==a&&i>=5;)a>>=1,i--;return o=n>>i-4&15,~(s|i-5<<4|o)&255},Fi=t=>{let r=2048,n=0,a=11,s=0,i=t;for(i<0&&(i=-i,n=128),i>4095&&(i=4095);(i&r)!==r&&a>=5;)r>>=1,a--;return s=i>>(a===4?1:a-4)&15,(n|a-4<<4|s)^85};Mr();let pr=-1/0,gr=-1/0,tt=null;typeof FinalizationRegistry<"u"&&(tt=new FinalizationRegistry(t=>{const e=Date.now();t.type==="video"?(e-pr>=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."),pr=e),typeof VideoFrame<"u"&&t.data instanceof VideoFrame&&t.data.close()):(e-gr>=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."),gr=e),typeof AudioData<"u"&&t.data instanceof AudioData&&t.data.close())}));class _e{get displayWidth(){return this.rotation%180===0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180===0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(ye*this.timestamp)}get microsecondDuration(){return Math.trunc(ye*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(!("format"in r)||typeof r.format!="string")throw new TypeError("init.format must be a string.");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.");this._data=re(e).slice(),this.format=r.format,this.codedWidth=r.codedWidth,this.codedHeight=r.codedHeight,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new VideoColorSpace(r.colorSpace)}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.");this._data=e,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=r?.rotation??0,this.timestamp=r?.timestamp??e.timestamp/1e6,this.duration=r?.duration??(e.duration??0)/1e6,this.colorSpace=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 _e(new VideoFrame(e,{timestamp:Math.trunc(r.timestamp*ye),duration:Math.trunc((r.duration??0)*ye)||void 0}),r);let n=0,a=0;if("naturalWidth"in e?(n=e.naturalWidth,a=e.naturalHeight):"videoWidth"in e?(n=e.videoWidth,a=e.videoHeight):"width"in e&&(n=Number(e.width),a=Number(e.height)),!n||!a)throw new TypeError("Could not determine dimensions.");const s=new OffscreenCanvas(n,a),i=s.getContext("2d",{alpha:dt(),willReadFrequently:!0});g(i),i.drawImage(e,0,0),this._data=s,this.format="RGBX",this.codedWidth=n,this.codedHeight=a,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new VideoColorSpace({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");tt?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return g(this._data!==null),qe(this._data)?new _e(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?new _e(this._data.slice(),{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation}):new _e(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){this._closed||(tt?.unregister(this),qe(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(){if(this._closed)throw new Error("VideoSample is closed.");return g(this._data!==null),qe(this._data)?this._data.allocationSize():this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e){if(!pt(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(this._closed)throw new Error("VideoSample is closed.");if(g(this._data!==null),qe(this._data))await this._data.copyTo(e);else if(this._data instanceof Uint8Array)re(e).set(this._data);else{const n=this._data.getContext("2d");g(n);const a=n.getImageData(0,0,this.codedWidth,this.codedHeight);re(e).set(a.data)}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return g(this._data!==null),qe(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,a,s,i,o,c,l){let u=0,d=0,f=this.displayWidth,h=this.displayHeight,m=0,p=0,T=this.displayWidth,k=this.displayHeight;if(i!==void 0?(u=r,d=n,f=a,h=s,m=i,p=o,c!==void 0?(T=c,k=l):(T=f,k=h)):(m=r,p=n,a!==void 0&&(T=a,k=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(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(m))throw new TypeError("dx must be a number.");if(!Number.isFinite(p))throw new TypeError("dy must be a number.");if(!Number.isFinite(T)||T<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(k)||k<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:d,sWidth:f,sHeight:h}=this._rotateSourceRegion(u,d,f,h,this.rotation));const b=this.toCanvasImageSource();e.save();const y=m+T/2,S=p+k/2;e.translate(y,S),e.rotate(this.rotation*Math.PI/180);const P=this.rotation%180===0?1:T/k;e.scale(1/P,P),e.drawImage(b,u,d,f,h,-T/2,-k/2,T,k),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&&Ai(r.crop,"options.");const n=e.canvas.width,a=e.canvas.height,s=r.rotation??this.rotation,[i,o]=s%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];r.crop&&Ii(r.crop,i,o);let c,l,u,d;const{sx:f,sy:h,sWidth:m,sHeight:p}=this._rotateSourceRegion(r.crop?.left??0,r.crop?.top??0,r.crop?.width??i,r.crop?.height??o,s);if(r.fit==="fill")c=0,l=0,u=n,d=a;else{const[k,b]=r.crop?[r.crop.width,r.crop.height]:[i,o],y=r.fit==="contain"?Math.min(n/k,a/b):Math.max(n/k,a/b);u=k*y,d=b*y,c=(n-u)/2,l=(a-d)/2}e.save();const T=s%180===0?1:u/d;e.translate(n/2,a/2),e.rotate(s*Math.PI/180),e.scale(1/T,T),e.translate(-n/2,-a/2),e.drawImage(this.toCanvasImageSource(),f,h,m,p,c,l,u,d),e.restore()}_rotateSourceRegion(e,r,n,a,s){return s===90?[e,r,n,a]=[r,this.codedHeight-e-n,a,n]:s===180?[e,r]=[this.codedWidth-e-n,this.codedHeight-r-a]:s===270&&([e,r,n,a]=[this.codedWidth-r-a,e,a,n]),{sx:e,sy:r,sWidth:n,sHeight:a}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(g(this._data!==null),this._data instanceof Uint8Array){const 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()}}const qe=t=>typeof VideoFrame<"u"&&t instanceof VideoFrame,Ii=(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),g(t.width>=0),g(t.height>=0)},Ai=(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.")},wt=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class Ee{get microsecondTimestamp(){return Math.trunc(ye*this.timestamp)}get microsecondDuration(){return Math.trunc(ye*this.duration)}constructor(e){if(this._closed=!1,Ke(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(!wt.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.");const r=e.data.byteLength/(je(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.");const a=this.numberOfFrames*this.numberOfChannels*je(this.format);if(n.byteLength<a)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=n}tt?.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&&!wt.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.");const r=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const a=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-n;if(a>this.numberOfFrames-n)throw new RangeError("frameCount out of range");const s=je(r),i=ct(r);if(i&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!i&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(i?a:a*this.numberOfChannels)*s}copyTo(e,r){if(!pt(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&&!wt.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.");const{planeIndex:n,format:a,frameCount:s,frameOffset:i}=r,o=a??this.format;if(!o)throw new Error("Destination format not determined");const c=this.numberOfFrames,l=this.numberOfChannels,u=i??0;if(u>=c)throw new RangeError("frameOffset out of range");const d=s!==void 0?s:c-u;if(d>c-u)throw new RangeError("frameCount out of range");const f=je(o),h=ct(o);if(h&&n>=l)throw new RangeError("planeIndex out of range");if(!h&&n!==0)throw new RangeError("planeIndex out of range");const p=(h?d:d*l)*f;if(e.byteLength<p)throw new RangeError("Destination buffer is too small");const T=Y(e),k=Oi(o);if(Ke(this._data))if(h)if(o==="f32-planar")this._data.copyTo(e,{planeIndex:n,frameOffset:u,frameCount:d,format:"f32-planar"});else{const b=new ArrayBuffer(d*4),y=new Float32Array(b);this._data.copyTo(y,{planeIndex:n,frameOffset:u,frameCount:d,format:"f32-planar"});const S=new DataView(b);for(let P=0;P<d;P++){const B=P*f,I=S.getFloat32(P*4,!0);k(T,B,I)}}else{const b=l,y=new Float32Array(d);for(let S=0;S<b;S++){this._data.copyTo(y,{planeIndex:S,frameOffset:u,frameCount:d,format:"f32-planar"});for(let P=0;P<d;P++){const I=(P*b+S)*f;k(T,I,y[P])}}}else{const b=this._data,y=Y(b),S=this.format,P=Bi(S),B=je(S),I=ct(S);for(let E=0;E<d;E++)if(h){const W=E*f;let M;I?M=(n*c+(E+u))*B:M=((E+u)*l+n)*B;const O=P(y,M);k(T,W,O)}else for(let W=0;W<l;W++){const O=(E*l+W)*f;let ue;I?ue=(W*c+(E+u))*B:ue=((E+u)*l+W)*B;const Le=P(y,ue);k(T,O,Le)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(Ke(this._data)){const e=new Ee(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new Ee({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(tt?.unregister(this),Ke(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(Ke(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(ct(this.format)){const 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{const 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.");const 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.");const n=48e3*5,a=e.numberOfChannels,s=e.sampleRate,i=e.length,o=Math.floor(n/a);let c=0,l=i;for(;l>0;){const u=Math.min(o,l),d=new Float32Array(a*u);for(let f=0;f<a;f++)e.copyFromChannel(d.subarray(f*u,(f+1)*u),f,c);yield new Ee({format:"f32-planar",sampleRate:s,numberOfFrames:u,numberOfChannels:a,timestamp:r+c/s,data:d}),c+=u,l-=u}}static fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const n=48e3*5,a=e.numberOfChannels,s=e.sampleRate,i=e.length,o=Math.floor(n/a);let c=0,l=i;const u=[];for(;l>0;){const d=Math.min(o,l),f=new Float32Array(a*d);for(let m=0;m<a;m++)e.copyFromChannel(f.subarray(m*d,(m+1)*d),m,c);const h=new Ee({format:"f32-planar",sampleRate:s,numberOfFrames:d,numberOfChannels:a,timestamp:r+c/s,data:f});u.push(h),c+=d,l-=d}return u}}const je=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")}},ct=t=>{switch(t){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Bi=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)}},Oi=t=>{switch(t){case"u8":case"u8-planar":return(e,r,n)=>e.setUint8(r,q((n+1)*127.5,0,255));case"s16":case"s16-planar":return(e,r,n)=>e.setInt16(r,q(Math.round(n*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,r,n)=>e.setInt32(r,q(Math.round(n*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,r,n)=>e.setFloat32(r,n,!0)}},Ke=t=>typeof AudioData<"u"&&t instanceof AudioData;const De=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.")},kr=t=>{if(!Kt(t))throw new TypeError("timestamp must be a number.")},yt=(t,e,r)=>r.verifyKeyPackets?e.then(async n=>{if(!n||n.type==="delta")return n;const a=await t.determinePacketType(n);return a&&(n.type=a),n}):e;class zi{constructor(e){if(!(e instanceof Xt))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(De(e),this._track.input._disposed)throw new ee;return yt(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,r={}){if(kr(e),De(r),this._track.input._disposed)throw new ee;return yt(this._track,this._track._backing.getPacket(e,r),r)}getNextPacket(e,r={}){if(!(e instanceof L))throw new TypeError("packet must be an EncodedPacket.");if(De(r),this._track.input._disposed)throw new ee;return yt(this._track,this._track._backing.getNextPacket(e,r),r)}async getKeyPacket(e,r={}){if(kr(e),De(r),this._track.input._disposed)throw new ee;if(!r.verifyKeyPackets)return this._track._backing.getKeyPacket(e,r);const n=await this._track._backing.getKeyPacket(e,r);return n&&(g(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 L))throw new TypeError("packet must be an EncodedPacket.");if(De(r),this._track.input._disposed)throw new ee;if(!r.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,r);const n=await this._track._backing.getNextKeyPacket(e,r);return n&&(g(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getNextKeyPacket(n,r):n)}packets(e,r,n={}){if(e!==void 0&&!(e instanceof L))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 L))throw new TypeError("endPacket must be an EncodedPacket.");if(De(n),this._track.input._disposed)throw new ee;const a=[];let{promise:s,resolve:i}=Ne(),{promise:o,resolve:c}=Ne(),l=!1,u=!1,d=null;const f=[],h=()=>Math.max(2,f.length);(async()=>{let p=e??await this.getFirstPacket(n);for(;p&&!u&&!this._track.input._disposed&&!(r&&p.sequenceNumber>=r?.sequenceNumber);){if(a.length>h()){({promise:o,resolve:c}=Ne()),await o;continue}a.push(p),i(),{promise:s,resolve:i}=Ne(),p=await this.getNextPacket(p,n)}l=!0,i()})().catch(p=>{d||(d=p,i())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new ee;if(u)return{value:void 0,done:!0};if(d)throw d;if(a.length>0){const p=a.shift(),T=performance.now();for(f.push(T);f.length>0&&T-f[0]>=1e3;)f.shift();return c(),{value:p,done:!1}}else{if(l)return{value:void 0,done:!0};await s}}},async return(){return u=!0,c(),i(),{value:void 0,done:!0}},async throw(p){throw p},[Symbol.asyncIterator](){return this}}}}class Xt{constructor(e,r){this.input=e,this._backing=r}isVideoTrack(){return this instanceof Gt}isAudioTrack(){return this instanceof Yt}get id(){return this._backing.getId()}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){const r=new zi(this);let n=1/0,a=-1/0,s=0,i=0;for await(const o of r.packets(void 0,void 0,{metadataOnly:!0})){if(s>=e&&o.timestamp>=a)break;n=Math.min(n,o.timestamp),a=Math.max(a,o.timestamp+o.duration),s++,i+=o.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(a-n)).toPrecision(16)):0,averageBitrate:s?Number((8*i/(a-n)).toPrecision(16)):0}}}class Gt extends Xt{constructor(e,r){super(e,r),this._backing=r}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 displayWidth(){return this._backing.getRotation()%180===0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180===0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const 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{const e=await this._backing.getDecoderConfig();if(!e)return!1;const r=this._backing.getCodec();return g(r!==null),Pi.some(a=>a.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 L))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;const r=await this.getDecoderConfig();return g(r),vi(this.codec,r,e.data)}}class Yt extends Xt{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{const e=await this._backing.getDecoderConfig();if(!e)return!1;const r=this._backing.getCodec();return g(r!==null),_i.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 L))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}}const en=t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");if(t.codecStrings.length>0){const n=[...new Set(t.codecStrings)];r+=`; codecs="${n.join(", ")}"`}return r};const me=8,Fe=16,Te=t=>{let e=x(t);const r=Ue(t,4);let n=8;e===1&&(e=J(t),n=16);const s=e-n;return s<0?null:{name:r,totalSize:e,headerSize:n,contentSize:s}},xe=t=>Ie(t)/65536,Ct=t=>Ie(t)/1073741824,St=t=>{let e=0;for(let r=0;r<4;r++){e<<=7;const n=A(t);if(e|=n&127,(n&128)===0)break}return e},ne=t=>{let e=Q(t);return t.skip(2),e=Math.min(e,t.remainingLength),et.decode(N(t,e))},Ri=t=>{const e=Te(t);if(!e||e.name!=="data"||t.remainingLength<8)return null;const r=x(t);t.skip(4);const n=N(t,e.contentSize-8);switch(r){case 1:return et.decode(n);case 2:return new TextDecoder("utf-16be").decode(n);case 13:return new Ve(n,"image/jpeg");case 14:return new Ve(n,"image/png");case 27:return new Ve(n,"image/bmp");default:return n}};class Di extends Jr{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(){const 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();const e=await Promise.all(this.tracks.map(r=>r.inputTrack.getCodecParameterString()));return en({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,me,Fe);if(r instanceof Promise&&(r=await r),!r)break;const n=e,a=Te(r);if(!a)break;if(a.name==="ftyp"){const s=Ue(r,4);this.isQuickTime=s==="qt "}else if(a.name==="moov"){let s=this.reader.requestSlice(r.filePos,a.contentSize);if(s instanceof Promise&&(s=await s),!s)break;this.moovSlice=s,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((i,o)=>Number(o.disposition.default)-Number(i.disposition.default));for(const i of this.tracks){const o=i.editListPreviousSegmentDurations/this.movieTimescale;i.editListOffset-=Math.round(o*i.timescale)}break}e=n+a.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let r=this.reader.requestSlice(this.reader.fileSize-4,4);r instanceof Promise&&(r=await r),g(r);const n=x(r),a=this.reader.fileSize-n;if(a>=0&&a<=this.reader.fileSize-Fe){let s=this.reader.requestSliceRange(a,me,Fe);if(s instanceof Promise&&(s=await s),s){const i=Te(s);if(i&&i.name==="mfra"){let o=this.reader.requestSlice(s.filePos,i.contentSize);o instanceof Promise&&(o=await o),o&&this.readContiguousBoxes(o)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;const r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=r,g(this.moovSlice);const n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&X.includes(e.info.codec)&&r.sampleCompositionTimeOffsets.length===0){g(e.info?.type==="audio");const s=ze(e.info.codec),i=[],o=[];for(let c=0;c<r.sampleToChunk.length;c++){const l=r.sampleToChunk[c],u=r.sampleToChunk[c+1],d=(u?u.startChunkIndex:r.chunkOffsets.length)-l.startChunkIndex;for(let f=0;f<d;f++){const h=l.startSampleIndex+f*l.samplesPerChunk,m=h+l.samplesPerChunk,p=U(r.sampleTimingEntries,h,E=>E.startIndex),T=r.sampleTimingEntries[p],k=U(r.sampleTimingEntries,m,E=>E.startIndex),b=r.sampleTimingEntries[k],y=T.startDecodeTimestamp+(h-T.startIndex)*T.delta,P=b.startDecodeTimestamp+(m-b.startIndex)*b.delta-y,B=$(i);B&&B.delta===P?B.count++:i.push({startIndex:l.startChunkIndex+f,startDecodeTimestamp:y,count:1,delta:P});const I=l.samplesPerChunk*s.sampleSize*e.info.numberOfChannels;o.push(I)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}r.sampleTimingEntries=i,r.sampleSizes=o}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(const s of r.sampleTimingEntries)for(let i=0;i<s.count;i++)r.presentationTimestamps.push({presentationTimestamp:s.startDecodeTimestamp+i*s.delta,sampleIndex:s.startIndex+i});for(const s of r.sampleCompositionTimeOffsets)for(let i=0;i<s.count;i++){const o=s.startIndex+i,c=r.presentationTimestamps[o];c&&(c.presentationTimestamp+=s.offset)}r.presentationTimestamps.sort((s,i)=>s.presentationTimestamp-i.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,me,Fe);r instanceof Promise&&(r=await r),g(r);const n=Te(r);g(n?.name==="moof");let a=this.reader.requestSlice(e,n.totalSize);a instanceof Promise&&(a=await a),g(a),this.traverseBox(a);const s=this.lastReadFragment;g(s&&s.moofOffset===e);for(const[,i]of s.trackData){const o=i.track,{fragmentPositionCache:c}=o;if(!i.startTimestampIsFinal){const u=o.fragmentLookupTable.find(d=>d.moofOffset===s.moofOffset);if(u)xt(i,u.timestamp);else{const d=U(c,s.moofOffset-1,f=>f.moofOffset);if(d!==-1){const f=c[d];xt(i,f.endTimestamp)}}i.startTimestampIsFinal=!0}const l=U(c,i.startTimestamp,u=>u.startTimestamp);(l===-1||c[l].moofOffset!==s.moofOffset)&&c.splice(l+1,0,{moofOffset:s.moofOffset,startTimestamp:i.startTimestamp,endTimestamp:i.endTimestamp})}return s}readContiguousBoxes(e){const r=e.filePos;for(;e.filePos-r<=e.length-me&&this.traverseBox(e););}*iterateContiguousBoxes(e){const r=e.filePos;for(;e.filePos-r<=e.length-me;){const n=e.filePos,a=Te(e);if(!a)break;yield{boxInfo:a,slice:e},e.filePos=n+a.totalSize}}traverseBox(e){const r=e.filePos,n=Te(e);if(!n)return!1;const a=e.filePos,s=r+n.totalSize;switch(n.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(a,n.contentSize));break;case"mvhd":{const i=A(e);e.skip(3),i===1?(e.skip(16),this.movieTimescale=x(e),this.movieDurationInTimescale=J(e)):(e.skip(8),this.movieTimescale=x(e),this.movieDurationInTimescale=x(e))}break;case"trak":{const i={id:-1,demuxer:this,inputTrack:null,disposition:{...Vr},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Pe,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=i,this.readContiguousBoxes(e.slice(a,n.contentSize)),i.id!==-1&&i.timescale!==-1&&i.info!==null){if(i.info.type==="video"&&i.info.width!==-1){const o=i;i.inputTrack=new Gt(this.input,new Mi(o)),this.tracks.push(i)}else if(i.info.type==="audio"&&i.info.numberOfChannels!==-1){const o=i;i.inputTrack=new Yt(this.input,new Ni(o)),this.tracks.push(i)}}this.currentTrack=null}break;case"tkhd":{const i=this.currentTrack;if(!i)break;const o=A(e),l=!!(Xe(e)&1);if(i.disposition.default=l,o===0)e.skip(8),i.id=x(e),e.skip(4),i.durationInMovieTimescale=x(e);else if(o===1)e.skip(16),i.id=x(e),e.skip(4),i.durationInMovieTimescale=J(e);else throw new Error(`Incorrect track header version ${o}.`);e.skip(16);const u=[xe(e),xe(e),Ct(e),xe(e),xe(e),Ct(e),xe(e),xe(e),Ct(e)],d=vr(Hn(Hi(u),90));g(d===0||d===90||d===180||d===270),i.rotation=d}break;case"elst":{const i=this.currentTrack;if(!i)break;const o=A(e);e.skip(3);let c=!1,l=0;const u=x(e);for(let d=0;d<u;d++){const f=o===1?J(e):x(e),h=o===1?ns(e):Ie(e),m=xe(e);if(f!==0){if(c){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(h===-1){l+=f;continue}if(m!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}i.editListPreviousSegmentDurations=l,i.editListOffset=h,c=!0}}}break;case"mdhd":{const i=this.currentTrack;if(!i)break;const o=A(e);e.skip(3),o===0?(e.skip(8),i.timescale=x(e),i.durationInMediaTimescale=x(e)):o===1&&(e.skip(16),i.timescale=x(e),i.durationInMediaTimescale=J(e));let c=Q(e);if(c>0){i.languageCode="";for(let l=0;l<3;l++)i.languageCode=String.fromCharCode(96+(c&31))+i.languageCode,c>>=5;jt(i.languageCode)||(i.languageCode=Pe)}}break;case"hdlr":{const i=this.currentTrack;if(!i)break;e.skip(8);const o=Ue(e,4);o==="vide"?i.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:o==="soun"&&(i.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{const i=this.currentTrack;if(!i)break;i.sampleTableByteOffset=r,this.readContiguousBoxes(e.slice(a,n.contentSize))}break;case"stsd":{const i=this.currentTrack;if(!i||i.info===null||i.sampleTable)break;const o=A(e);e.skip(3);const c=x(e);for(let l=0;l<c;l++){const u=e.filePos,d=Te(e);if(!d)break;i.internalCodecId=d.name;const f=d.name.toLowerCase();if(i.info.type==="video")f==="avc1"||f==="avc3"?(i.info.codec="avc",i.info.avcType=f==="avc1"?1:3):f==="hvc1"||f==="hev1"?i.info.codec="hevc":f==="vp08"?i.info.codec="vp8":f==="vp09"?i.info.codec="vp9":f==="av01"?i.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${d.name}').`),e.skip(24),i.info.width=Q(e),i.info.height=Q(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos));else{f==="mp4a"||(f==="opus"?i.info.codec="opus":f==="flac"?i.info.codec="flac":f==="twos"||f==="sowt"||f==="raw "||f==="in24"||f==="in32"||f==="fl32"||f==="fl64"||f==="lpcm"||f==="ipcm"||f==="fpcm"||(f==="ulaw"?i.info.codec="ulaw":f==="alaw"?i.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${d.name}').`))),e.skip(8);const h=Q(e);e.skip(6);let m=Q(e),p=Q(e);e.skip(4);let T=x(e)/65536;if(o===0&&h>0){if(h===1)e.skip(4),p=8*x(e),e.skip(8);else if(h===2){e.skip(4),T=hn(e),m=x(e),e.skip(4),p=x(e);const k=x(e);if(e.skip(8),f==="lpcm"){const b=p+7>>3,y=!!(k&1),S=!!(k&2),P=k&4?-1:0;p>0&&p<=64&&(y?p===32&&(i.info.codec=S?"pcm-f32be":"pcm-f32"):P&1<<b-1?b===1?i.info.codec="pcm-s8":b===2?i.info.codec=S?"pcm-s16be":"pcm-s16":b===3?i.info.codec=S?"pcm-s24be":"pcm-s24":b===4&&(i.info.codec=S?"pcm-s32be":"pcm-s32"):b===1&&(i.info.codec="pcm-u8")),i.info.codec===null&&console.warn("Unsupported PCM format.")}}}i.info.codec==="opus"&&(T=Lr),i.info.numberOfChannels=m,i.info.sampleRate=T,f==="twos"?p===8?i.info.codec="pcm-s8":p===16?i.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${p} for codec 'twos'.`),i.info.codec=null):f==="sowt"?p===8?i.info.codec="pcm-s8":p===16?i.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${p} for codec 'sowt'.`),i.info.codec=null):f==="raw "?i.info.codec="pcm-u8":f==="in24"?i.info.codec="pcm-s24be":f==="in32"?i.info.codec="pcm-s32be":f==="fl32"?i.info.codec="pcm-f32be":f==="fl64"?i.info.codec="pcm-f64be":f==="ipcm"?i.info.codec="pcm-s16be":f==="fpcm"&&(i.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos))}}}break;case"avcC":{const i=this.currentTrack;if(!i)break;g(i.info),i.info.codecDescription=N(e,n.contentSize)}break;case"hvcC":{const i=this.currentTrack;if(!i)break;g(i.info),i.info.codecDescription=N(e,n.contentSize)}break;case"vpcC":{const i=this.currentTrack;if(!i)break;g(i.info?.type==="video"),e.skip(4);const o=A(e),c=A(e),l=A(e),u=l>>4,d=l>>1&7,f=l&1,h=A(e),m=A(e),p=A(e);i.info.vp9CodecInfo={profile:o,level:c,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:h,transferCharacteristics:m,matrixCoefficients:p}}break;case"av1C":{const i=this.currentTrack;if(!i)break;g(i.info?.type==="video"),e.skip(1);const o=A(e),c=o>>5,l=o&31,u=A(e),d=u>>7,f=u>>6&1,h=u>>5&1,m=u>>4&1,p=u>>3&1,T=u>>2&1,k=u&3,b=c===2&&f?h?12:10:f?10:8;i.info.av1CodecInfo={profile:c,level:l,tier:d,bitDepth:b,monochrome:m,chromaSubsamplingX:p,chromaSubsamplingY:T,chromaSamplePosition:k}}break;case"colr":{const i=this.currentTrack;if(!i||(g(i.info?.type==="video"),Ue(e,4)!=="nclx"))break;const c=Q(e),l=Q(e),u=Q(e),d=!!(A(e)&128);i.info.colorSpace={primaries:Pr[c],transfer:_r[l],matrix:Er[u],fullRange:d}}break;case"wave":this.readContiguousBoxes(e.slice(a,n.contentSize));break;case"esds":{const i=this.currentTrack;if(!i)break;g(i.info?.type==="audio"),e.skip(4);const o=A(e);g(o===3),St(e),e.skip(2);const c=A(e),l=(c&128)!==0,u=(c&64)!==0,d=(c&32)!==0;if(l&&e.skip(2),u){const T=A(e);e.skip(T)}d&&e.skip(2);const f=A(e);g(f===4);const h=St(e),m=e.filePos,p=A(e);if(p===64||p===103?(i.info.codec="aac",i.info.aacCodecInfo={isMpeg2:p===103}):p===105||p===107?i.info.codec="mp3":p===221?i.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${p}) - discarding track.`),e.skip(12),h>e.filePos-m){const T=A(e);g(T===5);const k=St(e);if(i.info.codecDescription=N(e,k),i.info.codec==="aac"){const b=Qt(i.info.codecDescription);b.numberOfChannels!==null&&(i.info.numberOfChannels=b.numberOfChannels),b.sampleRate!==null&&(i.info.sampleRate=b.sampleRate)}}}break;case"enda":{const i=this.currentTrack;if(!i)break;g(i.info?.type==="audio"),Q(e)&255&&(i.info.codec==="pcm-s16be"?i.info.codec="pcm-s16":i.info.codec==="pcm-s24be"?i.info.codec="pcm-s24":i.info.codec==="pcm-s32be"?i.info.codec="pcm-s32":i.info.codec==="pcm-f32be"?i.info.codec="pcm-f32":i.info.codec==="pcm-f64be"&&(i.info.codec="pcm-f64"))}break;case"pcmC":{const i=this.currentTrack;if(!i)break;g(i.info?.type==="audio"),e.skip(4);const c=!!(A(e)&1),l=A(e);i.info.codec==="pcm-s16be"?c?l===16?i.info.codec="pcm-s16":l===24?i.info.codec="pcm-s24":l===32?i.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${l}.`),i.info.codec=null):l===16?i.info.codec="pcm-s16be":l===24?i.info.codec="pcm-s24be":l===32?i.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${l}.`),i.info.codec=null):i.info.codec==="pcm-f32be"&&(c?l===32?i.info.codec="pcm-f32":l===64?i.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${l}.`),i.info.codec=null):l===32?i.info.codec="pcm-f32be":l===64?i.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${l}.`),i.info.codec=null));break}case"dOps":{const i=this.currentTrack;if(!i)break;g(i.info?.type==="audio"),e.skip(1);const o=A(e),c=Q(e),l=x(e),u=Wt(e),d=A(e);let f;d!==0?f=N(e,2+o):f=new Uint8Array(0);const h=new Uint8Array(19+f.byteLength),m=new DataView(h.buffer);m.setUint32(0,1332770163,!1),m.setUint32(4,1214603620,!1),m.setUint8(8,1),m.setUint8(9,o),m.setUint16(10,c,!0),m.setUint32(12,l,!0),m.setInt16(16,u,!0),m.setUint8(18,d),h.set(f,19),i.info.codecDescription=h,i.info.numberOfChannels=o}break;case"dfLa":{const i=this.currentTrack;if(!i)break;g(i.info?.type==="audio"),e.skip(4);const o=127,c=128,l=e.filePos;for(;e.filePos<s;){const m=A(e),p=Xe(e);if((m&o)===Rt.STREAMINFO){e.skip(10);const k=x(e),b=k>>>12,y=(k>>9&7)+1;i.info.sampleRate=b,i.info.numberOfChannels=y,e.skip(20)}else e.skip(p);if(m&c)break}const u=e.filePos;e.filePos=l;const d=N(e,u-l),f=new Uint8Array(4+d.byteLength);new DataView(f.buffer).setUint32(0,1716281667,!1),f.set(d,4),i.info.codecDescription=f}break;case"stts":{const i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);const o=x(e);let c=0,l=0;for(let u=0;u<o;u++){const d=x(e),f=x(e);i.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:d,delta:f}),c+=d,l+=d*f}}break;case"ctts":{const i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);const o=x(e);let c=0;for(let l=0;l<o;l++){const u=x(e),d=Ie(e);i.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:u,offset:d}),c+=u}}break;case"stsz":{const i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);const o=x(e),c=x(e);if(o===0)for(let l=0;l<c;l++){const u=x(e);i.sampleTable.sampleSizes.push(u)}else i.sampleTable.sampleSizes.push(o)}break;case"stz2":{const i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4),e.skip(3);const o=A(e),c=x(e),l=N(e,Math.ceil(c*o/8)),u=new K(l);for(let d=0;d<c;d++){const f=u.readBits(o);i.sampleTable.sampleSizes.push(f)}}break;case"stss":{const i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4),i.sampleTable.keySampleIndices=[];const o=x(e);for(let c=0;c<o;c++){const l=x(e)-1;i.sampleTable.keySampleIndices.push(l)}i.sampleTable.keySampleIndices[0]!==0&&i.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);const o=x(e);for(let l=0;l<o;l++){const u=x(e)-1,d=x(e),f=x(e);i.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:u,samplesPerChunk:d,sampleDescriptionIndex:f})}let c=0;for(let l=0;l<i.sampleTable.sampleToChunk.length;l++)if(i.sampleTable.sampleToChunk[l].startSampleIndex=c,l<i.sampleTable.sampleToChunk.length-1){const d=i.sampleTable.sampleToChunk[l+1].startChunkIndex-i.sampleTable.sampleToChunk[l].startChunkIndex;c+=d*i.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{const i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);const o=x(e);for(let c=0;c<o;c++){const l=x(e);i.sampleTable.chunkOffsets.push(l)}}break;case"co64":{const i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);const o=x(e);for(let c=0;c<o;c++){const l=J(e);i.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(a,n.contentSize));break;case"mehd":{const i=A(e);e.skip(3);const o=i===1?J(e):x(e);this.movieDurationInTimescale=o}break;case"trex":{e.skip(4);const i=x(e),o=x(e),c=x(e),l=x(e),u=x(e);this.fragmentTrackDefaults.push({trackId:i,defaultSampleDescriptionIndex:o,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:u})}break;case"tfra":{const i=A(e);e.skip(3);const o=x(e),c=this.tracks.find(b=>b.id===o);if(!c)break;const l=x(e),u=(l&48)>>4,d=(l&12)>>2,f=l&3,h=[A,Q,Xe,x],m=h[u],p=h[d],T=h[f],k=x(e);for(let b=0;b<k;b++){const y=i===1?J(e):x(e),S=i===1?J(e):x(e);m(e),p(e),T(e),c.fragmentLookupTable.push({timestamp:y,moofOffset:S})}c.fragmentLookupTable.sort((b,y)=>b.timestamp-y.timestamp);for(let b=0;b<c.fragmentLookupTable.length-1;b++){const y=c.fragmentLookupTable[b],S=c.fragmentLookupTable[b+1];y.timestamp===S.timestamp&&(c.fragmentLookupTable.splice(b+1,1),b--)}}break;case"moof":this.currentFragment={moofOffset:r,moofSize:n.totalSize,implicitBaseDataOffset:r,trackData:new Map},this.readContiguousBoxes(e.slice(a,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(g(this.currentFragment),this.readContiguousBoxes(e.slice(a,n.contentSize)),this.currentTrack){const i=this.currentFragment.trackData.get(this.currentTrack.id);if(i){const{currentFragmentState:o}=this.currentTrack;g(o),o.startTimestamp!==null&&(xt(i,o.startTimestamp),i.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{g(this.currentFragment),e.skip(1);const i=Xe(e),o=!!(i&1),c=!!(i&2),l=!!(i&8),u=!!(i&16),d=!!(i&32),f=!!(i&65536),h=!!(i&131072),m=x(e),p=this.tracks.find(k=>k.id===m);if(!p)break;const T=this.fragmentTrackDefaults.find(k=>k.trackId===m);this.currentTrack=p,p.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:T?.defaultSampleDescriptionIndex??null,defaultSampleDuration:T?.defaultSampleDuration??null,defaultSampleSize:T?.defaultSampleSize??null,defaultSampleFlags:T?.defaultSampleFlags??null,startTimestamp:null},o?p.currentFragmentState.baseDataOffset=J(e):h&&(p.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(p.currentFragmentState.sampleDescriptionIndex=x(e)),l&&(p.currentFragmentState.defaultSampleDuration=x(e)),u&&(p.currentFragmentState.defaultSampleSize=x(e)),d&&(p.currentFragmentState.defaultSampleFlags=x(e)),f&&(p.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const i=this.currentTrack;if(!i)break;g(i.currentFragmentState);const o=A(e);e.skip(3);const c=o===0?x(e):J(e);i.currentFragmentState.startTimestamp=c}break;case"trun":{const i=this.currentTrack;if(!i)break;if(g(this.currentFragment),g(i.currentFragmentState),this.currentFragment.trackData.has(i.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}const o=A(e),c=Xe(e),l=!!(c&1),u=!!(c&4),d=!!(c&256),f=!!(c&512),h=!!(c&1024),m=!!(c&2048),p=x(e);let T=i.currentFragmentState.baseDataOffset;l&&(T+=Ie(e));let k=null;u&&(k=x(e));let b=T;if(p===0){this.currentFragment.implicitBaseDataOffset=b;break}let y=0;const S={track:i,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(i.id,S);for(let I=0;I<p;I++){let E;d?E=x(e):(g(i.currentFragmentState.defaultSampleDuration!==null),E=i.currentFragmentState.defaultSampleDuration);let W;f?W=x(e):(g(i.currentFragmentState.defaultSampleSize!==null),W=i.currentFragmentState.defaultSampleSize);let M;h?M=x(e):(g(i.currentFragmentState.defaultSampleFlags!==null),M=i.currentFragmentState.defaultSampleFlags),I===0&&k!==null&&(M=k);let O=0;m&&(o===0?O=x(e):O=Ie(e));const ue=!(M&65536);S.samples.push({presentationTimestamp:y+O,duration:E,byteOffset:b,byteSize:W,isKeyFrame:ue}),b+=W,y+=E}S.presentationTimestamps=S.samples.map((I,E)=>({presentationTimestamp:I.presentationTimestamp,sampleIndex:E})).sort((I,E)=>I.presentationTimestamp-E.presentationTimestamp);for(let I=0;I<S.presentationTimestamps.length;I++){const E=S.presentationTimestamps[I],W=S.samples[E.sampleIndex];if(S.firstKeyFrameTimestamp===null&&W.isKeyFrame&&(S.firstKeyFrameTimestamp=W.presentationTimestamp),I<S.presentationTimestamps.length-1){const M=S.presentationTimestamps[I+1];W.duration=M.presentationTimestamp-E.presentationTimestamp}}const P=S.samples[S.presentationTimestamps[0].sampleIndex],B=S.samples[$(S.presentationTimestamps).sampleIndex];S.startTimestamp=P.presentationTimestamp,S.endTimestamp=B.presentationTimestamp+B.duration,this.currentFragment.implicitBaseDataOffset=b}break;case"udta":{const i=this.iterateContiguousBoxes(e.slice(a,n.contentSize));for(const{boxInfo:o,slice:c}of i){if(o.name!=="meta"&&!this.currentTrack){const l=c.filePos;this.metadataTags.raw??={},o.name[0]==="©"?this.metadataTags.raw[o.name]??=ne(c):this.metadataTags.raw[o.name]??=N(c,o.contentSize),c.filePos=l}switch(o.name){case"meta":c.skip(-o.headerSize),this.traverseBox(c);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=et.decode(N(c,o.contentSize)):this.metadataTags.title??=ne(c);break;case"©des":this.currentTrack||(this.metadataTags.description??=ne(c));break;case"©ART":this.currentTrack||(this.metadataTags.artist??=ne(c));break;case"©alb":this.currentTrack||(this.metadataTags.album??=ne(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=ne(c));break;case"©gen":this.currentTrack||(this.metadataTags.genre??=ne(c));break;case"©day":if(!this.currentTrack){const l=new Date(ne(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"©cmt":this.currentTrack||(this.metadataTags.comment??=ne(c));break;case"©lyr":this.currentTrack||(this.metadataTags.lyrics??=ne(c));break}}}break;case"meta":{if(this.currentTrack)break;const o=x(e)!==0;this.currentMetadataKeys=new Map,o?this.readContiguousBoxes(e.slice(a,n.contentSize)):this.readContiguousBoxes(e.slice(a+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const i=x(e);for(let o=0;o<i;o++){const c=x(e);e.skip(4);const l=et.decode(N(e,c-8));this.currentMetadataKeys.set(o+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const i=this.iterateContiguousBoxes(e.slice(a,n.contentSize));for(const{boxInfo:o,slice:c}of i){let l=o.name;const u=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(u)&&(l=this.currentMetadataKeys.get(u));const d=Ri(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=d,l){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":typeof d=="string"&&(this.metadataTags.title??=d);break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof d=="string"&&(this.metadataTags.description??=d);break;case"©ART":case"com.apple.quicktime.artist":case"artist":typeof d=="string"&&(this.metadataTags.artist??=d);break;case"©alb":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"©cmt":case"com.apple.quicktime.comment":case"comment":typeof d=="string"&&(this.metadataTags.comment??=d);break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof d=="string"&&(this.metadataTags.genre??=d);break;case"©lyr":case"lyrics":typeof d=="string"&&(this.metadataTags.lyrics??=d);break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof d=="string"){const f=new Date(d);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"covr":case"com.apple.quicktime.artwork":d instanceof Ve?(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"){const f=d.split("/"),h=Number.parseInt(f[0],10),m=f[1]&&Number.parseInt(f[1],10);Number.isInteger(h)&&h>0&&(this.metadataTags.trackNumber??=h),m&&Number.isInteger(m)&&m>0&&(this.metadataTags.tracksTotal??=m)}break;case"trkn":if(d instanceof Uint8Array&&d.length>=6){const f=Y(d),h=f.getUint16(2,!1),m=f.getUint16(4,!1);h>0&&(this.metadataTags.trackNumber??=h),m>0&&(this.metadataTags.tracksTotal??=m)}break;case"disc":case"disk":if(d instanceof Uint8Array&&d.length>=6){const f=Y(d),h=f.getUint16(2,!1),m=f.getUint16(4,!1);h>0&&(this.metadataTags.discNumber??=h),m>0&&(this.metadataTags.discsTotal??=m)}break}}}break}return e.filePos=s,!0}}class tn{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}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(){const 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){const 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 zr(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,r){const n=this.mapTimestampIntoTimescale(e),a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Nt(a,n),i=await this.fetchPacketForSampleIndex(s,r);return!br(a)||!this.internalTrack.demuxer.isFragmented?i:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const l=U(c.presentationTimestamps,n,f=>f.presentationTimestamp),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&n<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},n,n,r)}async getNextPacket(e,r){const n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,r);const a=this.packetToFragmentLocation.get(e);if(a===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(a.fragment,s=>{if(s===a.fragment){const i=s.trackData.get(this.internalTrack.id);if(a.sampleIndex+1<i.samples.length)return{sampleIndex:a.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){const n=this.mapTimestampIntoTimescale(e),a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Vi(a,n),i=await this.fetchPacketForSampleIndex(s,r);return!br(a)||!this.internalTrack.demuxer.isFragmented?i:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const l=Ar(c.presentationTimestamps,f=>c.samples[f.sampleIndex].isKeyFrame&&f.presentationTimestamp<=n),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&n<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},n,n,r)}async getNextKeyPacket(e,r){const n=this.packetToSampleIndex.get(e);if(n!==void 0){const s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=Wi(s,n);return this.fetchPacketForSampleIndex(i,r)}const a=this.packetToFragmentLocation.get(e);if(a===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(a.fragment,s=>{if(s===a.fragment){const o=s.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>a.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{const i=s.trackData.get(this.internalTrack.id);if(i&&i.firstKeyFrameTimestamp!==null){const o=i.samples.findIndex(c=>c.isKeyFrame);return g(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,r)}async fetchPacketForSampleIndex(e,r){if(e===-1)return null;const n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Ui(n,e);if(!a)return null;let s;if(r.metadataOnly)s=He;else{let l=this.internalTrack.demuxer.reader.requestSlice(a.sampleOffset,a.sampleSize);l instanceof Promise&&(l=await l),g(l),s=N(l,a.sampleSize)}const i=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=a.duration/this.internalTrack.timescale,c=new L(s,a.isKeyFrame?"key":"delta",i,o,e,a.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,r,n){if(r===-1)return null;const s=e.trackData.get(this.internalTrack.id).samples[r];g(s);let i;if(n.metadataOnly)i=He;else{let u=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);u instanceof Promise&&(u=await u),g(u),i=N(u,s.byteSize)}const o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,l=new L(i,s.isKeyFrame?"key":"delta",o,c,e.moofOffset+r,s.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:r}),l}async performFragmentedLookup(e,r,n,a,s){const i=this.internalTrack.demuxer;let o=null,c=null,l=-1;if(e){const{sampleIndex:T,correctSampleFound:k}=r(e);if(k)return this.fetchPacketInFragment(e,T,s);T!==-1&&(c=e,l=T)}const u=U(this.internalTrack.fragmentLookupTable,n,T=>T.timestamp),d=u!==-1?this.internalTrack.fragmentLookupTable[u]:null,f=U(this.internalTrack.fragmentPositionCache,n,T=>T.startTimestamp),h=f!==-1?this.internalTrack.fragmentPositionCache[f]:null,m=Math.max(d?.moofOffset??0,h?.moofOffset??0)||null;let p;for(e?m===null||e.moofOffset>=m?(p=e.moofOffset+e.moofSize,o=e):p=m:p=m??0;;){if(o){const y=o.trackData.get(this.internalTrack.id);if(y&&y.startTimestamp>a)break}let T=i.reader.requestSliceRange(p,me,Fe);if(T instanceof Promise&&(T=await T),!T)break;const k=p,b=Te(T);if(!b)break;if(b.name==="moof"){o=await i.readFragment(k);const{sampleIndex:y,correctSampleFound:S}=r(o);if(S)return this.fetchPacketInFragment(o,y,s);y!==-1&&(c=o,l=y)}p=k+b.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){const T=this.internalTrack.fragmentLookupTable[u-1];g(!T||T.timestamp<d.timestamp);const k=T?.timestamp??-1/0;return this.performFragmentedLookup(null,r,k,a,s)}return c?this.fetchPacketInFragment(c,l,s):null}}class Mi extends tn{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}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){const e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&Gr(e.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){const e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&Zr(e.data)}return{codec:Wr(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}})():null}}class Ni extends tn{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:Hr(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}const Nt=(t,e)=>{if(t.presentationTimestamps){const r=U(t.presentationTimestamps,e,n=>n.presentationTimestamp);return r===-1?-1:t.presentationTimestamps[r].sampleIndex}else{const r=U(t.sampleTimingEntries,e,a=>a.startDecodeTimestamp);if(r===-1)return-1;const n=t.sampleTimingEntries[r];return n.startIndex+Math.min(Math.floor((e-n.startDecodeTimestamp)/n.delta),n.count-1)}},Vi=(t,e)=>{if(!t.keySampleIndices)return Nt(t,e);if(t.presentationTimestamps){const r=U(t.presentationTimestamps,e,n=>n.presentationTimestamp);if(r===-1)return-1;for(let n=r;n>=0;n--){const a=t.presentationTimestamps[n].sampleIndex;if(Ir(t.keySampleIndices,a,i=>i)!==-1)return a}return-1}else{const r=Nt(t,e),n=U(t.keySampleIndices,r,a=>a);return t.keySampleIndices[n]??-1}},Ui=(t,e)=>{const r=U(t.sampleTimingEntries,e,k=>k.startIndex),n=t.sampleTimingEntries[r];if(!n||n.startIndex+n.count<=e)return null;let s=n.startDecodeTimestamp+(e-n.startIndex)*n.delta;const i=U(t.sampleCompositionTimeOffsets,e,k=>k.startIndex),o=t.sampleCompositionTimeOffsets[i];o&&e-o.startIndex<o.count&&(s+=o.offset);const c=t.sampleSizes[Math.min(e,t.sampleSizes.length-1)],l=U(t.sampleToChunk,e,k=>k.startSampleIndex),u=t.sampleToChunk[l];g(u);const d=u.startChunkIndex+Math.floor((e-u.startSampleIndex)/u.samplesPerChunk),f=t.chunkOffsets[d],h=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk;let m=0,p=f;if(t.sampleSizes.length===1)p+=c*(e-h),m+=c*u.samplesPerChunk;else for(let k=h;k<h+u.samplesPerChunk;k++){const b=t.sampleSizes[k];k<e&&(p+=b),m+=b}let T=n.delta;if(t.presentationTimestamps){const k=t.presentationTimestampIndexMap[e];g(k!==void 0),k<t.presentationTimestamps.length-1&&(T=t.presentationTimestamps[k+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:T,sampleOffset:p,sampleSize:c,chunkOffset:f,chunkSize:m,isKeyFrame:t.keySampleIndices?Ir(t.keySampleIndices,e,k=>k)!==-1:!0}},Wi=(t,e)=>{if(!t.keySampleIndices)return e+1;const r=U(t.keySampleIndices,e,n=>n);return t.keySampleIndices[r+1]??-1},xt=(t,e)=>{t.startTimestamp+=e,t.endTimestamp+=e;for(const r of t.samples)r.presentationTimestamp+=e;for(const r of t.presentationTimestamps)r.presentationTimestamp+=e},Hi=t=>{const[e,,,r]=t,n=Math.hypot(e,r),a=e/n,s=r/n,i=-Math.atan2(s,a)*(180/Math.PI);return Number.isFinite(i)?i:0},br=t=>t.sampleSizes.length===0;var w;(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.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"})(w||(w={}));const $i=[w.EBML,w.Segment],rt=[w.SeekHead,w.Info,w.Cluster,w.Tracks,w.Cues,w.Attachments,w.Chapters,w.Tags],ut=[...$i,...rt],Vt=8,te=2,pe=2*Vt,rn=t=>{const e=A(t);if(t.skip(-1),e===0)return null;let r=1,n=128;for(;(e&n)===0;)r++,n>>=1;return r},Ye=t=>{const e=A(t);if(e===0)return null;let r=1,n=128;for(;(e&n)===0;)r++,n>>=1;let a=e&n-1;for(let s=1;s<r;s++)a*=256,a+=A(t);return a},z=(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+=A(t);return r},Li=(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(A(t));return r},Zt=t=>{const e=rn(t);return e===null?null:z(t,e)},nn=t=>{let e=A(t);return e===255?e=null:(t.skip(-1),e=Ye(t),e===72057594037927940&&(e=null)),e},fe=t=>{const e=Zt(t);if(e===null)return null;const r=nn(t);return{id:e,size:r}},Me=(t,e)=>{const r=N(t,e);let n=0;for(;n<e&&r[n]!==0;)n+=1;return String.fromCharCode(...r.subarray(0,n))},Qe=(t,e)=>{const r=N(t,e);let n=0;for(;n<e&&r[n]!==0;)n+=1;return et.decode(r.subarray(0,n))},vt=(t,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?is(t):hn(t)},Ut=async(t,e,r,n)=>{const a=new Set(r);let s=e;for(;n===null||s<n;){let i=t.requestSliceRange(s,te,pe);if(i instanceof Promise&&(i=await i),!i)break;const o=fe(i);if(!o)break;if(a.has(o.id))return{pos:s,found:!0};be(o.size),s=i.filePos+o.size}return{pos:n!==null&&n>s?n:s,found:!1}},sn=async(t,e,r,n)=>{const s=new Set(r);let i=e;for(;i<n;){let o=t.requestSliceRange(i,0,Math.min(65536,n-i));if(o instanceof Promise&&(o=await o),!o||o.length<Vt)break;for(let c=0;c<o.length-Vt;c++){o.filePos=i;const l=Zt(o);if(l!==null&&s.has(l))return i;i++}}return null},ie={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"};function be(t){if(t===null)throw new Error("Undefined element size is used in a place where it is not supported.")}const qi=t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isWebM?"webm":"x-matroska");if(t.codecStrings.length>0){const n=[...new Set(t.codecStrings.filter(Boolean))];r+=`; codecs="${n.join(", ")}"`}return r};var de;(function(t){t[t.None=0]="None",t[t.Xiph=1]="Xiph",t[t.FixedSize=2]="FixedSize",t[t.Ebml=3]="Ebml"})(de||(de={}));var mt;(function(t){t[t.Block=1]="Block",t[t.Private=2]="Private",t[t.Next=4]="Next"})(mt||(mt={}));var Je;(function(t){t[t.Zlib=0]="Zlib",t[t.Bzlib=1]="Bzlib",t[t.lzo1x=2]="lzo1x",t[t.HeaderStripping=3]="HeaderStripping"})(Je||(Je={}));const Pt=[{id:w.SeekHead,flag:"seekHeadSeen"},{id:w.Info,flag:"infoSeen"},{id:w.Tracks,flag:"tracksSeen"},{id:w.Cues,flag:"cuesSeen"}],an=10*2**20;class ji extends Jr{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(){const 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();const e=await this.getTracks(),r=await Promise.all(e.map(n=>n.getCodecParameterString()));return qi({isWebM:this.isWebM,hasVideo:this.segments.some(n=>n.tracks.some(a=>a.info?.type==="video")),hasAudio:this.segments.some(n=>n.tracks.some(a=>a.info?.type==="audio")),codecStrings:r.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const r of this.segments)r.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(r),r.metadataTagsCollected=!0);let e={};for(const 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,te,pe);if(r instanceof Promise&&(r=await r),!r)break;const n=fe(r);if(!n)break;const a=n.id;let s=n.size;const i=r.filePos;if(a===w.EBML){be(s);let o=this.reader.requestSlice(i,s);if(o instanceof Promise&&(o=await o),!o)break;this.readContiguousElements(o)}else if(a===w.Segment){if(await this.readSegment(i,s),s===null||this.reader.fileSize===null)break}else if(a===w.Cluster){if(this.reader.fileSize===null)break;s===null&&(s=(await Ut(this.reader,i,ut,this.reader.fileSize)).pos-i);const o=$(this.segments);o&&(o.elementEndPos=i+s)}be(s),e=i+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===null?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 o=this.reader.requestSliceRange(n,te,pe);if(o instanceof Promise&&(o=await o),!o)break;const c=n,l=fe(o);if(!l||!rt.includes(l.id)&&l.id!==w.Void){const m=await sn(this.reader,c,rt,Math.min(this.currentSegment.elementEndPos??1/0,c+an));if(m){n=m;continue}else break}const{id:u,size:d}=l,f=o.filePos,h=Pt.findIndex(m=>m.id===u);if(h!==-1){const m=Pt[h].flag;this.currentSegment[m]=!0,be(d);let p=this.reader.requestSlice(f,d);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(u===w.Tags||u===w.Attachments){u===w.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,be(d);let m=this.reader.requestSlice(f,d);m instanceof Promise&&(m=await m),m&&this.readContiguousElements(m)}else if(u===w.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===null)break;n=f+d}if(this.currentSegment.seekEntries.sort((o,c)=>o.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(const o of this.currentSegment.seekEntries){const c=Pt.find(m=>m.id===o.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+o.segmentPosition,te,pe);if(l instanceof Promise&&(l=await l),!l)continue;const u=fe(l);if(!u)continue;const{id:d,size:f}=u;if(d!==c.id)continue;be(f),this.currentSegment[c.flag]=!0;let h=this.reader.requestSlice(l.filePos,f);h instanceof Promise&&(h=await h),h&&this.readContiguousElements(h)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6),this.currentSegment.tracks.sort((o,c)=>Number(c.disposition.default)-Number(o.disposition.default));const a=new Map(this.currentSegment.tracks.map(o=>[o.id,o]));for(const o of this.currentSegment.cuePoints){const c=a.get(o.trackId);c&&c.cuePoints.push(o)}for(const o of this.currentSegment.tracks){o.cuePoints.sort((c,l)=>c.time-l.time);for(let c=0;c<o.cuePoints.length-1;c++){const l=o.cuePoints[c],u=o.cuePoints[c+1];l.time===u.time&&(o.cuePoints.splice(c+1,1),c--)}}let s=null,i=-1/0;for(const o of this.currentSegment.tracks)o.cuePoints.length>i&&(i=o.cuePoints.length,s=o);for(const o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,r){if(r.lastReadCluster?.elementStartPos===e)return r.lastReadCluster;let n=this.reader.requestSliceRange(e,te,pe);n instanceof Promise&&(n=await n),g(n);const a=e,s=fe(n);g(s);const i=s.id;g(i===w.Cluster);let o=s.size;const c=n.filePos;o===null&&(o=(await Ut(this.reader,c,ut,r.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,o);l instanceof Promise&&(l=await l);const u={segment:r,elementStartPos:a,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){const d=this.readContiguousElements(l,ut);u.elementEndPos=d}for(const[,d]of u.trackData){const f=d.track;g(d.blocks.length>0);let h=!1;for(let k=0;k<d.blocks.length;k++){const b=d.blocks[k];b.timestamp+=u.timestamp,h||=b.lacing!==de.None}d.presentationTimestamps=d.blocks.map((k,b)=>({timestamp:k.timestamp,blockIndex:b})).sort((k,b)=>k.timestamp-b.timestamp);for(let k=0;k<d.presentationTimestamps.length;k++){const b=d.presentationTimestamps[k],y=d.blocks[b.blockIndex];if(d.firstKeyFrameTimestamp===null&&y.isKeyFrame&&(d.firstKeyFrameTimestamp=y.timestamp),k<d.presentationTimestamps.length-1){const S=d.presentationTimestamps[k+1];y.duration=S.timestamp-y.timestamp}else y.duration===0&&f.defaultDuration!=null&&y.lacing===de.None&&(y.duration=f.defaultDuration)}h&&(this.expandLacedBlocks(d.blocks,f),d.presentationTimestamps=d.blocks.map((k,b)=>({timestamp:k.timestamp,blockIndex:b})).sort((k,b)=>k.timestamp-b.timestamp));const m=d.blocks[d.presentationTimestamps[0].blockIndex],p=d.blocks[$(d.presentationTimestamps).blockIndex];d.startTimestamp=m.timestamp,d.endTimestamp=p.timestamp+p.duration;const T=U(f.clusterPositionCache,d.startTimestamp,k=>k.startTimestamp);(T===-1||f.clusterPositionCache[T].elementStartPos!==a)&&f.clusterPositionCache.splice(T+1,0,{elementStartPos:u.elementStartPos,startTimestamp:d.startTimestamp})}return r.lastReadCluster=u,u}getTrackDataInCluster(e,r){let n=e.trackData.get(r);if(!n){const a=e.segment.tracks.find(s=>s.id===r);if(!a)return null;n={track:a,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++){const a=e[n];if(a.lacing===de.None)continue;a.decoded||(a.data=this.decodeBlockData(r,a.data),a.decoded=!0);const s=$e.tempFromBytes(a.data),i=[],o=A(s)+1;switch(a.lacing){case de.Xiph:{let l=0;for(let u=0;u<o-1;u++){let d=0;for(;s.bufferPos<s.length;){const f=A(s);if(d+=f,f<255){i.push(d),l+=d;break}}}i.push(s.length-(s.bufferPos+l))}break;case de.FixedSize:{const l=s.length-1,u=Math.floor(l/o);for(let d=0;d<o;d++)i.push(u)}break;case de.Ebml:{const l=Ye(s);g(l!==null);let u=l;i.push(u);let d=u;for(let f=1;f<o-1;f++){const h=s.bufferPos,m=Ye(s);g(m!==null);const p=m,k=(1<<(s.bufferPos-h)*7-1)-1,b=p-k;u+=b,i.push(u),d+=u}i.push(s.length-(s.bufferPos+d))}break;default:g(!1)}g(i.length===o),e.splice(n,1);const c=a.duration||o*(r.defaultDuration??0);for(let l=0;l<o;l++){const u=i[l],d=N(s,u),f=a.timestamp+c*l/o,h=c/o;e.splice(n+l,0,{timestamp:f,duration:h,isKeyFrame:a.isKeyFrame,data:d,lacing:de.None,decoded:!0,mainAdditional:a.mainAdditional})}n+=o,n--}}async loadSegmentMetadata(e){for(const r of e.seekEntries){if(!(r.id===w.Tags&&!e.tagsSeen)){if(!(r.id===w.Attachments&&!e.attachmentsSeen))continue}let n=this.reader.requestSliceRange(e.dataStartPos+r.segmentPosition,te,pe);if(n instanceof Promise&&(n=await n),!n)continue;const a=fe(n);if(!a||a.id!==r.id)continue;const{size:s}=a;be(s),g(!this.currentSegment),this.currentSegment=e;let i=this.reader.requestSlice(n.filePos,s);i instanceof Promise&&(i=await i),i&&this.readContiguousElements(i),this.currentSegment=null,r.id===w.Tags?e.tagsSeen=!0:r.id===w.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,r){const n=e.filePos;for(;e.filePos-n<=e.length-te;){const a=e.filePos;if(!this.traverseElement(e,r))return a}return e.filePos}traverseElement(e,r){const n=fe(e);if(!n||r&&r.includes(n.id))return!1;const{id:a,size:s}=n,i=e.filePos;switch(be(s),a){case w.DocType:this.isWebM=Me(e,s)==="webm";break;case w.Seek:{if(!this.currentSegment)break;const o={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(o),this.readContiguousElements(e.slice(i,s)),(o.id===-1||o.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case w.SeekID:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.id=z(e,s)}break;case w.SeekPosition:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=z(e,s)}break;case w.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=z(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case w.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=vt(e,s)}break;case w.TrackEntry:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Vr},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:Pe,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(i,s)),this.currentTrack.decodingInstructions.some(o=>o.data?.type!=="decompress"||o.scope!==mt.Block||o.data.algorithm!==Je.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){const o=this.currentTrack.codecId.indexOf("/"),c=o===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,o);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.codecId===ie.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===ie.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ie.vp8?this.currentTrack.info.codec="vp8":c===ie.vp9?this.currentTrack.info.codec="vp9":c===ie.av1&&(this.currentTrack.info.codec="av1");const l=this.currentTrack,u=new Gt(this.input,new Ki(l));this.currentTrack.inputTrack=u,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){c===ie.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2")},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===ie.mp3?this.currentTrack.info.codec="mp3":c===ie.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Lr):c===ie.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ie.flac?(this.currentTrack.info.codec="flac",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"));const l=this.currentTrack,u=new Yt(this.input,new Qi(l));this.currentTrack.inputTrack=u,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case w.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=z(e,s)}break;case w.TrackType:{if(!this.currentTrack)break;const o=z(e,s);o===1?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:o===2&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case w.FlagEnabled:{if(!this.currentTrack)break;z(e,s)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case w.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!z(e,s)}break;case w.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!z(e,s)}break;case w.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!z(e,s)}break;case w.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!z(e,s)}break;case w.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!z(e,s)}break;case w.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!z(e,s)}break;case w.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=Me(e,s)}break;case w.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=N(e,s)}break;case w.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*z(e,s)/1e9}break;case w.Name:{if(!this.currentTrack)break;this.currentTrack.name=Qe(e,s)}break;case w.Language:{if(!this.currentTrack||this.currentTrack.languageCode!==Pe)break;this.currentTrack.languageCode=Me(e,s),jt(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Pe)}break;case w.LanguageBCP47:{if(!this.currentTrack)break;const c=Me(e,s).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=Pe}break;case w.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(i,s))}break;case w.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=z(e,s)}break;case w.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=z(e,s)}break;case w.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=z(e,s)===1}break;case w.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(i,s))}break;case w.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;const o=z(e,s),c=Er[o]??null;this.currentTrack.info.colorSpace.matrix=c}break;case w.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=z(e,s)===2}break;case w.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;const o=z(e,s),c=_r[o]??null;this.currentTrack.info.colorSpace.transfer=c}break;case w.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;const o=z(e,s),c=Pr[o]??null;this.currentTrack.info.colorSpace.primaries=c}break;case w.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(i,s))}break;case w.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;const c=-vt(e,s);try{this.currentTrack.info.rotation=vr(c)}catch{}}break;case w.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(i,s))}break;case w.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=vt(e,s)}break;case w.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=z(e,s)}break;case w.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=z(e,s)}break;case w.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(i,s)),this.currentCueTime=null}break;case w.CueTime:this.currentCueTime=z(e,s);break;case w.CueTrackPositions:{if(this.currentCueTime===null)break;g(this.currentSegment);const o={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(o),this.readContiguousElements(e.slice(i,s)),(o.trackId===-1||o.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case w.CueTrack:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=z(e,s)}break;case w.CueClusterPosition:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;g(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+z(e,s)}break;case w.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=z(e,s)}break;case w.SimpleBlock:{if(!this.currentCluster)break;const o=Ye(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const l=Wt(e),u=A(e),d=u>>1&3;let f=!!(u&128);c.track.info?.type==="audio"&&c.track.info.codec&&(f=!0);const h=N(e,s-(e.filePos-i)),m=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:f,data:h,lacing:d,decoded:!m,mainAdditional:null})}break;case w.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(i,s)),this.currentBlock=null}break;case w.Block:{if(!this.currentCluster)break;const o=Ye(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const l=Wt(e),d=A(e)>>1&3,f=N(e,s-(e.filePos-i)),h=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:f,lacing:d,decoded:!h,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case w.BlockAdditions:this.readContiguousElements(e.slice(i,s));break;case w.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(i,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case w.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=N(e,s)}break;case w.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=z(e,s)}break;case w.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=z(e,s)}break;case w.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case w.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(i,s));break;case w.Targets:this.readContiguousElements(e.slice(i,s));break;case w.TargetTypeValue:z(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case w.TagTrackUID:case w.TagEditionUID:case w.TagChapterUID:case w.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case w.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(i,s))}break;case w.TagName:this.currentSimpleTagName=Qe(e,s);break;case w.TagString:{if(!this.currentSimpleTagName)break;const o=Qe(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case w.TagBinary:{if(!this.currentSimpleTagName)break;const o=N(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case w.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(i,s));const o=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(o.raw??={},o.raw[this.currentAttachedFile.fileUid.toString()]=new Nr(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){const c=this.currentAttachedFile.fileName;let l="unknown";if(c){const u=c.toLowerCase();u.startsWith("cover.")?l="coverFront":u.startsWith("back.")&&(l="coverBack")}o.images??=[],o.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:l,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case w.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=Li(e,s)}break;case w.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Qe(e,s)}break;case w.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Me(e,s)}break;case w.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=N(e,s)}break;case w.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Qe(e,s)}break;case w.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(i,s)),this.currentTrack.decodingInstructions.sort((o,c)=>c.order-o.order)}break;case w.ContentEncoding:this.currentDecodingInstruction={order:0,scope:mt.Block,data:null},this.readContiguousElements(e.slice(i,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case w.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=z(e,s)}break;case w.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=z(e,s)}break;case w.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Je.Zlib,settings:null},this.readContiguousElements(e.slice(i,s))}break;case w.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=z(e,s)}break;case w.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=N(e,s)}break;case w.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=i+s,!0}decodeBlockData(e,r){g(e.decodingInstructions.length>0);let n=r;for(const a of e.decodingInstructions)switch(g(a.data),a.data.type){case"decompress":switch(a.data.algorithm){case Je.HeaderStripping:if(a.data.settings&&a.data.settings.length>0){const s=a.data.settings,i=new Uint8Array(s.length+n.length);i.set(s,0),i.set(n,s.length),n=i}break}break}return n}processTagValue(e,r){if(!this.currentSegment?.metadataTags)return;const 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":{const a=new Date(r);Number.isNaN(a.getTime())||(n.date??=a)}break;case"track_number":case"part_number":{const a=r.split("/"),s=Number.parseInt(a[0],10),i=a[1]&&Number.parseInt(a[1],10);Number.isInteger(s)&&s>0&&(n.trackNumber??=s),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case"disc_number":case"disc":{const a=r.split("/"),s=Number.parseInt(a[0],10),i=a[1]&&Number.parseInt(a[1],10);Number.isInteger(s)&&s>0&&(n.discNumber??=s),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}break}}}class on{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){const 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 zr(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,r){const n=this.intoTimescale(e);return this.performClusterLookup(null,a=>{const s=a.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};const i=U(s.presentationTimestamps,n,l=>l.timestamp),o=i!==-1?s.presentationTimestamps[i].blockIndex:-1,c=i!==-1&&n<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},n,n,r)}async getNextPacket(e,r){const n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,a=>{if(a===n.cluster){const s=a.trackData.get(this.internalTrack.id);if(n.blockIndex+1<s.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(a.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async getKeyPacket(e,r){const n=this.intoTimescale(e);return this.performClusterLookup(null,a=>{const s=a.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};const i=Ar(s.presentationTimestamps,l=>s.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=n),o=i!==-1?s.presentationTimestamps[i].blockIndex:-1,c=i!==-1&&n<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},n,n,r)}async getNextKeyPacket(e,r){const n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,a=>{if(a===n.cluster){const i=a.trackData.get(this.internalTrack.id).blocks.findIndex((o,c)=>o.isKeyFrame&&c>n.blockIndex);if(i!==-1)return{blockIndex:i,correctBlockFound:!0}}else{const s=a.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){const i=s.blocks.findIndex(o=>o.isKeyFrame);return g(i!==-1),{blockIndex:i,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async fetchPacketInCluster(e,r,n){if(r===-1)return null;const s=e.trackData.get(this.internalTrack.id).blocks[r];g(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0);const i=n.metadataOnly?He:s.data,o=s.timestamp/this.internalTrack.segment.timestampFactor,c=s.duration/this.internalTrack.segment.timestampFactor,l={};s.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=n.metadataOnly?He:s.mainAdditional,l.alphaByteLength=s.mainAdditional.byteLength);const u=new L(i,s.isKeyFrame?"key":"delta",o,c,e.dataStartPos+r,s.data.byteLength,l);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:r}),u}async performClusterLookup(e,r,n,a,s){const{demuxer:i,segment:o}=this.internalTrack;let c=null,l=null,u=-1;if(e){const{blockIndex:k,correctBlockFound:b}=r(e);if(b)return this.fetchPacketInCluster(e,k,s);k!==-1&&(l=e,u=k)}const d=U(this.internalTrack.cuePoints,n,k=>k.time),f=d!==-1?this.internalTrack.cuePoints[d]:null,h=U(this.internalTrack.clusterPositionCache,n,k=>k.startTimestamp),m=h!==-1?this.internalTrack.clusterPositionCache[h]:null,p=Math.max(f?.clusterPosition??0,m?.elementStartPos??0)||null;let T;for(e?p===null||e.elementStartPos>=p?(T=e.elementEndPos,c=e):T=p:T=p??o.clusterSeekStartPos;o.elementEndPos===null||T<=o.elementEndPos-te;){if(c){const E=c.trackData.get(this.internalTrack.id);if(E&&E.startTimestamp>a)break}let k=i.reader.requestSliceRange(T,te,pe);if(k instanceof Promise&&(k=await k),!k)break;const b=T,y=fe(k);if(!y||!rt.includes(y.id)&&y.id!==w.Void){const E=await sn(i.reader,b,rt,Math.min(o.elementEndPos??1/0,b+an));if(E){T=E;continue}else break}const S=y.id;let P=y.size;const B=k.filePos;if(S===w.Cluster){c=await i.readCluster(b,o),P=c.elementEndPos-B;const{blockIndex:E,correctBlockFound:W}=r(c);if(W)return this.fetchPacketInCluster(c,E,s);E!==-1&&(l=c,u=E)}P===null&&(g(S!==w.Cluster),P=(await Ut(i.reader,B,ut,o.elementEndPos)).pos-B);const I=B+P;if(o.elementEndPos===null){let E=i.reader.requestSliceRange(I,te,pe);if(E instanceof Promise&&(E=await E),!E)break;if(Zt(E)===w.Segment){o.elementEndPos=I;break}}T=I}if(f&&(!l||l.elementStartPos<f.clusterPosition)){const k=this.internalTrack.cuePoints[d-1];g(!k||k.time<f.time);const b=k?.time??-1/0;return this.performClusterLookup(null,r,b,a,s)}return l?this.fetchPacketInCluster(l,u,s):null}}class Ki extends on{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}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;return(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({})),{codec:Wr({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?Qr(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Xr(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Gr(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Zr(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}})():null}}class Qi extends on{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:Hr({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}}class Jt{}class cn extends Jt{async _getMajorBrand(e){let r=e._reader.requestSlice(0,12);return r instanceof Promise&&(r=await r),!r||(r.skip(4),Ue(r,4)!=="ftyp")?null:Ue(r,4)}_createDemuxer(e){return new Di(e)}}class Xi extends cn{async _canReadInput(e){const r=await this._getMajorBrand(e);return!!r&&r!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class Gi extends cn{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class ln extends Jt{async isSupportedEBMLOfDocType(e,r){let n=e._reader.requestSlice(0,pe);if(n instanceof Promise&&(n=await n),!n)return!1;const a=rn(n);if(a===null||a<1||a>8||z(n,a)!==w.EBML)return!1;const i=nn(n);if(i===null)return!1;let o=e._reader.requestSlice(n.filePos,i);if(o instanceof Promise&&(o=await o),!o)return!1;const c=n.filePos;for(;o.filePos<=c+i-te;){const l=fe(o);if(!l)break;const{id:u,size:d}=l,f=o.filePos;if(d===null)return!1;switch(u){case w.EBMLVersion:if(z(o,d)!==1)return!1;break;case w.EBMLReadVersion:if(z(o,d)!==1)return!1;break;case w.DocType:if(Me(o,d)!==r)return!1;break;case w.DocTypeVersion:if(z(o,d)>4)return!1;break}o.filePos=f+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new ji(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Yi extends ln{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class er{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new ee;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new ee;const e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}}class Zi extends er{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&&(!Kt(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 fn({maxCacheSize:r.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:dn.fileSystem})}_retrieveSize(){const 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&&!qn()?r=this._blob.slice(e.currentPos).stream().getReader():r=null,this._readers.set(e,r));e.currentPos<e.targetPos&&!e.aborted;)if(r){const{done:n,value:a}=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+a.length),this._orchestrator.supplyWorkerData(e,a)}else{const 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}_dispose(){this._orchestrator.dispose()}}const un=.5*2**20,Ji=((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 a=null;try{typeof window<"u"&&typeof window.location<"u"&&(a=new URL(r instanceof Request?r.url:r,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&a!==null&&a!==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)});class es extends er{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&&(!Kt(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative 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??Ji,this._orchestrator=new fn({maxCacheSize:r.maxCacheSize??64*2**20,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:dn.network})}async _retrieveSize(){const e=new AbortController,r=await cr(this._options.fetchFn??fetch,this._url,ar(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,a;if(r.status===206)a=this._getTotalLengthFromRangeResponse(r),n=this._orchestrator.createWorker(0,Math.min(a,un));else{const s=r.headers.get("Content-Length");if(s)a=Number(s),n=this._orchestrator.createWorker(0,a),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=a,this._existingResponses.set(n,{response:r,abortController:e}),this._orchestrator.runWorker(n),a}_read(e,r){return this._orchestrator.read(e,r)}async _runWorker(e){for(;;){const r=this._existingResponses.get(e);this._existingResponses.delete(e);let n=r?.abortController,a=r?.response;if(n||(n=new AbortController,a=await cr(this._options.fetchFn??fetch,this._url,ar(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>this._disposed)),g(a),!a.ok)throw new Error(`Error fetching ${String(this._url)}: ${a.status} ${a.statusText}`);if(e.currentPos>0&&a.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(!a.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");const s=a.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){n.abort(),e.running=!1;return}let i;try{i=await s.read()}catch(l){if(this._disposed)throw l;const u=this._getRetryDelay(1,l,this._url);if(u!==null){console.error("Error while reading response stream. Attempting to resume.",l),await new Promise(d=>setTimeout(d,1e3*u));break}else throw l}if(e.aborted)break;const{done:o,value:c}=i;if(o){if(e.currentPos>=e.targetPos){this._orchestrator.forgetWorker(e),e.running=!1;return}break}this.onread?.(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}if(e.aborted)break}e.running=!1}_getTotalLengthFromRangeResponse(e){const r=e.headers.get("Content-Range");if(r){const a=/\/(\d+)/.exec(r);if(a)return Number(a[1])}const 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()}}const dn={fileSystem:(t,e)=>(t=Math.floor((t-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:t,end:e}),network:(t,e,r)=>{t=Math.max(0,Math.floor((t-65536)/65536)*65536);for(const a of r){const i=Math.max((a.startPos+a.targetPos)/2,a.targetPos-8388608);if(Ot(t,e,i,a.targetPos)){const o=a.targetPos-a.startPos,c=Math.ceil((o+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(o+1)),u=Math.min(l,c);e=Math.max(e,a.startPos+u)}}return e=Math.max(e,t+un),{start:t,end:e}}};class fn{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,r){g(this.fileSize!==null);const n=this.options.prefetchProfile(e,r,this.workers),a=Math.max(n.start,0),s=Math.min(n.end,this.fileSize);g(a<=e&&r<=s);let i=null;const o=U(this.cache,e,b=>b.start),c=o!==-1?this.cache[o]:null;c&&c.start<=e&&r<=c.end&&(c.age=this.nextAge++,i={bytes:c.bytes,view:c.view,offset:c.start});const l=U(this.cache,a,b=>b.start),u=i?null:new Uint8Array(r-e);let d=0,f=a;const h=[];if(l!==-1){for(let b=l;b<this.cache.length;b++){const y=this.cache[b];if(y.start>=s)break;if(y.end<=a)continue;const S=Math.max(a,y.start),P=Math.min(s,y.end);if(g(S<=P),f<S&&h.push({start:f,end:S}),f=P,u){const B=Math.max(e,y.start),I=Math.min(r,y.end);if(B<I){const E=B-e;u.set(y.bytes.subarray(B-y.start,I-y.start),E),E===d&&(d=I-e)}}y.age=this.nextAge++}f<s&&h.push({start:f,end:s})}else h.push({start:a,end:s});if(u&&d>=u.length&&(i={bytes:u,view:Y(u),offset:e}),h.length===0)return g(i),i;const{promise:m,resolve:p,reject:T}=Ne(),k=[];for(const b of h){const y=Math.max(e,b.start),S=Math.min(r,b.end);y===b.start&&S===b.end?k.push(b):y<S&&k.push({start:y,end:S})}for(const b of h){const y=u&&{start:e,bytes:u,holes:k,resolve:p,reject:T};let S=!1;for(const P of this.workers)if(Ot(b.start-131072,b.start,P.currentPos,P.targetPos)){P.targetPos=Math.max(P.targetPos,b.end),S=!0,y&&!P.pendingSlices.includes(y)&&P.pendingSlices.push(y),P.running||this.runWorker(P);break}if(!S){const P=this.createWorker(b.start,b.end);y&&(P.pendingSlices=[y]),this.runWorker(P)}}return i||(g(u),i=m.then(b=>({bytes:b,view:Y(b),offset:e}))),i}createWorker(e,r){const 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 a=0,s=this.workers[0];for(let i=1;i<this.workers.length;i++){const o=this.workers[i];o.age<s.age&&(a=i,s=o)}if(s.running&&s.pendingSlices.length>0)break;s.aborted=!0,this.workers.splice(a,1)}return n}runWorker(e){g(!e.running),g(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){g(!e.aborted);const n=e.currentPos,a=n+r.length;this.insertIntoCache({start:n,end:a,bytes:r,view:Y(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++){const i=e.pendingSlices[s],o=Math.max(n,i.start),c=Math.min(a,i.start+i.bytes.length);o<c&&i.bytes.set(r.subarray(o-n,c-n),o-i.start);for(let l=0;l<i.holes.length;l++){const u=i.holes[l];n<=u.start&&a>u.start&&(u.start=a),u.end<=u.start&&(i.holes.splice(l,1),l--)}i.holes.length===0&&(i.resolve(i.bytes),e.pendingSlices.splice(s,1),s--)}for(let s=0;s<this.workers.length;s++){const i=this.workers[s];e===i||i.running||Ot(n,a,i.currentPos,i.targetPos)&&(this.workers.splice(s,1),s--)}}forgetWorker(e){const r=this.workers.indexOf(e);g(r!==-1),this.workers.splice(r,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let r=U(this.cache,e.start,n=>n.start)+1;if(r>0){const n=this.cache[r-1];if(n.end>=e.end)return;if(n.end>e.start){const a=new Uint8Array(e.end-n.start);a.set(n.bytes,0),a.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=a,n.view=Y(a),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++){const a=this.cache[n];if(e.end<=a.start)break;if(e.end>=a.end){this.cache.splice(n,1),this.currentCacheSize-=a.bytes.length,n--;continue}const s=new Uint8Array(a.end-e.start);s.set(e.bytes,0),s.set(a.bytes,a.start-e.start),this.currentCacheSize-=e.end-a.start,e.bytes=s,e.view=Y(s),e.end=a.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let n=0,a=this.cache[0];for(let s=1;s<this.cache.length;s++){const i=this.cache[s];i.age<a.age&&(n=s,a=i)}if(this.currentCacheSize-a.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(n,1),this.currentCacheSize-=a.bytes.length}}dispose(){for(const e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}Mr();class ts{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 Jt)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof er))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 rs(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(const 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(),g(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}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()}}class ee extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class rs{constructor(e){this.source=e}requestSlice(e,r){if(this.source._disposed)throw new ee;if(this.fileSize!==null&&e+r>this.fileSize)return null;const n=e+r,a=this.source._read(e,n);return a instanceof Promise?a.then(s=>s?new $e(s.bytes,s.view,s.offset,e,n):null):a?new $e(a.bytes,a.view,a.offset,e,n):null}requestSliceRange(e,r,n){if(this.source._disposed)throw new ee;if(this.fileSize!==null)return this.requestSlice(e,q(this.fileSize-e,r,n));{const a=this.requestSlice(e,n),s=i=>{if(i)return i;const o=l=>(g(l!==null),this.requestSlice(e,q(l-e,r,n))),c=this.source._retrieveSize();return c instanceof Promise?c.then(o):o(c)};return a instanceof Promise?a.then(s):s(a)}}}class $e{constructor(e,r,n,a,s){this.bytes=e,this.view=r,this.offset=n,this.start=a,this.end=s,this.bufferPos=a-n}static tempFromBytes(e){return new $e(e,Y(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 $e(this.bytes,this.view,this.offset,e,e+r)}}const le=(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.`)},N=(t,e)=>{le(t,e);const r=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,r},A=t=>(le(t,1),t.view.getUint8(t.bufferPos++)),Q=t=>{le(t,2);const e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e},Xe=t=>{le(t,3);const e=Br(t.view,t.bufferPos);return t.bufferPos+=3,e},Wt=t=>{le(t,2);const e=t.view.getInt16(t.bufferPos,!1);return t.bufferPos+=2,e},x=t=>{le(t,4);const e=t.view.getUint32(t.bufferPos,!1);return t.bufferPos+=4,e},Ie=t=>{le(t,4);const e=t.view.getInt32(t.bufferPos,!1);return t.bufferPos+=4,e},J=t=>{const e=x(t),r=x(t);return e*4294967296+r},ns=t=>{const e=Ie(t),r=x(t);return e*4294967296+r},is=t=>{le(t,4);const e=t.view.getFloat32(t.bufferPos,!1);return t.bufferPos+=4,e},hn=t=>{le(t,8);const e=t.view.getFloat64(t.bufferPos,!1);return t.bufferPos+=8,e},Ue=(t,e)=>{le(t,e);let r="";for(let n=0;n<e;n++)r+=String.fromCharCode(t.bytes[t.bufferPos++]);return r};const Tr=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,ss=t=>{const e=Math.floor(t/36e5),r=Math.floor(t%(3600*1e3)/(60*1e3)),n=Math.floor(t%(60*1e3)/1e3),a=t%1e3;return e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+n.toString().padStart(2,"0")+"."+a.toString().padStart(3,"0")};class wr{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{const r=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const s of e.children)s&&this.writeBox(s);const n=this.writer.getPos(),a=e.size??n-r;this.writer.seek(r),this.writeBoxHeader(e,a),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){const r=this.offsets.get(e);g(r!==void 0);const 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(const n of e.children)n&&(r+=this.measureBox(n));return r}}}const R=new Uint8Array(8),ce=new DataView(R.buffer),V=t=>[(t%256+256)%256],_=t=>(ce.setUint16(0,t,!1),[R[0],R[1]]),mn=t=>(ce.setInt16(0,t,!1),[R[0],R[1]]),pn=t=>(ce.setUint32(0,t,!1),[R[1],R[2],R[3]]),C=t=>(ce.setUint32(0,t,!1),[R[0],R[1],R[2],R[3]]),we=t=>(ce.setInt32(0,t,!1),[R[0],R[1],R[2],R[3]]),Oe=t=>(ce.setUint32(0,Math.floor(t/2**32),!1),ce.setUint32(4,t,!1),[R[0],R[1],R[2],R[3],R[4],R[5],R[6],R[7]]),gn=t=>(ce.setInt16(0,2**8*t,!1),[R[0],R[1]]),he=t=>(ce.setInt32(0,2**16*t,!1),[R[0],R[1],R[2],R[3]]),_t=t=>(ce.setInt32(0,2**30*t,!1),[R[0],R[1],R[2],R[3]]),Et=(t,e)=>{const r=[];let n=t;do{let a=n&127;n>>=7,r.length>0&&(a|=128),r.push(a)}while(n>0||e);return r.reverse()},j=(t,e=!1)=>{const r=Array(t.length).fill(null).map((n,a)=>t.charCodeAt(a));return e&&r.push(0),r},tr=t=>{let e=null;for(const r of t)(!e||r.timestamp>e.timestamp)&&(e=r);return e},kn=t=>{const 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]},bn=kn(0),Tn=t=>[he(t[0]),he(t[1]),_t(t[2]),he(t[3]),he(t[4]),_t(t[5]),he(t[6]),he(t[7]),_t(t[8])],F=(t,e,r)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:r}),D=(t,e,r,n,a)=>F(t,[V(e),pn(r),n??[]],a),as=t=>t.isQuickTime?F("ftyp",[j("qt "),C(512),j("qt ")]):t.fragmented?F("ftyp",[j("iso5"),C(512),j("iso5"),j("iso6"),j("mp41")]):F("ftyp",[j("isom"),C(512),j("isom"),t.holdsAvc?j("avc1"):[],j("mp41")]),lt=t=>({type:"mdat",largeSize:t}),os=t=>({type:"free",size:t}),Ge=t=>F("moov",void 0,[cs(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>ls(e,t.creationTime)),t.isFragmented?Ls(t.trackDatas):null,na(t)]),cs=(t,e)=>{const r=H(Math.max(0,...e.filter(i=>i.samples.length>0).map(i=>{const o=tr(i.samples);return o.timestamp+o.duration})),Ht),n=Math.max(0,...e.map(i=>i.track.id))+1,a=!We(t)||!We(r),s=a?Oe:C;return D("mvhd",+a,0,[s(t),s(t),C(Ht),s(r),he(1),gn(1),Array(10).fill(0),Tn(bn),Array(24).fill(0),C(n)])},ls=(t,e)=>{const r=ma(t);return F("trak",void 0,[us(t,e),ds(t,e),r.name!==void 0?F("udta",void 0,[F("name",[...oe.encode(r.name)])]):null])},us=(t,e)=>{const r=tr(t.samples),n=H(r?r.timestamp+r.duration:0,Ht),a=!We(e)||!We(n),s=a?Oe:C;let i;if(t.type==="video"){const c=t.track.metadata.rotation;i=kn(c??0)}else i=bn;let o=2;return t.track.metadata.disposition?.default!==!1&&(o|=1),D("tkhd",+a,o,[s(e),s(e),C(t.track.id),C(0),s(n),Array(8).fill(0),_(0),_(t.track.id),gn(t.type==="audio"?1:0),_(0),Tn(i),he(t.type==="video"?t.info.width:0),he(t.type==="video"?t.info.height:0)])},ds=(t,e)=>F("mdia",void 0,[fs(t,e),rr(!0,hs[t.type],ms[t.type]),ps(t)]),fs=(t,e)=>{const r=tr(t.samples),n=H(r?r.timestamp+r.duration:0,t.timescale),a=!We(e)||!We(n),s=a?Oe:C;return D("mdhd",+a,0,[s(e),s(e),C(t.timescale),s(n),_(Sn(t.track.metadata.languageCode??Pe)),_(0)])},hs={video:"vide",audio:"soun",subtitle:"text"},ms={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},rr=(t,e,r,n="\0\0\0\0")=>D("hdlr",0,0,[t?j("mhlr"):C(0),j(e),j(n),C(0),C(0),j(r,!0)]),ps=t=>F("minf",void 0,[Ts[t.type](),ws(),Ss(t)]),gs=()=>D("vmhd",0,1,[_(0),_(0),_(0),_(0)]),ks=()=>D("smhd",0,0,[_(0),_(0)]),bs=()=>D("nmhd",0,0),Ts={video:gs,audio:ks,subtitle:bs},ws=()=>F("dinf",void 0,[ys()]),ys=()=>D("dref",0,0,[C(1)],[Cs()]),Cs=()=>D("url ",0,1),Ss=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(r=>r.sampleCompositionTimeOffset!==0);return F("stbl",void 0,[xs(t),Ms(t),e?Hs(t):null,e?$s(t):null,Vs(t),Us(t),Ws(t),Ns(t)])},xs=t=>{let e;if(t.type==="video")e=vs(oa(t.track.source._codec,t.info.decoderConfig.codec),t);else if(t.type==="audio"){const r=Cn(t.track.source._codec,t.muxer.isQuickTime);g(r),e=Is(r,t)}else t.type==="subtitle"&&(e=Rs(ua[t.track.source._codec],t));return g(e),D("stsd",0,0,[C(1)],[e])},vs=(t,e)=>F(t,[Array(6).fill(0),_(1),_(0),_(0),Array(12).fill(0),_(e.info.width),_(e.info.height),C(4718592),C(4718592),C(0),_(1),Array(32).fill(0),_(24),mn(65535)],[ca[e.track.source._codec](e),Un(e.info.decoderConfig.colorSpace)?Ps(e):null]),Ps=t=>F("colr",[j("nclx"),_(nt[t.info.decoderConfig.colorSpace.primaries]),_(it[t.info.decoderConfig.colorSpace.transfer]),_(st[t.info.decoderConfig.colorSpace.matrix]),V((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),_s=t=>t.info.decoderConfig&&F("avcC",[...re(t.info.decoderConfig.description)]),Es=t=>t.info.decoderConfig&&F("hvcC",[...re(t.info.decoderConfig.description)]),yr=t=>{if(!t.info.decoderConfig)return null;const e=t.info.decoderConfig,r=e.codec.split("."),n=Number(r[1]),a=Number(r[2]),s=Number(r[3]),i=r[4]?Number(r[4]):1,o=r[8]?Number(r[8]):Number(e.colorSpace?.fullRange??0),c=(s<<4)+(i<<1)+o,l=r[5]?Number(r[5]):e.colorSpace?.primaries?nt[e.colorSpace.primaries]:2,u=r[6]?Number(r[6]):e.colorSpace?.transfer?it[e.colorSpace.transfer]:2,d=r[7]?Number(r[7]):e.colorSpace?.matrix?st[e.colorSpace.matrix]:2;return D("vpcC",1,0,[V(n),V(a),V(c),V(l),V(u),V(d),_(0)])},Fs=t=>F("av1C",Yn(t.info.decoderConfig.codec)),Is=(t,e)=>{let r=0,n,a=16;if(X.includes(e.track.source._codec)){const s=e.track.source._codec,{sampleSize:i}=ze(s);a=8*i,a>16&&(r=1)}return r===0?n=[Array(6).fill(0),_(1),_(r),_(0),C(0),_(e.info.numberOfChannels),_(a),_(0),_(0),_(e.info.sampleRate<2**16?e.info.sampleRate:0),_(0)]:n=[Array(6).fill(0),_(1),_(r),_(0),C(0),_(e.info.numberOfChannels),_(Math.min(a,16)),_(0),_(0),_(e.info.sampleRate<2**16?e.info.sampleRate:0),_(0),C(1),C(a/8),C(e.info.numberOfChannels*a/8),C(2)],F(t,n,[la(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},Ft=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=[...V(e),...V(21),...pn(0),...C(0),...C(0)];if(t.info.decoderConfig.description){const n=re(t.info.decoderConfig.description);r=[...r,...V(5),...Et(n.byteLength),...n]}return r=[..._(1),...V(0),...V(4),...Et(r.length),...r,...V(6),...V(1),...V(2)],r=[...V(3),...Et(r.length),...r],D("esds",0,0,r)},ke=t=>F("wave",void 0,[As(t),Bs(t),F("\0\0\0\0")]),As=t=>F("frma",[j(Cn(t.track.source._codec,t.muxer.isQuickTime))]),Bs=t=>{const{littleEndian:e}=ze(t.track.source._codec);return F("enda",[_(+e)])},Os=t=>{let e=t.info.numberOfChannels,r=3840,n=t.info.sampleRate,a=0,s=0,i=new Uint8Array(0);const o=t.info.decoderConfig?.description;if(o){g(o.byteLength>=18);const c=re(o),l=xi(c);e=l.outputChannelCount,r=l.preSkip,n=l.inputSampleRate,a=l.outputGain,s=l.channelMappingFamily,l.channelMappingTable&&(i=l.channelMappingTable)}return F("dOps",[V(0),V(e),_(r),C(n),mn(a),V(s),...i])},zs=t=>{const e=t.info.decoderConfig?.description;g(e);const r=re(e);return D("dfLa",0,0,[...r.subarray(4)])},se=t=>{const{littleEndian:e,sampleSize:r}=ze(t.track.source._codec),n=+e;return D("pcmC",0,0,[V(n),V(8*r)])},Rs=(t,e)=>F(t,[Array(6).fill(0),_(1)],[da[e.track.source._codec](e)]),Ds=t=>F("vttC",[...oe.encode(t.info.config.description)]),Ms=t=>D("stts",0,0,[C(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[C(e.sampleCount),C(e.sampleDelta)])]),Ns=t=>{if(t.samples.every(r=>r.type==="key"))return null;const e=[...t.samples.entries()].filter(([,r])=>r.type==="key");return D("stss",0,0,[C(e.length),e.map(([r])=>C(r+1))])},Vs=t=>D("stsc",0,0,[C(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[C(e.firstChunk),C(e.samplesPerChunk),C(1)])]),Us=t=>{if(t.type==="audio"&&t.info.requiresPcmTransformation){const{sampleSize:e}=ze(t.track.source._codec);return D("stsz",0,0,[C(e*t.info.numberOfChannels),C(t.samples.reduce((r,n)=>r+H(n.duration,t.timescale),0))])}return D("stsz",0,0,[C(0),C(t.samples.length),t.samples.map(e=>C(e.size))])},Ws=t=>t.finalizedChunks.length>0&&$(t.finalizedChunks).offset>=2**32?D("co64",0,0,[C(t.finalizedChunks.length),t.finalizedChunks.map(e=>Oe(e.offset))]):D("stco",0,0,[C(t.finalizedChunks.length),t.finalizedChunks.map(e=>C(e.offset))]),Hs=t=>D("ctts",1,0,[C(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[C(e.sampleCount),we(e.sampleCompositionTimeOffset)])]),$s=t=>{let e=1/0,r=-1/0,n=1/0,a=-1/0;g(t.compositionTimeOffsetTable.length>0),g(t.samples.length>0);for(let i=0;i<t.compositionTimeOffsetTable.length;i++){const o=t.compositionTimeOffsetTable[i];e=Math.min(e,o.sampleCompositionTimeOffset),r=Math.max(r,o.sampleCompositionTimeOffset)}for(let i=0;i<t.samples.length;i++){const o=t.samples[i];n=Math.min(n,H(o.timestamp,t.timescale)),a=Math.max(a,H(o.timestamp+o.duration,t.timescale))}const s=Math.max(-e,0);return a>=2**31?null:D("cslg",0,0,[we(s),we(e),we(r),we(n),we(a)])},Ls=t=>F("mvex",void 0,t.map(qs)),qs=t=>D("trex",0,0,[C(t.track.id),C(1),C(0),C(0),C(0)]),Cr=(t,e)=>F("moof",void 0,[js(t),...e.map(Ks)]),js=t=>D("mfhd",0,0,[C(t)]),wn=t=>{let e=0,r=0;const n=0,a=0,s=t.type==="delta";return r|=+s,s?e|=1:e|=2,e<<24|r<<16|n<<8|a},Ks=t=>F("traf",void 0,[Qs(t),Xs(t),Gs(t)]),Qs=t=>{g(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const r=t.currentChunk.samples[1]??t.currentChunk.samples[0],n={duration:r.timescaleUnitsToNextSample,size:r.size,flags:wn(r)};return D("tfhd",0,e,[C(t.track.id),C(n.duration),C(n.size),C(n.flags)])},Xs=t=>(g(t.currentChunk),D("tfdt",1,0,[Oe(H(t.currentChunk.startTimestamp,t.timescale))])),Gs=t=>{g(t.currentChunk);const e=t.currentChunk.samples.map(p=>p.timescaleUnitsToNextSample),r=t.currentChunk.samples.map(p=>p.size),n=t.currentChunk.samples.map(wn),a=t.currentChunk.samples.map(p=>H(p.timestamp-p.decodeTimestamp,t.timescale)),s=new Set(e),i=new Set(r),o=new Set(n),c=new Set(a),l=o.size===2&&n[0]!==n[1],u=s.size>1,d=i.size>1,f=!l&&o.size>1,h=c.size>1||[...c].some(p=>p!==0);let m=0;return m|=1,m|=4*+l,m|=256*+u,m|=512*+d,m|=1024*+f,m|=2048*+h,D("trun",1,m,[C(t.currentChunk.samples.length),C(t.currentChunk.offset-t.currentChunk.moofOffset||0),l?C(n[0]):[],t.currentChunk.samples.map((p,T)=>[u?C(e[T]):[],d?C(r[T]):[],f?C(n[T]):[],h?we(a[T]):[]])])},Ys=t=>F("mfra",void 0,[...t.map(Zs),Js()]),Zs=(t,e)=>D("tfra",1,0,[C(t.track.id),C(63),C(t.finalizedChunks.length),t.finalizedChunks.map(n=>[Oe(H(n.samples[0].timestamp,t.timescale)),Oe(n.moofOffset),C(e+1),C(1),C(1)])]),Js=()=>D("mfro",0,0,[C(0)]),ea=()=>F("vtte"),ta=(t,e,r,n,a)=>F("vttc",void 0,[a!==null?F("vsid",[we(a)]):null,r!==null?F("iden",[...oe.encode(r)]):null,e!==null?F("ctim",[...oe.encode(ss(e))]):null,n!==null?F("sttg",[...oe.encode(n)]):null,F("payl",[...oe.encode(t)])]),ra=t=>F("vtta",[...oe.encode(t)]),na=t=>{const e=[],r=t.format._options.metadataFormat??"auto",n=t.output._metadataTags;if(r==="mdir"||r==="auto"&&!t.isQuickTime){const a=sa(n);a&&e.push(a)}else if(r==="mdta"){const a=aa(n);a&&e.push(a)}else(r==="udta"||r==="auto"&&t.isQuickTime)&&ia(e,t.output._metadataTags);return e.length===0?null:F("udta",void 0,e)},ia=(t,e)=>{for(const{key:r,value:n}of Dr(e))switch(r){case"title":t.push(ae("©nam",n));break;case"description":t.push(ae("©des",n));break;case"artist":t.push(ae("©ART",n));break;case"album":t.push(ae("©alb",n));break;case"albumArtist":t.push(ae("albr",n));break;case"genre":t.push(ae("©gen",n));break;case"date":t.push(ae("©day",n.toISOString().slice(0,10)));break;case"comment":t.push(ae("©cmt",n));break;case"lyrics":t.push(ae("©lyr",n));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:at(r)}if(e.raw)for(const r in e.raw){const n=e.raw[r];n==null||r.length!==4||t.some(a=>a.type===r)||(typeof n=="string"?t.push(ae(r,n)):n instanceof Uint8Array&&t.push(F(r,Array.from(n))))}},ae=(t,e)=>{const r=oe.encode(e);return F(t,[_(r.length),_(Sn("und")),Array.from(r)])},Sr={"image/jpeg":13,"image/png":14,"image/bmp":27},yn=(t,e)=>{const r=[];for(const{key:n,value:a}of Dr(t))switch(n){case"title":r.push({key:e?"title":"©nam",value:Z(a)});break;case"description":r.push({key:e?"description":"©des",value:Z(a)});break;case"artist":r.push({key:e?"artist":"©ART",value:Z(a)});break;case"album":r.push({key:e?"album":"©alb",value:Z(a)});break;case"albumArtist":r.push({key:e?"album_artist":"aART",value:Z(a)});break;case"comment":r.push({key:e?"comment":"©cmt",value:Z(a)});break;case"genre":r.push({key:e?"genre":"©gen",value:Z(a)});break;case"lyrics":r.push({key:e?"lyrics":"©lyr",value:Z(a)});break;case"date":r.push({key:e?"date":"©day",value:Z(a.toISOString().slice(0,10))});break;case"images":for(const s of a)s.kind==="coverFront"&&r.push({key:"covr",value:F("data",[C(Sr[s.mimeType]??0),C(0),Array.from(s.data)])});break;case"trackNumber":if(e){const s=t.tracksTotal!==void 0?`${a}/${t.tracksTotal}`:a.toString();r.push({key:"track",value:Z(s)})}else r.push({key:"trkn",value:F("data",[C(0),C(0),_(0),_(a),_(t.tracksTotal??0),_(0)])});break;case"discNumber":e||r.push({key:"disc",value:F("data",[C(0),C(0),_(0),_(a),_(t.discsTotal??0),_(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:at(n)}if(t.raw)for(const n in t.raw){const a=t.raw[n];a==null||!e&&n.length!==4||r.some(s=>s.key===n)||(typeof a=="string"?r.push({key:n,value:Z(a)}):a instanceof Uint8Array?r.push({key:n,value:F("data",[C(0),C(0),Array.from(a)])}):a instanceof Ve&&r.push({key:n,value:F("data",[C(Sr[a.mimeType]??0),C(0),Array.from(a.data)])}))}return r},sa=t=>{const e=yn(t,!1);return e.length===0?null:D("meta",0,0,void 0,[rr(!1,"mdir","","appl"),F("ilst",void 0,e.map(r=>F(r.key,void 0,[r.value])))])},aa=t=>{const e=yn(t,!0);return e.length===0?null:F("meta",void 0,[rr(!1,"mdta",""),D("keys",0,0,[C(e.length)],e.map(r=>F("mdta",[...oe.encode(r.key)]))),F("ilst",void 0,e.map((r,n)=>{const a=String.fromCharCode(...C(n+1));return F(a,void 0,[r.value])}))])},Z=t=>F("data",[C(1),C(0),...oe.encode(t)]),oa=(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"}},ca={avc:_s,hevc:Es,vp8:yr,vp9:yr,av1:Fs},Cn=(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"}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"}},la=(t,e)=>{switch(t){case"aac":return Ft;case"mp3":return Ft;case"opus":return Os;case"vorbis":return Ft;case"flac":return zs}if(e)switch(t){case"pcm-s24":return ke;case"pcm-s24be":return ke;case"pcm-s32":return ke;case"pcm-s32be":return ke;case"pcm-f32":return ke;case"pcm-f32be":return ke;case"pcm-f64":return ke;case"pcm-f64be":return ke}else switch(t){case"pcm-s16":return se;case"pcm-s16be":return se;case"pcm-s24":return se;case"pcm-s24be":return se;case"pcm-s32":return se;case"pcm-s32be":return se;case"pcm-f32":return se;case"pcm-f32be":return se;case"pcm-f64":return se;case"pcm-f64be":return se}return null},ua={webvtt:"wvtt"},da={webvtt:Ds},Sn=t=>{g(t.length===3);let e=0;for(let r=0;r<3;r++)e<<=5,e+=t.charCodeAt(r)-96;return e};class fa{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}const n=r+e.byteLength-this.trackedStart;let a=this.trackedWrites.byteLength;for(;a<n;)a*=2;if(a!==this.trackedWrites.byteLength){const s=new Uint8Array(a);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.");const r={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,r}}const It=2**16,At=2**32;class xn extends fa{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(It,{maxByteLength:At})}catch{this.buffer=new ArrayBuffer(It),this.supportsResize=!1}else this.buffer=new ArrayBuffer(It);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>At)throw new Error(`ArrayBuffer exceeded maximum size of ${At} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(r);else{const n=new ArrayBuffer(r),a=new Uint8Array(n);a.set(this.bytes,0),this.buffer=n,this.bytes=a}}}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)}}class vn{constructor(){this._output=null,this.onwrite=null}}class Pn extends vn{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new xn(this)}}const Ht=1e3,ha=2082844800,ma=t=>{const e={},r=t.track;return r.metadata.name!==void 0&&(e.name=r.metadata.name),e},H=(t,e,r=!0)=>{const n=t*e;return r?Math.round(n):n};class pa extends di{constructor(e,r){super(e),this.auxTarget=new Pn,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new wr(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Ne(),this.creationTime=Math.floor(Date.now()/1e3)+ha,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=r,this.writer=e._writer,this.boxWriter=new wr(this.writer),this.isQuickTime=r instanceof In;const n=this.writer instanceof xn?"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(){const 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(as({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented})),this.format._options.onFtyp){const{data:n,start:a}=this.writer.stopTrackingWrites();this.format._options.onFtyp(n,a)}if(this.ftypSize=this.writer.getPos(),this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(const 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=lt(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(const 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;const e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return en({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){const a=this.trackDatas.find(l=>l.track===e);if(a)return a;oi(n),g(n),g(n.decoderConfig);const s={...n.decoderConfig};g(s.codedWidth!==void 0),g(s.codedHeight!==void 0);let i=!1;if(e.source._codec==="avc"&&!s.description){const l=Qr(r.data);if(!l)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=mi(l),i=!0}else if(e.source._codec==="hevc"&&!s.description){const l=Xr(r.data);if(!l)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=Si(l),i=!0}const o=Ln(1/(e.metadata.frameRate??57600),1e6).denominator,c={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,decoderConfig:s,requiresAnnexBTransformation:i},timescale:o,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}getAudioTrackData(e,r){const n=this.trackDatas.find(s=>s.track===e);if(n)return n;li(r),g(r),g(r.decoderConfig);const a={muxer:this,track:e,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:r.decoderConfig,requiresPcmTransformation:!this.isFragmented&&X.includes(e.source._codec)},timescale:r.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(a),this.trackDatas.sort((s,i)=>s.track.id-i.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getSubtitleTrackData(e,r){const n=this.trackDatas.find(s=>s.track===e);if(n)return n;ui(r),g(r),g(r.config);const a={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(a),this.trackDatas.sort((s,i)=>s.track.id-i.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,r,n){const a=await this.mutex.acquire();try{const s=this.getVideoTrackData(e,r,n);let i=r.data;if(s.info.requiresAnnexBTransformation){const l=fi(i);if(!l)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.");i=l}const o=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),c=this.createSampleForTrack(s,i,o,r.duration,r.type);await this.registerSample(s,c)}finally{a()}}async addEncodedAudioPacket(e,r,n){const a=await this.mutex.acquire();try{const s=this.getAudioTrackData(e,n),i=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),o=this.createSampleForTrack(s,r.data,i,r.duration,r.type);s.info.requiresPcmTransformation&&await this.maybePadWithSilence(s,i),await this.registerSample(s,o)}finally{a()}}async maybePadWithSilence(e,r){const n=$(e.samples),a=n?n.timestamp+n.duration:0,s=r-a,i=H(s,e.timescale);if(i>0){const{sampleSize:o,silentValue:c}=ze(e.info.decoderConfig.codec),l=i*e.info.numberOfChannels,u=new Uint8Array(o*l).fill(c),d=this.createSampleForTrack(e,new Uint8Array(u.buffer),a,s,"key");await this.registerSample(e,d)}}async addSubtitleCue(e,r,n){const a=await this.mutex.acquire();try{const 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{a()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){const n=new Set([]);for(const l of e.cueQueue)g(l.timestamp<=r),g(e.lastCueEndTimestamp<=l.timestamp+l.duration),n.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),n.add(l.timestamp+l.duration);const a=[...n].sort((l,u)=>l-u),s=a[0],i=a[1]??s;if(r<i)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);const l=ea();this.auxBoxWriter.writeBox(l);const u=this.auxWriter.getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,u,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let l=0;l<e.cueQueue.length;l++){const u=e.cueQueue[l];if(u.timestamp>=i)break;Tr.lastIndex=0;const d=Tr.test(u.text),f=u.timestamp+u.duration;let h=e.cueToSourceId.get(u);if(h===void 0&&i<f&&(h=e.nextSourceId++,e.cueToSourceId.set(u,h)),u.notes){const p=ra(u.notes);this.auxBoxWriter.writeBox(p)}const m=ta(u.text,d?s:null,u.identifier??null,u.settings??null,h??null);this.auxBoxWriter.writeBox(m),f===i&&e.cueQueue.splice(l--,1)}const o=this.auxWriter.getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,o,s,i-s,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=i}}createSampleForTrack(e,r,n,a,s){return{timestamp:n,decodeTimestamp:n,duration:a,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:H(a,e.timescale)}}processTimestamps(e,r){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){let a=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){const i=e.timestampProcessingQueue[s],o=H(i.duration,e.timescale);a+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:a,sampleDelta:1});else{const s=$(e.timeToSampleTable);s.sampleCount+=a}e.timestampProcessingQueue.length=0;return}const n=e.timestampProcessingQueue.map(a=>a.timestamp).sort((a,s)=>a-s);for(let a=0;a<e.timestampProcessingQueue.length;a++){const s=e.timestampProcessingQueue[a];s.decodeTimestamp=n[a],!this.isFragmented&&e.lastTimescaleUnits===null&&(s.decodeTimestamp=0);const i=H(s.timestamp-s.decodeTimestamp,e.timescale),o=H(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){g(e.lastSample);const c=H(s.decodeTimestamp,e.timescale,!1),l=Math.round(c-e.lastTimescaleUnits);if(g(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let u=$(e.timeToSampleTable);if(g(u),u.sampleCount===1){u.sampleDelta=l;const f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===l&&(f.sampleCount++,e.timeToSampleTable.pop(),u=f)}else u.sampleDelta!==l&&(u.sampleCount--,e.timeToSampleTable.push(u={sampleCount:1,sampleDelta:l}));u.sampleDelta===o?u.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const d=$(e.compositionTimeOffsetTable);g(d),d.sampleCompositionTimeOffset===i?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=H(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,g(e.lastSample),g(e.lastTimescaleUnits!==null),r!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){g(r.type==="key");const a=H(r.timestamp,e.timescale,!1),s=Math.round(a-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")){const a=e.track.metadata.maximumPacketCount;if(g(a!==void 0),e.samples.length>a)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${a}). 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);const a=r.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const s=this.trackDatas.every(i=>{if(e===i)return r.type==="key";const o=i.sampleQueue[0];return o?o.type==="key":i.track.source._closed});a>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=a>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}),g(e.currentChunk),e.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(e){if(g(!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,a)=>n+H(a.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||$(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(const n of e.currentChunk.samples)g(n.data),this.writer.write(n.data),n.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(g(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let r=null,n=1/0;for(const 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;const a=r.sampleQueue.shift();await this.addSampleToTrack(r,a)}}async finalizeFragment(e=!0){g(this.isFragmented);const r=this.nextFragmentNumber++;if(r===1){this.format._options.onMoov&&this.writer.startTrackingWrites();const h=Ge(this);if(this.boxWriter.writeBox(h),this.format._options.onMoov){const{data:m,start:p}=this.writer.stopTrackingWrites();this.format._options.onMoov(m,p)}}const n=this.trackDatas.filter(h=>h.currentChunk),a=Cr(r,n),s=this.writer.getPos(),i=s+this.boxWriter.measureBox(a);let o=i+me,c=1/0;for(const h of n){h.currentChunk.offset=o,h.currentChunk.moofOffset=s;for(const m of h.currentChunk.samples)o+=m.size;c=Math.min(c,h.currentChunk.startTimestamp)}const l=o-i,u=l>=2**32;if(u)for(const h of n)h.currentChunk.offset+=Fe-me;this.format._options.onMoof&&this.writer.startTrackingWrites();const d=Cr(r,n);if(this.boxWriter.writeBox(d),this.format._options.onMoof){const{data:h,start:m}=this.writer.stopTrackingWrites();this.format._options.onMoof(h,m,c)}g(this.writer.getPos()===i),this.format._options.onMdat&&this.writer.startTrackingWrites();const f=lt(u);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(i+(u?Fe:me));for(const h of n)for(const m of h.currentChunk.samples)this.writer.write(m.data),m.data=null;if(this.format._options.onMdat){const{data:h,start:m}=this.writer.stopTrackingWrites();this.format._options.onMdat(h,m)}for(const h of n)h.finalizedChunks.push(h.currentChunk),this.finalizedChunks.push(h.currentChunk),h.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,r){if(this.allTracksAreKnown()){if(!this.mdat){const n=Ge(this),s=this.boxWriter.measureBox(n)+this.computeSampleTableSizeUpperBound()+4096;g(this.ftypSize!==null),this.writer.seek(this.ftypSize+s),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=lt(!0),this.boxWriter.writeBox(this.mdat);for(const i of this.trackDatas){for(const o of i.sampleQueue)await this.addSampleToTrack(i,o);i.sampleQueue.length=0}}await this.addSampleToTrack(e,r)}else e.sampleQueue.push(r)}computeSampleTableSizeUpperBound(){g(this.fastStart==="reserve");let e=0;for(const r of this.trackDatas){const n=r.track.metadata.maximumPacketCount;g(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){const r=await this.mutex.acquire();if(e.type==="subtitle"&&e.source._codec==="webvtt"){const n=this.trackDatas.find(a=>a.track===e);n&&await this.processWebVTTCues(n,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),r()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(const r of this.trackDatas)this.processTimestamps(r);await this.finalizeFragment(!1)}else for(const r of this.trackDatas)this.processTimestamps(r),await this.finalizeCurrentChunk(r);if(this.fastStart==="in-memory"){this.mdat=lt(!1);let r;for(let a=0;a<2;a++){const s=Ge(this),i=this.boxWriter.measureBox(s);r=this.boxWriter.measureBox(this.mdat);let o=this.writer.getPos()+i+r;for(const c of this.finalizedChunks){c.offset=o;for(const{data:l}of c.samples)g(l),o+=l.byteLength,r+=l.byteLength}if(o<2**32)break;r>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const n=Ge(this);if(this.boxWriter.writeBox(n),this.format._options.onMoov){const{data:a,start:s}=this.writer.stopTrackingWrites();this.format._options.onMoov(a,s)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(const a of this.finalizedChunks)for(const s of a.samples)g(s.data),this.writer.write(s.data),s.data=null;if(this.format._options.onMdat){const{data:a,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(a,s)}}else if(this.isFragmented){const r=this.writer.getPos(),n=Ys(this.trackDatas);this.boxWriter.writeBox(n);const a=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(a)}else{g(this.mdat);const r=this.boxWriter.offsets.get(this.mdat);g(r!==void 0);const 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){const{data:s,start:i}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,i)}const a=Ge(this);if(this.fastStart==="reserve"){g(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(a);const s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(os(s))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(a);if(this.format._options.onMoov){const{data:s,start:i}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,i)}}e()}}class _n{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Se.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Be.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>ft.includes(e))}_codecUnsupportedHint(e){return""}}class En extends _n{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:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:2**32-1}}}get supportsVideoRotationMetadata(){return!0}_createMuxer(e){return new pa(e,this)}}class Fn extends En{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Se,...Ur,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ft]}_codecUnsupportedHint(e){return new In().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class In extends En{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Se,...Be]}_codecUnsupportedHint(e){return new Fn().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}const ga=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!Se.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${Se.join(", ")}.`);if(!(t.bitrate instanceof Re)&&(!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.");An(t.codec,t)},An=(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&&jr(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.")},$t=t=>{const e=t.bitrate instanceof Re?t.bitrate._toVideoBitrate(t.codec,t.width,t.height):t.bitrate;return{codec:t.fullCodecString??Gn(t.codec,t.width,t.height,e),width:t.width,height:t.height,bitrate:e,bitrateMode:t.bitrateMode,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...ei(t.codec)}},ka=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!Be.includes(t.codec))throw new TypeError(`Invalid audio codec '${t.codec}'. Must be one of: ${Be.join(", ")}.`);if(t.bitrate===void 0&&(!X.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 Re)&&(!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.");Bn(t.codec,t)},Bn=(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&&jr(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`)},Lt=t=>{const e=t.bitrate instanceof Re?t.bitrate._toAudioBitrate(t.codec):t.bitrate;return{codec:t.fullCodecString??Zn(t.codec,t.numberOfChannels,t.sampleRate),numberOfChannels:t.numberOfChannels,sampleRate:t.sampleRate,bitrate:e,bitrateMode:t.bitrateMode,...ti(t.codec)}};class Re{constructor(e){this._factor=e}_toVideoBitrate(e,r,n){const a=r*n,s={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},i=1920*1080,o=3e6,c=Math.pow(a/i,.95),d=o*c*s[e]*this._factor;return Math.ceil(d/1e3)*1e3}_toAudioBitrate(e){if(X.includes(e)||e==="flac")return;const n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[e];if(!n)throw new Error(`Unhandled codec: ${e}`);let a=n*this._factor;return e==="aac"?a=[96e3,128e3,16e4,192e3].reduce((i,o)=>Math.abs(o-a)<Math.abs(i-a)?o:i):e==="opus"||e==="vorbis"?a=Math.max(6e3,a):e==="mp3"&&(a=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((i,o)=>Math.abs(o-a)<Math.abs(i-a)?o:i)),Math.round(a/1e3)*1e3}}const On=new Re(2),ba=async(t,e={})=>{const{width:r=1280,height:n=720,bitrate:a=1e6,...s}=e;if(!Se.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(!(a instanceof Re)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer or a quality.");An(t,s);let i=null;return Dt.length>0&&(i??=$t({codec:t,width:r,height:n,bitrate:a,framerate:void 0,...s}),Dt.some(l=>l.supports(t,i)))?!0:typeof VideoEncoder>"u"||(r%2===1||n%2===1)&&(t==="avc"||t==="hevc")||(i??=$t({codec:t,width:r,height:n,bitrate:a,framerate:void 0,...s,alpha:"discard"}),!(await VideoEncoder.isConfigSupported(i)).supported)?!1:dt()?new Promise(async l=>{try{const u=new VideoEncoder({output:()=>{},error:()=>l(!1)});u.configure(i);const d=new Uint8Array(r*n*4),f=new VideoFrame(d,{format:"RGBA",codedWidth:r,codedHeight:n,timestamp:0});u.encode(f),f.close(),await u.flush(),l(!0)}catch{l(!1)}}):!0},Ta=async(t,e={})=>{const{numberOfChannels:r=2,sampleRate:n=48e3,bitrate:a=128e3,...s}=e;if(!Be.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(!(a instanceof Re)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer.");Bn(t,s);let i=null;return Mt.length>0&&(i??=Lt({codec:t,numberOfChannels:r,sampleRate:n,bitrate:a,...s}),Mt.some(c=>c.supports(t,i)))||X.includes(t)?!0:typeof AudioEncoder>"u"?!1:(i??=Lt({codec:t,numberOfChannels:r,sampleRate:n,bitrate:a,...s}),(await AudioEncoder.isConfigSupported(i)).supported===!0)},wa=async(t,e)=>{for(const r of t)if(await ba(r,e))return r;return null},ya=async(t,e)=>{for(const r of t)if(await Ta(r,e))return r;return null};class nr{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;const 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?this._closingPromise:this._flushAndClose(e)}}class zn extends nr{constructor(e){if(super(),this._connectedTrack=null,!Se.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${Se.join(", ")}.`);this._codec=e}}class Ca{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 Rr,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorNeedsNewStack=!0}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){const o=this.encodingConfig.sizeChangeBehavior??"deny";if(o!=="passThrough"){if(o==="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 c=!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),c=!0);const l=this.resizeCanvas.getContext("2d",{alpha:dt()});g(l),c||(dt()?(l.fillStyle="black",l.fillRect(0,0,this.codedWidth,this.codedHeight)):l.clearRect(0,0,this.codedWidth,this.codedHeight)),e.drawWithFit(l,{fit:o}),r&&e.close(),e=new _e(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),g(this.encoderInitialized);const a=this.encodingConfig.keyFrameInterval??5,s=Math.floor(e.timestamp/a),i={...n,keyFrame:n?.keyFrame||a===0||s!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=s,this.customEncoder){this.customEncoderQueueSize++;const o=e.clone(),c=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(o,i)).then(()=>this.customEncoderQueueSize--).catch(l=>this.error??=l).finally(()=>{o.close()});this.customEncoderQueueSize>=4&&await c}else{g(this.encoder);const o=e.toVideoFrame();if(!this.alphaEncoder)this.encoder.encode(o,i),o.close();else if(!!o.format&&!o.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(o,i),o.close();else{const l=o.displayWidth,u=o.displayHeight;if(!this.splitter)try{this.splitter=new Sa(l,u)}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(o,i),o.close()}if(this.splitter){const d=this.splitter.extractColor(o),f=this.splitter.extractAlpha(o);this.alphaFrameQueue.push(f),this.encoder.encode(d,i),d.close(),o.close()}}r&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(c=>this.encoder.addEventListener("dequeue",c,{once:!0}))}await this.muxer.mutex.currentPromise}finally{r&&e.close()}}ensureEncoder(e){const r=new Error;this.ensureEncoderPromise=(async()=>{const n=$t({width:e.codedWidth,height:e.codedHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(n);const a=Dt.find(s=>s.supports(this.encodingConfig.codec,n));if(a)this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(s,i)=>{if(!(s instanceof L))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(i!==void 0&&(!i||typeof i!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(s,i),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,s,i).catch(o=>{this.error??=o,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(n.alpha="discard",this.encodingConfig.alpha==="keep"&&(n.latencyMode="quality"),(n.width%2===1||n.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${n.width}x${n.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(n)).supported)throw new Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.width}x${n.height}, hardware acceleration: ${n.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);const o=[],c=[];let l=0,u=0;const d=(f,h,m)=>{const p={};if(h){const k=new Uint8Array(h.byteLength);h.copyTo(k),p.alpha=k}const T=L.fromEncodedChunk(f,p);this.encodingConfig.onEncodedPacket?.(T,m),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,T,m).catch(k=>{this.error??=k,this.errorNeedsNewStack=!1})};this.encoder=new VideoEncoder({output:(f,h)=>{if(!this.alphaEncoder){d(f,null,h);return}const m=this.alphaFrameQueue.shift();g(m!==void 0),m?(this.alphaEncoder.encode(m,{keyFrame:f.type==="key"}),u++,m.close(),o.push({chunk:f,meta:h})):u===0?d(f,null,h):(c.push(l+u),o.push({chunk:f,meta:h}))},error:f=>{f.stack=r.stack,this.error??=f}}),this.encoder.configure(n),this.encodingConfig.alpha==="keep"&&(this.alphaEncoder=new VideoEncoder({output:(f,h)=>{u--;const m=o.shift();for(g(m!==void 0),d(m.chunk,f,m.meta),l++;c.length>0&&c[0]===l;){c.shift();const p=o.shift();g(p!==void 0),d(p.chunk,null,p.meta)}},error:f=>{f.stack=r.stack,this.error??=f}}),this.alphaEncoder.configure(n))}g(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.errorNeedsNewStack&&(this.error.stack=new Error().stack),this.error}}class Sa{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);const 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
2
- in vec2 a_position;
3
- in vec2 a_texCoord;
4
- out vec2 v_texCoord;
5
-
6
- void main() {
7
- gl_Position = vec4(a_position, 0.0, 1.0);
8
- v_texCoord = a_texCoord;
9
- }
10
- `)}createColorProgram(){const e=this.createVertexShader(),r=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
11
- precision highp float;
12
-
13
- uniform sampler2D u_sourceTexture;
14
- in vec2 v_texCoord;
15
- out vec4 fragColor;
16
-
17
- void main() {
18
- vec4 source = texture(u_sourceTexture, v_texCoord);
19
- fragColor = vec4(source.rgb, 1.0);
20
- }
21
- `),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,r),this.gl.linkProgram(n),n}createAlphaProgram(){const e=this.createVertexShader(),r=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
22
- precision highp float;
23
-
24
- uniform sampler2D u_sourceTexture;
25
- uniform vec2 u_resolution; // The width and height of the canvas
26
- in vec2 v_texCoord;
27
- out vec4 fragColor;
28
-
29
- // This function determines the value for a single byte in the YUV stream
30
- float getByteValue(float byteOffset) {
31
- float width = u_resolution.x;
32
- float height = u_resolution.y;
33
-
34
- float yPlaneSize = width * height;
35
-
36
- if (byteOffset < yPlaneSize) {
37
- // This byte is in the luma plane. Find the corresponding pixel coordinates to sample from
38
- float y = floor(byteOffset / width);
39
- float x = mod(byteOffset, width);
40
-
41
- // Add 0.5 to sample the center of the texel
42
- vec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution;
43
-
44
- // The luma value is the alpha from the source texture
45
- return texture(u_sourceTexture, sampleCoord).a;
46
- } else {
47
- // Write a fixed value for chroma and beyond
48
- return 128.0 / 255.0;
49
- }
50
- }
51
-
52
- void main() {
53
- // Each fragment writes 4 bytes (R, G, B, A)
54
- float pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x);
55
- float baseByteOffset = pixelIndex * 4.0;
56
-
57
- vec4 result;
58
- for (int i = 0; i < 4; i++) {
59
- float currentByteOffset = baseByteOffset + float(i);
60
- result[i] = getByteValue(currentByteOffset);
61
- }
62
-
63
- fragColor = result;
64
- }
65
- `),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,r),this.gl.linkProgram(n),n}createShader(e,r){const n=this.gl.createShader(e);return this.gl.shaderSource(n,r),this.gl.compileShader(n),this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)||console.error("Shader compile error:",this.gl.getShaderInfoLog(n)),n}createVAO(){const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const 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);const a=this.gl.getAttribLocation(this.colorProgram,"a_position"),s=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){const 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}updateTexture(e){this.lastFrame!==e&&((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.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.lastFrame=e)}extractColor(e){return this.updateTexture(e),this.gl.useProgram(this.colorProgram),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),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:"discard"})}extractAlpha(e){this.updateTexture(e),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),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);const{width:r,height:n}=this.canvas,a=Math.ceil(r/2)*Math.ceil(n/2),s=r*n+a*2,i=Math.ceil(s/(r*4));let o=new Uint8Array(4*r*i);this.gl.readPixels(0,0,r,i,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),o=o.subarray(0,s),g(o[r*n]===128),g(o[o.length-1]===128);const c={format:"I420",codedWidth:r,codedHeight:n,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,c)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class xa extends zn{constructor(e,r){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");ga(r),super(r.codec),this._encoder=new Ca(this,r),this._canvas=e}add(e,r=0,n){if(!Number.isFinite(e)||e<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");const a=new _e(this._canvas,{timestamp:e,duration:r});return this._encoder.add(a,!0,n)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Rn extends nr{constructor(e){if(super(),this._connectedTrack=null,!Be.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Be.join(", ")}.`);this._codec=e}}class va{constructor(e,r){this.source=e,this.encodingConfig=r,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new Rr,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.error=null,this.errorNeedsNewStack=!0}async add(e,r){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),g(this.encoderInitialized);{const n=Math.round(e.timestamp*e.sampleRate),a=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=a;else{const s=n-this.lastEndSampleIndex;if(s>=64){const i=new Ee({data:new Float32Array(s*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:s,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.add(i,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.customEncoder){this.customEncoderQueueSize++;const n=e.clone(),a=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(n)).then(()=>this.customEncoderQueueSize--).catch(s=>this.error??=s).finally(()=>{n.close()});this.customEncoderQueueSize>=4&&await a,await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,r);else{g(this.encoder);const n=e.toAudioData();this.encoder.encode(n),n.close(),r&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(a=>this.encoder.addEventListener("dequeue",a,{once:!0})),await this.muxer.mutex.currentPromise}}finally{r&&e.close()}}async doPcmEncoding(e,r){g(this.outputSampleSize),g(this.writeOutputValue);const{numberOfChannels:n,numberOfFrames:a,sampleRate:s,timestamp:i}=e,o=2048,c=[];for(let f=0;f<a;f+=o){const h=Math.min(o,e.numberOfFrames-f),m=h*n*this.outputSampleSize,p=new ArrayBuffer(m),T=new DataView(p);c.push({frameCount:h,view:T})}const l=e.allocationSize({planeIndex:0,format:"f32-planar"}),u=new Float32Array(l/Float32Array.BYTES_PER_ELEMENT);for(let f=0;f<n;f++){e.copyTo(u,{planeIndex:f,format:"f32-planar"});for(let h=0;h<c.length;h++){const{frameCount:m,view:p}=c[h];for(let T=0;T<m;T++)this.writeOutputValue(p,(T*n+f)*this.outputSampleSize,u[h*o+T])}}r&&e.close();const d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:n,sampleRate:s}};for(let f=0;f<c.length;f++){const{frameCount:h,view:m}=c[f],p=m.buffer,T=f*o,k=new L(new Uint8Array(p),"key",i+T/s,h/s);this.encodingConfig.onEncodedPacket?.(k,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,k,d)}}ensureEncoder(e){const r=new Error;this.ensureEncoderPromise=(async()=>{const{numberOfChannels:n,sampleRate:a}=e,s=Lt({numberOfChannels:n,sampleRate:a,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(s);const i=Mt.find(o=>o.supports(this.encodingConfig.codec,s));if(i)this.customEncoder=new i,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=s,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof L))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(o,c),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,o,c).catch(l=>{this.error??=l,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else if(X.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(s)).supported)throw new Error(`This specific encoder configuration (${s.codec}, ${s.bitrate} bps, ${s.numberOfChannels} channels, ${s.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);this.encoder=new AudioEncoder({output:(c,l)=>{if(this.encodingConfig.codec==="aac"&&l?.decoderConfig){let d=!1;if(!l.decoderConfig.description||l.decoderConfig.description.byteLength<2?d=!0:d=Qt(re(l.decoderConfig.description)).objectType===0,d){const f=Number($(s.codec.split(".")));l.decoderConfig.description=Jn({objectType:f,numberOfChannels:l.decoderConfig.numberOfChannels,sampleRate:l.decoderConfig.sampleRate})}}const u=L.fromEncodedChunk(c);this.encodingConfig.onEncodedPacket?.(u,l),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,u,l).catch(d=>{this.error??=d,this.errorNeedsNewStack=!1})},error:c=>{c.stack=r.stack,this.error??=c}}),this.encoder.configure(s)}g(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;const e=this.encodingConfig.codec,{dataType:r,sampleSize:n,littleEndian:a}=ze(e);switch(this.outputSampleSize=n,n){case 1:r==="unsigned"?this.writeOutputValue=(s,i,o)=>s.setUint8(i,q((o+1)*127.5,0,255)):r==="signed"?this.writeOutputValue=(s,i,o)=>{s.setInt8(i,q(Math.round(o*128),-128,127))}:r==="ulaw"?this.writeOutputValue=(s,i,o)=>{const c=q(Math.floor(o*32767),-32768,32767);s.setUint8(i,Ei(c))}:r==="alaw"?this.writeOutputValue=(s,i,o)=>{const c=q(Math.floor(o*32767),-32768,32767);s.setUint8(i,Fi(c))}:g(!1);break;case 2:r==="unsigned"?this.writeOutputValue=(s,i,o)=>s.setUint16(i,q((o+1)*32767.5,0,65535),a):r==="signed"?this.writeOutputValue=(s,i,o)=>s.setInt16(i,q(Math.round(o*32767),-32768,32767),a):g(!1);break;case 3:r==="unsigned"?this.writeOutputValue=(s,i,o)=>Or(s,i,q((o+1)*83886075e-1,0,16777215),a):r==="signed"?this.writeOutputValue=(s,i,o)=>Wn(s,i,q(Math.round(o*8388607),-8388608,8388607),a):g(!1);break;case 4:r==="unsigned"?this.writeOutputValue=(s,i,o)=>s.setUint32(i,q((o+1)*21474836475e-1,0,4294967295),a):r==="signed"?this.writeOutputValue=(s,i,o)=>s.setInt32(i,q(Math.round(o*2147483647),-2147483648,2147483647),a):r==="float"?this.writeOutputValue=(s,i,o)=>s.setFloat32(i,o,a):g(!1);break;case 8:r==="float"?this.writeOutputValue=(s,i,o)=>s.setFloat64(i,o,a):g(!1);break;default:at(n),g(!1)}}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(),this.encoder.state!=="closed"&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.errorNeedsNewStack&&(this.error.stack=new Error().stack),this.error}}class Pa extends Rn{constructor(e){ka(e),super(e.codec),this._accumulatedTime=0,this._encoder=new va(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=Ee._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(const n of r)await this._encoder.add(n,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class _a extends nr{constructor(e){if(super(),this._connectedTrack=null,!ft.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${ft.join(", ")}.`);this._codec=e}}const Ea=["video","audio","subtitle"],Bt=t=>{if(!t||typeof t!="object")throw new TypeError("metadata must be an object.");if(t.languageCode!==void 0&&!jt(t.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(t.name!==void 0&&typeof t.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(t.disposition!==void 0&&Xn(t.disposition),t.maximumPacketCount!==void 0&&(!Number.isInteger(t.maximumPacketCount)||t.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.")};class Fa{constructor(e){if(this.state="pending",this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Fr,this._metadataTags={},!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof _n))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof vn))throw new TypeError("options.target must be a Target.");if(e.target._output)throw new Error("Target is already used for another output.");e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,r={}){if(!(e instanceof zn))throw new TypeError("source must be a VideoSource.");if(Bt(r),r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError(`Invalid video rotation: ${r.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&r.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(r.frameRate!==void 0&&(!Number.isFinite(r.frameRate)||r.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${r.frameRate}. Must be a positive number.`);this._addTrack("video",e,r)}addAudioTrack(e,r={}){if(!(e instanceof Rn))throw new TypeError("source must be an AudioSource.");Bt(r),this._addTrack("audio",e,r)}addSubtitleTrack(e,r={}){if(!(e instanceof _a))throw new TypeError("source must be a SubtitleSource.");Bt(r),this._addTrack("subtitle",e,r)}setMetadataTags(e){if(Qn(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e,r,n){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(r._connectedTrack)throw new Error("Source is already used for a track.");const a=this.format.getSupportedTrackCounts(),s=this._tracks.reduce((l,u)=>l+(u.type===e?1:0),0),i=a[e].max;if(s===i)throw new Error(i===0?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${i} ${e} track${i===1?"":"s"}.`);const o=a.total.max;if(this._tracks.length===o)throw new Error(`${this.format._name} does not support more than ${o} tracks${o===1?"":"s"} in total.`);const c={id:this._tracks.length+1,output:this,type:e,source:r,metadata:n};if(c.type==="video"){const l=this.format.getSupportedVideoCodecs();if(l.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!l.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${l.map(u=>`'${u}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}else if(c.type==="audio"){const l=this.format.getSupportedAudioCodecs();if(l.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!l.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${l.map(u=>`'${u}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}else if(c.type==="subtitle"){const l=this.format.getSupportedSubtitleCodecs();if(l.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!l.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${l.map(u=>`'${u}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}this._tracks.push(c),r._connectedTrack=c}async start(){const e=this.format.getSupportedTrackCounts();for(const n of Ea){const a=this._tracks.reduce((i,o)=>i+(o.type===n?1:0),0),s=e[n].min;if(a<s)throw new Error(s===e[n].max?`${this.format._name} requires exactly ${s} ${n} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${n} track${s===1?"":"s"}.`)}const r=e.total.min;if(this._tracks.length<r)throw new Error(r===e.total.max?`${this.format._name} requires exactly ${r} track${r===1?"":"s"}.`:`${this.format._name} requires at least ${r} track${r===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started",this._writer.start();const n=await this._mutex.acquire();await this._muxer.start();const a=this._tracks.map(s=>s.source._start());await Promise.all(a),n()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){console.warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire(),r=this._tracks.map(n=>n.source._flushOrWaitForOngoingClose(!0));await Promise.all(r),await this._writer.close(),e()})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire(),r=this._tracks.map(n=>n.source._flushOrWaitForOngoingClose(!1));await Promise.all(r),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",e()})()}}function xr(t){return Math.round(t/2)*2}function Ia(t){return t.pages.reduce((e,r)=>e+(r.duration||5e3),0)}function Aa(t){let e=0;return t.pages.map(r=>{const n=e,a=r.duration||5e3;return e=n+a,{id:r.id,startTime:n,duration:a}})}function Dn(t){const e=[];let r=0;for(const n of t.pages){const a=n.duration||5e3;for(const s of n.children)if(s.type==="video"){const i=s.startTime||0,o=s.endTime||1,c=s.duration||5e3,l=s.volume!==void 0?s.volume:1;e.push({src:s.src,volume:l,startTime:i,endTime:o,duration:c,pageStartTime:r,pageDuration:a})}r+=a}return e}function Ba(t,e){const r=document.createElement("canvas"),n=t.width,a=t.height;if(r.width=xr(n*e),r.height=xr(a*e),r.width<=0||r.height<=0)throw new Error(`Invalid canvas dimensions: ${r.width}x${r.height}`);const s=r.getContext("2d",{alpha:!1,willReadFrequently:!1});if(!s)throw new Error("Failed to get canvas context");return{canvas:r,ctx:s}}async function Oa(t,e){const r=new Fa({target:new Pn,format:new Fn}),n=await wa(r.format.getSupportedVideoCodecs(),{width:t.width,height:t.height});if(!n)throw new Error("Your browser doesn't support video encoding.");const a=new xa(t,{codec:n,bitrate:On});return r.addVideoTrack(a,{frameRate:e}),{output:r,canvasSource:a}}async function za(t,e,r){if(!r)return{audioBufferSource:null};const n=44100,a=2,s=e.audios&&e.audios.length>0,i=Dn(e).length>0;if(!s&&!i)return{audioBufferSource:null};const o=await ya(t.format.getSupportedAudioCodecs(),{numberOfChannels:a,sampleRate:n});if(!o)return console.warn("Browser doesn't support audio encoding, video will be generated without audio."),{audioBufferSource:null};const c=new Pa({codec:o,bitrate:On});return t.addAudioTrack(c),{audioBufferSource:c,audioCodec:o}}async function Ra(t){for(const e of t.pages)t.selectPage(e.id),await t.waitLoading()}function Da(t,e,r){const n=e[r];return n&&t>=n.startTime&&t<n.startTime+n.duration?r:e.findIndex(a=>t>=a.startTime&&t<a.startTime+a.duration)}async function Ma(t,e,r,n,a,s){t.setCurrentTime(n);const i=await t._toCanvas({pixelRatio:s,pageId:t.pages[a]?.id,_skipTimeout:!0});r.drawImage(i,0,0,e.width,e.height),Vn.Util.releaseCanvas(i)}async function Na(t,e,r,n,a,s,i,o,c){const l=1e3/i,u=Math.floor(s/1e3*i)||1;t.setElementsPixelRatio(o),await Ra(t);let d=-1,f=0;const h=300;for(let m=0;m<u;m++){const p=Date.now(),T=m/i,k=1/i;let b=T*1e3;m===0&&(b=1),m===u-1&&(b=Math.min(s-1,(m+1)*l-1));const y=Da(b,a,d);if(y!==d&&y>=0&&(t.activePage.set({_rendering:!1}),t.selectPage(t.pages[y].id),t.activePage.set({_rendering:!0}),await t.waitLoading(),d=y),await Ma(t,e,r,b,y,o),await n.add(T,k),c){const S=Date.now();if(m===u-1||S-f>=h){const P=S-p,B=(m+1)/u;c(B,P),f=S}}}t.pages.forEach(m=>{m.set({_rendering:!1})}),t.setCurrentTime(0)}async function Va(t){if(t.startsWith("data:")||t.startsWith("blob:")){const e=await(await fetch(t)).blob();return new Zi(e)}return new es(t)}async function Ua(t){const e=await Va(t),r=new ts({source:e,formats:[new Xi,new Yi,new ln,new Gi]});try{return(await r.getAudioTracks()).length>0}finally{r.dispose()}}async function Mn(t){const e=await fetch(t);if(!e.ok)throw new Error(`Failed to download audio from ${t}`);return e.arrayBuffer()}async function Nn(t,e){return t.decodeAudioData(e)}async function Wa(t,e){const r=(t.delay||0)/1e3,n=t.volume!==void 0?t.volume:1,a=t.startTime||0,s=t.endTime||1,i=await Mn(t.src),o=await Nn(e.offlineContext,i),c=t.duration||e.totalDuration,l=a*c/1e3,u=c*(s-a)/1e3,d=e.offlineContext.createBufferSource();d.buffer=o;const f=e.offlineContext.createGain();f.gain.value=n,d.connect(f),f.connect(e.offlineContext.destination);const h=r,m=l,p=Math.min(u,o.duration-l);d.start(h,m,p)}async function Ha(t,e){if(!await Ua(t.src))return;const r=await Mn(t.src),n=await Nn(e.offlineContext,r),a=t.startTime*t.duration/1e3,s=t.duration*(t.endTime-t.startTime)/1e3,i=t.pageStartTime/1e3,o=e.offlineContext.createBufferSource();o.buffer=n;const c=e.offlineContext.createGain();c.gain.value=t.volume,o.connect(c),c.connect(e.offlineContext.destination);const l=i,u=a,d=Math.min(s,n.duration-a,t.pageDuration/1e3);o.start(l,u,d)}async function $a(t,e,r,n){const a=t.audios||[],s=Dn(t);if(a.length+s.length===0)return;const i=44100,o=2,c=typeof n=="string"?n:typeof n?.codec=="string"?n.codec:void 0,l=c?.includes("opus")?960:1024,u=c==="aac"?3:c?.includes("opus")?2:0,d=Math.floor(r/1e3*i),f=Math.floor(d/l)*l,h=u*l,m=Math.max(l,f-h),p=new OfflineAudioContext(o,m,i),T={offlineContext:p,sampleRate:i,totalDuration:r};for(const b of a)try{await Wa(b,T)}catch(y){console.error(`Failed to process audio ${b.src}:`,y)}for(const b of s)try{await Ha(b,T)}catch(y){console.error(`Failed to process video audio ${b.src}:`,y)}const k=await p.startRendering();await e.add(k)}async function qa({store:t,fps:e=30,pixelRatio:r=1,onProgress:n,includeAudio:a=!0}){const s=Ia(t);if(s===0)throw new Error("Video duration is 0");const i=Aa(t),{canvas:o,ctx:c}=Ba(t,r),{output:l,canvasSource:u}=await Oa(o,e),{audioBufferSource:d,audioCodec:f}=await za(l,t,a);await l.start(),await Na(t,o,c,u,i,s,e,r,n),u.close(),d&&(await $a(t,d,s,f),d.close()),await l.finalize();const h=l.target;return new Blob([h.buffer],{type:l.format.mimeType})}export{qa as storeToVideo};