"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[54758],{98425:(e,t,r)=>{r.d(t,{fP:()=>i3});var a,i,n,s,o,l,c,u,d,h,m=r(3053),f=r(52114);function p(e){if(!e)throw Error("Assertion failed.")}let g=e=>{let t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw Error(`Invalid rotation ${e}.`)},b=e=>e&&e[e.length-1];class k{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,r=7-(7&this.pos);return this.pos++,(t&1<>r}readBits(e){if(1===e)return this.readBit();let t=0;for(let r=0;r>r-e-1<{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw Error("Invalid exponential-Golomb code.");return(1<{let t=y(e);return(1&t)==0?-(t>>1):t+1>>1},T=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),S=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),v=new TextDecoder,x=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),P={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},I=x(P),C={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},E=x(C),F={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},A=x(F),B=e=>e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class D{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e;let t=new Promise(t=>{e=t}),r=this.currentPromise;return this.currentPromise=t,await r,e}}let R=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),M=e=>(e=(e=(e=(e=(e=e>>1&0x55555555|(0x55555555&e)<<1)>>2&0x33333333|(0x33333333&e)<<2)>>4&0xf0f0f0f|(0xf0f0f0f&e)<<4)>>8&0xff00ff|(0xff00ff&e)<<8)>>16&65535|(65535&e)<<16)>>>0,_=(e,t,r)=>{let a=0,i=e.length-1,n=-1;for(;a<=i;){let s=a+i>>1,o=r(e[s]);o===t?(n=s,i=s-1):o{let a=0,i=e.length-1,n=-1;for(;a<=i;){let s=a+(i-a+1)/2|0;r(e[s])<=t?(n=s,a=s+1):i=s-1}return n},L=(e,t,r)=>{let a=N(e,r(t),r);e.splice(a+1,0,t)},O=()=>{let e,t;return{promise:new Promise((r,a)=>{e=r,t=a}),resolve:e,reject:t}},z=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return e[r]},V=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return -1},U=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()},$=e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw TypeError("Argument must be an iterable or async iterable.")},j=e=>{throw Error(`Unexpected value: ${e}`)},H=(e,t,r)=>{let a=e.getUint8(t),i=e.getUint8(t+1),n=e.getUint8(t+2);return r?a|i<<8|n<<16:a<<16|i<<8|n},q=(e,t,r)=>H(e,t,r)<<8>>8,X=(e,t,r,a)=>{r>>>=0,r&=0xffffff,a?(e.setUint8(t,255&r),e.setUint8(t+1,r>>>8&255),e.setUint8(t+2,r>>>16&255)):(e.setUint8(t,r>>>16&255),e.setUint8(t+1,r>>>8&255),e.setUint8(t+2,255&r))},W=(e,t)=>({async next(){let r=await e.next();return r.done?{value:void 0,done:!0}:{value:t(r.value),done:!1}},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),K=(e,t,r)=>Math.max(t,Math.min(r,e)),Q=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},G=(e,t)=>Math.round(e/t)*t,J=e=>{let t=0;for(;e;)t++,e>>=1;return t},Y=/^[a-z]{3}$/,Z=e=>Y.test(e),ee=1e6*(1+Number.EPSILON),et=(e,t)=>{let r={...e,...t};if(e.headers||t.headers){let a=e.headers?er(e.headers):{},i=t.headers?er(t.headers):{},n={...a};Object.entries(i).forEach(([e,t])=>{let r=Object.keys(n).find(t=>t.toLowerCase()===e.toLowerCase());r&&delete n[r],n[e]=t}),r.headers=n}return r},er=e=>{if(e instanceof Headers){let t={};return e.forEach((e,r)=>{t[r]=e}),t}if(Array.isArray(e)){let t={};return e.forEach(([e,r])=>{t[e]=r}),t}return e},ea=async(e,t,r,a,i)=>{let n=0;for(;;)try{return await e(t,r)}catch(r){if(i())throw r;let e=a(++n,r,t);if(null===e)throw r;if(console.error("Retrying failed fetch. Error:",r),!Number.isFinite(e)||e<0)throw TypeError("Retry delay must be a non-negative finite number.");if(e>0&&await new Promise(t=>setTimeout(t,1e3*e)),i())throw r}};class ei{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let en=null,es=()=>null!==en?en:en=!!("undefined"!=typeof navigator&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),eo=null,el=()=>null!==eo?eo:eo="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox"),ec=null,eu=()=>null!==ec?ec:ec=!!("undefined"!=typeof navigator&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),ed=null,eh=()=>{if(null!==ed)return ed;if("undefined"==typeof navigator)return null;let e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?ed=Number(e[1]):null},em=(e,t)=>-1!==e?e:t,ef=(e,t,r,a)=>e<=a&&r<=t,ep=e=>{let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e{Symbol.dispose??=Symbol("Symbol.dispose")},eb=e=>"number"==typeof e&&!Number.isNaN(e),ek=["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"];[...ek];let ey=[{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:0x2200000,maxBitrate:18e7,level:60},{maxPictureSize:0x2200000,maxBitrate:24e7,level:61},{maxPictureSize:0x2200000,maxBitrate:48e7,level:62}],ew=".01.01.01.01.00",eT=".0.110.01.01.01.0",eS=e=>{let{codec:t,codecDescription:r,colorSpace:a,avcCodecInfo:i,hevcCodecInfo:n,vp9CodecInfo:s,av1CodecInfo:o}=e;if("avc"===t){if(p(null!==e.avcType),i){let t=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${e.avcType}.${R(t)}`}if(!r||r.byteLength<4)throw TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${R(r.subarray(1,4))}`}if("hevc"===t){let e,t,a,i,s,o;if(n)e=n.generalProfileSpace,t=n.generalProfileIdc,a=M(n.generalProfileCompatibilityFlags),i=n.generalTierFlag,s=n.generalLevelIdc,o=[...n.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let n=S(r),l=n.getUint8(1);e=l>>6&3,t=31&l,a=M(n.getUint32(2)),i=l>>5&1,s=n.getUint8(12),o=[];for(let e=0;e<6;e++)o.push(n.getUint8(6+e))}let l="hev1.";for(l+=["","A","B","C"][e]+t,l+=".",l+=a.toString(16).toUpperCase(),l+=".",l+=0===i?"L":"H",l+=s;o.length>0&&0===o[o.length-1];)o.pop();return o.length>0&&(l+=".",l+=o.map(e=>e.toString(16).toUpperCase()).join(".")),l}if("vp8"===t)return"vp8";if("vp9"===t){if(!s){let t=e.width*e.height,r=b(ey).level;for(let e of ey)if(t<=e.maxPictureSize){r=e.level;break}return`vp09.00.${r.toString().padStart(2,"0")}.08`}let t=s.profile.toString().padStart(2,"0"),r=s.level.toString().padStart(2,"0"),a=s.bitDepth.toString().padStart(2,"0"),i=s.chromaSubsampling.toString().padStart(2,"0"),n=s.colourPrimaries.toString().padStart(2,"0"),o=s.transferCharacteristics.toString().padStart(2,"0"),l=s.matrixCoefficients.toString().padStart(2,"0"),c=s.videoFullRangeFlag.toString().padStart(2,"0"),u=`vp09.${t}.${r}.${a}.${i}`;return(u+=`.${n}.${o}.${l}.${c}`).endsWith(ew)&&(u=u.slice(0,-ew.length)),u}if("av1"===t){if(!o){let t=e.width*e.height,r=b(ey).level;for(let e of ey)if(t<=e.maxPictureSize){r=e.level;break}return`av01.0.${r.toString().padStart(2,"0")}M.08`}let t=o.profile,r=o.level.toString().padStart(2,"0"),i=o.tier?"H":"M",n=o.bitDepth.toString().padStart(2,"0"),s=o.monochrome?"1":"0",l=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),c=a?.primaries?P[a.primaries]:1,u=a?.transfer?C[a.transfer]:1,d=a?.matrix?F[a.matrix]:1,h=a?.fullRange?1:0,m=`av01.${t}.${r}${i}.${n}`;return m+=`.${s}.${l.toString().padStart(3,"0")}`,m+=`.${c.toString().padStart(2,"0")}`,m+=`.${u.toString().padStart(2,"0")}`,m+=`.${d.toString().padStart(2,"0")}`,(m+=`.${h}`).endsWith(eT)&&(m=m.slice(0,-eT.length)),m}throw TypeError(`Unhandled codec '${t}'.`)},ev=e=>{let{codec:t,codecDescription:r,aacCodecInfo:a}=e;if("aac"===t){if(!a)throw TypeError("AAC codec info must be provided.");if(a.isMpeg2)return"mp4a.67";{let e=eI(r);return`mp4a.40.${e.objectType}`}}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if(t&&ek.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},ex=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],eP=[-1,1,2,3,4,5,6,8],eI=e=>{if(!e||e.byteLength<2)throw TypeError("AAC description must be at least 2 bytes long.");let t=new k(e),r=t.readBits(5);31===r&&(r=32+t.readBits(6));let a=t.readBits(4),i=null;15===a?i=t.readBits(24):a=1&&n<=7&&(s=eP[n]),{objectType:r,frequencyIndex:a,sampleRate:i,channelConfiguration:n,numberOfChannels:s}},eC=/^pcm-([usf])(\d+)+(be)?$/,eE=e=>{let t;if(p(ek.includes(e)),"ulaw"===e)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===e)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let r=eC.exec(e);return p(r),t="u"===r[1]?"unsigned":"s"===r[1]?"signed":"float",{dataType:t,sampleSize:Number(r[2])/8,littleEndian:"be"!==r[3],silentValue:"pcm-u8"===e?128:0}};!function(e){e[e.IDR=5]="IDR",e[e.SEI=6]="SEI",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.SPS_EXT=13]="SPS_EXT"}(a||(a={})),function(e){e[e.RASL_N=8]="RASL_N",e[e.RASL_R=9]="RASL_R",e[e.BLA_W_LP=16]="BLA_W_LP",e[e.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",e[e.VPS_NUT=32]="VPS_NUT",e[e.SPS_NUT=33]="SPS_NUT",e[e.PPS_NUT=34]="PPS_NUT",e[e.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(i||(i={}));let eF=e=>{let t=[],r=0;for(;r0&&a>r){let i=e.subarray(r,a);i.length>0&&t.push(i)}r=a+i}if(r0&&t.push(a)}return t},eA=(e,t)=>{let r=[],a=0,i=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;a+t<=e.length;){let n;1===t?n=i.getUint8(a):2===t?n=i.getUint16(a,!1):3===t?n=H(i,a,!1):4===t?n=i.getUint32(a,!1):(j(t),p(!1)),a+=t;let s=e.subarray(a,a+n);r.push(s),a+=n}return r},eB=e=>{let t=[],r=e.length;for(let a=0;a{let t=new Uint8Array(e.reduce((e,t)=>e+eD.byteLength+t.byteLength,0)),r=0;for(let a of e)t.set(eD,r),r+=eD.byteLength,t.set(a,r),r+=a.byteLength;return t},eM=(e,t)=>{let r=new Uint8Array(e.reduce((e,r)=>e+t+r.byteLength,0)),a=0;for(let i of e){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(a,i.byteLength);break;case 2:e.setUint16(a,i.byteLength,!1);break;case 3:X(e,a,i.byteLength,!1);break;case 4:e.setUint32(a,i.byteLength,!1)}a+=t,r.set(i,a),a+=i.byteLength}return r},e_=(e,t)=>t.description?eA(e,(3&T(t.description)[4])+1):eF(e),eN=(e,t)=>t.description?eM(e,(3&T(t.description)[4])+1):eR(e),eL=e=>31&e[0],eO=e=>{try{let t=eF(e),r=t.filter(e=>eL(e)===a.SPS),i=t.filter(e=>eL(e)===a.PPS),n=t.filter(e=>eL(e)===a.SPS_EXT);if(0===r.length||0===i.length)return null;let s=r[0],o=eV(s);p(null!==o);let l=100===o.profileIdc||110===o.profileIdc||122===o.profileIdc||144===o.profileIdc;return{configurationVersion:1,avcProfileIndication:o.profileIdc,profileCompatibility:o.constraintFlags,avcLevelIndication:o.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:r,pictureParameterSets:i,chromaFormat:l?o.chromaFormatIdc:null,bitDepthLumaMinus8:l?o.bitDepthLumaMinus8:null,bitDepthChromaMinus8:l?o.bitDepthChromaMinus8:null,sequenceParameterSetExt:l?n:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},ez=e=>{try{let t=S(e),r=0,a=t.getUint8(r++),i=t.getUint8(r++),n=t.getUint8(r++),s=t.getUint8(r++),o=3&t.getUint8(r++),l=31&t.getUint8(r++),c=[];for(let a=0;a{try{let t=new k(eB(e));t.skipBits(1),t.skipBits(2);let r=t.readBits(5);if(7!==r)return null;let a=t.readAlignedByte(),i=t.readAlignedByte(),n=t.readAlignedByte();y(t);let s=null,o=null,l=null;if((100===a||110===a||122===a||244===a||44===a||83===a||86===a||118===a||128===a)&&(s=y(t),3===s&&t.skipBits(1),o=y(t),l=y(t),t.skipBits(1),t.readBits(1))){for(let e=0;e<(3!==s?8:12);e++)if(t.readBits(1)){let r=e<6?16:64,a=8,i=8;for(let e=0;et.description?eA(e,(3&T(t.description)[21])+1):eF(e),e$=e=>e[0]>>1&63,ej=e=>{try{let t=eF(e),r=t.filter(e=>e$(e)===i.VPS_NUT),a=t.filter(e=>e$(e)===i.SPS_NUT),n=t.filter(e=>e$(e)===i.PPS_NUT),s=t.filter(e=>e$(e)===i.PREFIX_SEI_NUT||e$(e)===i.SUFFIX_SEI_NUT);if(0===a.length||0===n.length)return null;let o=a[0],l=new k(eB(o));l.skipBits(16),l.readBits(4);let c=l.readBits(3),u=l.readBits(1),{general_profile_space:d,general_tier_flag:h,general_profile_idc:m,general_profile_compatibility_flags:f,general_constraint_indicator_flags:p,general_level_idc:g}=eH(l,c);y(l);let b=y(l);3===b&&l.skipBits(1),y(l),y(l),l.readBits(1)&&(y(l),y(l),y(l),y(l));let T=y(l),S=y(l);y(l);let v=l.readBits(1)?0:c;for(let e=v;e<=c;e++)y(l),y(l),y(l);y(l),y(l),y(l),y(l),y(l),y(l),l.readBits(1)&&l.readBits(1)&&eq(l),l.skipBits(1),l.skipBits(1),l.readBits(1)&&(l.skipBits(4),l.skipBits(4),y(l),y(l),l.skipBits(1));let x=y(l);if(eX(l,x),l.readBits(1)){let e=y(l);for(let t=0;t0){let e=n[0],t=new k(eB(e));t.skipBits(16),y(t),y(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),y(t),y(t),w(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&y(t),w(t),w(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let r=t.readBits(1),a=t.readBits(1);I=r||a?r&&!a?2:!r&&a?3:0:0}let C=[...r.length?[{arrayCompleteness:1,nalUnitType:i.VPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:i.SPS_NUT,nalUnits:a}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:i.PPS_NUT,nalUnits:n}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:e$(s[0]),nalUnits:s}]:[]];return{configurationVersion:1,generalProfileSpace:d,generalTierFlag:h,generalProfileIdc:m,generalProfileCompatibilityFlags:f,generalConstraintIndicatorFlags:p,generalLevelIdc:g,minSpatialSegmentationIdc:P,parallelismType:I,chromaFormatIdc:b,bitDepthLumaMinus8:T,bitDepthChromaMinus8:S,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:u,lengthSizeMinusOne:3,arrays:C}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},eH=(e,t)=>{let r=e.readBits(2),a=e.readBits(1),i=e.readBits(5),n=0;for(let t=0;t<32;t++)n=n<<1|e.readBits(1);let s=new Uint8Array(6);for(let t=0;t<6;t++)s[t]=e.readBits(8);let o=e.readBits(8),l=[],c=[];for(let r=0;r0)for(let r=t;r<8;r++)e.skipBits(2);for(let r=0;r{for(let t=0;t<4;t++)for(let r=0;r<(3===t?2:6);r++)if(e.readBits(1)){let r=Math.min(64,1<<4+(t<<1));t>1&&w(e);for(let t=0;t{let r=[];for(let a=0;a{let i=0,n=0,s=0;if(0!==t&&(n=e.readBits(1)),n){s=t===r?t-(y(e)+1):t-1,e.readBits(1),y(e);let n=a[s]??0;for(let t=0;t<=n;t++)e.readBits(1)||e.readBits(1);i=a[s]}else{let t=y(e),r=y(e);for(let r=0;r{if(e.readBits(1)&&255===e.readBits(8)&&(e.readBits(16),e.readBits(16)),e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),e.readBits(1),e.readBits(1)&&(e.readBits(8),e.readBits(8),e.readBits(8))),e.readBits(1)&&(y(e),y(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(y(e),y(e),y(e),y(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&y(e),e.readBits(1)&&eQ(e,!0,t)),e.readBits(1)){e.readBits(1),e.readBits(1),e.readBits(1);let t=y(e);return y(e),y(e),y(e),y(e),t}return 0},eQ=(e,t,r)=>{let a=!1,i=!1,n=!1;t&&(a=1===e.readBits(1),i=1===e.readBits(1),(a||i)&&((n=1===e.readBits(1))&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),n&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=r;t++){let t=1===e.readBits(1),r=!0;t||(r=1===e.readBits(1));let s=!1;r?y(e):s=1===e.readBits(1);let o=1;s||(o=y(e)+1),a&&eG(e,o,n),i&&eG(e,o,n)}},eG=(e,t,r)=>{for(let a=0;a{let t=new k(e);if(2!==t.readBits(2))return null;let r=t.readBits(1),a=(t.readBits(1)<<1)+r;if(3===a&&t.skipBits(1),1===t.readBits(1)||0!==t.readBits(1)||(t.skipBits(2),4817730!==t.readBits(24)))return null;let i=8;a>=2&&(i=t.readBits(1)?12:10);let n=t.readBits(3),s=0,o=0;if(7!==n){if(o=t.readBits(1),1===a||3===a){let e=t.readBits(1),r=t.readBits(1);s=e||r?e&&!r?2:1:3,t.skipBits(1)}else s=1}else s=3,o=1;let l=(t.readBits(16)+1)*(t.readBits(16)+1),c=b(ey).level;for(let e of ey)if(l<=e.maxPictureSize){c=e.level;break}return{profile:a,level:c,bitDepth:i,chromaSubsampling:s,videoFullRangeFlag:o,colourPrimaries:2===n?1:1===n?6:2,transferCharacteristics:2===n?1:1===n?6:2,matrixCoefficients:7===n?0:2===n?1:1===n?6:2}},eY=function*(e){let t=new k(e),r=()=>{let e=0;for(let r=0;r<8;r++){let a=t.readAlignedByte();if(e|=(127&a)<<7*r,!(128&a))break;if(7===r&&128&a)return null}return e>=0x100000000-1?null:e};for(;t.getBitsLeft()>=8;){let a;t.skipBits(1);let i=t.readBits(4),n=t.readBits(1),s=t.readBits(1);if(t.skipBits(1),n&&t.skipBits(8),s){let e=r();if(null===e)return;a=e}else a=Math.floor(t.getBitsLeft()/8);p(t.pos%8==0),yield{type:i,data:e.subarray(t.pos/8,t.pos/8+a)},t.skipBits(8*a)}},eZ=e=>{for(let{type:t,data:r}of eY(e)){if(1!==t)continue;let e=new k(r),a=e.readBits(3);e.readBits(1);let i=e.readBits(1),n=0,s=0,o=0;if(i)n=e.readBits(5);else{if(e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.readBits(1)))return null;let t=e.readBits(1);t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));let r=e.readBits(5);for(let a=0;a<=r;a++){e.skipBits(12);let r=e.readBits(5);if(0===a&&(n=r),r>7){let t=e.readBits(1);0===a&&(s=t)}if(t&&e.readBits(1)){let t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}e.readBits(1)&&e.skipBits(4)}}let l=e.readBits(4),c=e.readBits(4),u=l+1;e.skipBits(u);let d=c+1;e.skipBits(d);if((i?0:e.readBits(1))&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!i){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);let t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let r=e.readBits(1);(r?2:e.readBits(1))>0&&!e.readBits(1)&&e.skipBits(1),t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);let h=e.readBits(1),m=8;2===a&&h?m=e.readBits(1)?12:10:a<=2&&(m=h?10:8);let f=0;1!==a&&(f=e.readBits(1));let p=1,g=1,b=0;return!f&&(0===a?(p=1,g=1):1===a?(p=0,g=0):12===m&&(p=e.readBits(1))&&(g=e.readBits(1)),p&&g&&(b=e.readBits(2))),{profile:a,level:n,tier:s,bitDepth:m,monochrome:f,chromaSubsamplingX:p,chromaSubsamplingY:g,chromaSamplePosition:b}}return null},e0=e=>{let t=S(e),r=t.getUint8(9),a=t.getUint16(10,!0),i=t.getUint32(12,!0),n=t.getInt16(16,!0),s=t.getUint8(18),o=null;return s&&(o=e.subarray(19,21+r)),{outputChannelCount:r,preSkip:a,inputSampleRate:i,outputGain:n,channelMappingFamily:s,channelMappingTable:o}},e1=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],e2=e=>({durationInSamples:e1[e[0]>>3]}),e3=e=>{if(e.length<7)throw Error("Setup header is too short.");if(5!==e[0])throw Error("Wrong packet type in Setup header.");if("vorbis"!==String.fromCharCode(...e.slice(1,7)))throw Error("Invalid packet signature in Setup header.");let t=e.length,r=new Uint8Array(t);for(let a=0;a97;)if(1===a.readBits(1)){i=a.pos;break}if(0===i)throw Error("Invalid Setup header: framing bit not found.");let n=0,s=!1,o=0;for(;a.getBitsLeft()>=97;){let e=a.pos,t=a.readBits(8),r=a.readBits(16),i=a.readBits(16);if(t>63||0!==r||0!==i){a.pos=e;break}if(a.skipBits(1),++n>64)break;a.clone().readBits(6)+1===n&&(s=!0,o=n)}if(!s)throw Error("Invalid Setup header: mode header not found.");if(o>63)throw Error(`Unsupported mode count: ${o}.`);let l=o;a.pos=0,a.skipBits(i);let c=Array(l).fill(0);for(let e=l-1;e>=0;e--)a.skipBits(40),c[e]=a.readBits(1);return{modeBlockflags:c}},e4=(e,t,r)=>{switch(e){case"avc":{let e=e_(r,t),i=e.some(e=>eL(e)===a.IDR);if(!i&&(!eu()||eh()>=144))for(let t of e){if(eL(t)!==a.SEI)continue;let e=eB(t),r=1;do{let t=0;for(;;){let a=e[r++];if(void 0===a||(t+=a,a<255))break}let a=0;for(;;){let t=e[r++];if(void 0===t||(a+=t,t<255))break}if(6===t){let t=new k(e);t.pos=8*r;let a=y(t),n=t.readBits(1);if(0===a&&1===n){i=!0;break}}r+=a}while(r{let t=e$(e);return i.BLA_W_LP<=t&&t<=i.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return 0==(1&r[0])?"key":"delta";case"vp9":{let e=new k(r);if(2!==e.readBits(2))return null;let t=e.readBits(1);if(3===(e.readBits(1)<<1)+t&&e.skipBits(1),e.readBits(1))return null;return 0===e.readBits(1)?"key":"delta"}case"av1":{let e=!1;for(let{type:t,data:a}of eY(r))if(1===t){let t=new k(a);t.skipBits(4),e=!!t.readBits(1)}else if(3===t||6===t||7===t){if(e)return"key";let t=new k(a);if(t.readBits(1))return null;return 0===t.readBits(2)?"key":"delta"}return null}default:j(e),p(!1)}};!function(e){e[e.STREAMINFO=0]="STREAMINFO",e[e.VORBIS_COMMENT=4]="VORBIS_COMMENT",e[e.PICTURE=6]="PICTURE"}(n||(n={}));let e8=(e,t)=>{let r=S(e),a=0,i=r.getUint32(a,!0);a+=4;let n=v.decode(e.subarray(a,a+i));a+=i,i>0&&(t.raw??={},t.raw.vendor??=n);let s=r.getUint32(a,!0);a+=4;for(let i=0;i0&&(t.trackNumber??=r),a&&Number.isInteger(a)&&a>0&&(t.tracksTotal??=a)}break;case"TRACKTOTAL":{let e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case"DISCNUMBER":{let e=l.split("/"),r=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(t.discNumber??=r),a&&Number.isInteger(a)&&a>0&&(t.discsTotal??=a)}break;case"DISCTOTAL":{let e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.discsTotal??=e)}break;case"DATE":{let e=new Date(l);Number.isNaN(e.getTime())||(t.date??=e)}break;case"GENRE":t.genre??=l;break;case"METADATA_BLOCK_PICTURE":{let e=ep(l),r=S(e),a=r.getUint32(0,!1),i=r.getUint32(4,!1),n=String.fromCharCode(...e.subarray(8,8+i)),s=r.getUint32(8+i,!1),o=v.decode(e.subarray(12+i,12+i+s)),c=r.getUint32(i+s+28),u=e.subarray(i+s+32,i+s+32+c);t.images??=[],t.images.push({data:u,mimeType:n,kind:3===a?"coverFront":4===a?"coverBack":"unknown",name:void 0,description:o||void 0})}}}};class e6{constructor(e){this.input=e}}let e5=[],e9=[],e7=new Uint8Array(0);class te{constructor(e,t,r,a,i=-1,n,s){if(this.data=e,this.type=t,this.timestamp=r,this.duration=a,this.sequenceNumber=i,e===e7&&void 0===n)throw Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===n&&(n=e.byteLength),!(e instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if("key"!==t&&"delta"!==t)throw TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw TypeError("timestamp must be a number.");if(!Number.isFinite(a)||a<0)throw TypeError("duration must be a non-negative number.");if(!Number.isFinite(i))throw TypeError("sequenceNumber must be a number.");if(!Number.isInteger(n)||n<0)throw TypeError("byteLength must be a non-negative integer.");if(void 0!==s&&("object"!=typeof s||!s))throw TypeError("sideData, when provided, must be an object.");if(s?.alpha!==void 0&&!(s.alpha instanceof Uint8Array))throw TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(s?.alphaByteLength!==void 0&&(!Number.isInteger(s.alphaByteLength)||s.alphaByteLength<0))throw TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=n,this.sideData=s??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===e7}get microsecondTimestamp(){return Math.trunc(ee*this.timestamp)}get microsecondDuration(){return Math.trunc(ee*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw 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 TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw 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 TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"==typeof EncodedAudioChunk)throw 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,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let r=new Uint8Array(e.byteLength);return e.copyTo(r),new te(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(void 0!==e&&("object"!=typeof e||null===e))throw TypeError("options, when provided, must be an object.");if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw TypeError("options.duration, when provided, must be a number.");return new te(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}}let tt=e=>{let t=0,r=0,a=~e;128&a&&(a&=-129,t=-1);let i=(1<<(r=((240&a)>>4)+5)|(15&a)<{let t=0,r=0,a=85^e;128&a&&(a&=-129,t=-1);let i=0;return i=4!=(r=((240&a)>>4)+4)?1<{let t=Date.now();"video"===e.type?(t-ta>=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."),ta=t),"undefined"!=typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-ti>=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."),ti=t),"undefined"!=typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));let ts=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],to=new Set(ts);class tl{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(ee*this.timestamp)}get microsecondDuration(){return Math.trunc(ee*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||"object"!=typeof t)throw TypeError("init must be an object.");if(void 0===t.format||!to.has(t.format))throw TypeError("init.format must be one of: "+ts.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw TypeError("init.codedHeight must be a positive integer.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");this._data=T(e).slice(),this._layout=t.layout??tf(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new tc(t.colorSpace)}else if("undefined"!=typeof VideoFrame&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this._layout=null,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=t?.rotation??0,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new tc(e.colorSpace)}else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!t||"object"!=typeof t)throw TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if("undefined"!=typeof VideoFrame)return new tl(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*ee),duration:Math.trunc((t.duration??0)*ee)||void 0}),t);let r=0,a=0;if("naturalWidth"in e?(r=e.naturalWidth,a=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,a=e.videoHeight):"width"in e&&(r=Number(e.width),a=Number(e.height)),!r||!a)throw TypeError("Could not determine dimensions.");let i=new OffscreenCanvas(r,a),n=i.getContext("2d",{alpha:el(),willReadFrequently:!0});p(n),n.drawImage(e,0,0),this._data=i,this._layout=null,this.format="RGBX",this.codedWidth=r,this.codedHeight=a,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new tc({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");tn?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw Error("VideoSample is closed.");return(p(null!==this._data),tu(this._data))?new tl(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(p(this._layout),new tl(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})):new tl(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||(tn?.unregister(this),tu(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(tm(e),this._closed)throw Error("VideoSample is closed.");if((e.format??this.format)===null)throw Error("Cannot get allocation size when format is null. Please manually provide an RGB pixel format in the options instead.");if(p(null!==this._data),!tu(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let t=this.toVideoFrame(),r=t.allocationSize(e);return t.close(),r}return tu(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,t={}){if(!B(e))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(tm(t),this._closed)throw Error("VideoSample is closed.");if((t.format??this.format)===null)throw Error("Cannot copy video sample data when format is null. Please manually provide an RGB pixel format in the options instead.");if(p(null!==this._data),!tu(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){let r=this.toVideoFrame(),a=await r.copyTo(e,t);return r.close(),a}if(tu(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array)return p(this._layout),T(e).set(this._data),this._layout;{let t=this._data.getContext("2d");p(t);let r=t.getImageData(0,0,this.codedWidth,this.codedHeight);return T(e).set(r.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw Error("VideoSample is closed.");return(p(null!==this._data),tu(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,t,r,a,i,n,s,o,l){let c=0,u=0,d=this.displayWidth,h=this.displayHeight,m=0,f=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==n?(c=t,u=r,d=a,h=i,m=n,f=s,void 0!==o?(p=o,g=l):(p=d,g=h)):(m=t,f=r,void 0!==a&&(p=a,g=i)),!("undefined"!=typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(c))throw TypeError("sx must be a number.");if(!Number.isFinite(u))throw TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(m))throw TypeError("dx must be a number.");if(!Number.isFinite(f))throw TypeError("dy must be a number.");if(!Number.isFinite(p)||p<0)throw TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw TypeError("dHeight must be a non-negative number.");if(this._closed)throw Error("VideoSample is closed.");({sx:c,sy:u,sWidth:d,sHeight:h}=this._rotateSourceRegion(c,u,d,h,this.rotation));let b=this.toCanvasImageSource();e.save();let k=m+p/2,y=f+g/2;e.translate(k,y),e.rotate(this.rotation*Math.PI/180);let w=this.rotation%180==0?1:p/g;e.scale(1/w,w),e.drawImage(b,c,u,d,h,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){let r,a,i,n;if(!("undefined"!=typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&th(t.crop,"options.");let s=e.canvas.width,o=e.canvas.height,l=t.rotation??this.rotation,[c,u]=l%180==0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];t.crop&&td(t.crop,c,u);let{sx:d,sy:h,sWidth:m,sHeight:f}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??c,t.crop?.height??u,l);if("fill"===t.fit)r=0,a=0,i=s,n=o;else{let[e,l]=t.crop?[t.crop.width,t.crop.height]:[c,u],d="contain"===t.fit?Math.min(s/e,o/l):Math.max(s/e,o/l);i=e*d,n=l*d,r=(s-i)/2,a=(o-n)/2}e.save();let p=l%180==0?1:i/n;e.translate(s/2,o/2),e.rotate(l*Math.PI/180),e.scale(1/p,p),e.translate(-s/2,-o/2),e.drawImage(this.toCanvasImageSource(),d,h,m,f,r,a,i,n),e.restore()}_rotateSourceRegion(e,t,r,a,i){return 90===i?[e,t,r,a]=[t,this.codedHeight-e-r,a,r]:180===i?[e,t]=[this.codedWidth-e-r,this.codedHeight-t-a]:270===i&&([e,t,r,a]=[this.codedWidth-t-a,e,a,r]),{sx:e,sy:t,sWidth:r,sHeight:a}}toCanvasImageSource(){if(this._closed)throw Error("VideoSample is closed.");if(p(null!==this._data),!(this._data instanceof Uint8Array))return this._data;{let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}}setRotation(e){if(![0,90,180,270].includes(e))throw TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}}class tc{constructor(e){this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}let tu=e=>"undefined"!=typeof VideoFrame&&e instanceof VideoFrame,td=(e,t,r)=>{e.left=Math.min(e.left,t),e.top=Math.min(e.top,r),e.width=Math.min(e.width,t-e.left),e.height=Math.min(e.height,r-e.top),p(e.width>=0),p(e.height>=0)},th=(e,t)=>{if(!e||"object"!=typeof e)throw TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(e.left)||e.left<0)throw TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(e.top)||e.top<0)throw TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(e.width)||e.width<0)throw TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(e.height)||e.height<0)throw TypeError(t+"crop.height must be a non-negative integer.")},tm=e=>{if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.colorSpace&&!["display-p3","srgb"].includes(e.colorSpace))throw TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(void 0!==e.format&&"string"!=typeof e.format)throw TypeError("options.format, when provided, must be a string.");if(void 0!==e.layout){if(!Array.isArray(e.layout))throw TypeError("options.layout, when provided, must be an array.");for(let t of e.layout){if(!t||"object"!=typeof t)throw TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==e.rect){if(!e.rect||"object"!=typeof e.rect)throw TypeError("options.rect, when provided, must be an object.");if(void 0!==e.rect.x&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw TypeError("options.rect.x, when provided, must be a non-negative integer.");if(void 0!==e.rect.y&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw TypeError("options.rect.y, when provided, must be a non-negative integer.");if(void 0!==e.rect.width&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw TypeError("options.rect.width, when provided, must be a non-negative integer.");if(void 0!==e.rect.height&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw TypeError("options.rect.height, when provided, must be a non-negative integer.")}},tf=(e,t,r)=>{let a=tp(e),i=[],n=0;for(let e of a){let a=Math.ceil(t/e.widthDivisor),s=Math.ceil(r/e.heightDivisor),o=a*e.sampleBytes,l=o*s;i.push({offset:n,stride:o}),n+=l}return i},tp=e=>{let t=(e,t,r,a,i)=>{let n=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:r,heightDivisor:a},{sampleBytes:t,widthDivisor:r,heightDivisor:a}];return i&&n.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),n};switch(e){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:j(e),p(!1)}},tg=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class tb{get microsecondTimestamp(){return Math.trunc(ee*this.timestamp)}get microsecondDuration(){return Math.trunc(ee*this.duration)}constructor(e){if(this._closed=!1,tS(e)){if(null===e.format)throw 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{let t;if(!e||"object"!=typeof e)throw TypeError("Invalid AudioDataInit: must be an object.");if(!tg.has(e.format))throw TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw TypeError("init.timestamp must be a number.");let r=e.data.byteLength/(tk(e.format)*e.numberOfChannels);if(!Number.isInteger(r))throw TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");if(this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=r,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=r/e.sampleRate,e.data instanceof ArrayBuffer)t=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))t=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw TypeError("Invalid AudioDataInit: data is not a BufferSource.");let a=this.numberOfFrames*this.numberOfChannels*tk(this.format);if(t.byteLength=this.numberOfFrames)throw RangeError("frameOffset out of range");let a=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-r;if(a>this.numberOfFrames-r)throw RangeError("frameCount out of range");let i=tk(t),n=ty(t);if(n&&e.planeIndex>=this.numberOfChannels||!n&&0!==e.planeIndex)throw RangeError("planeIndex out of range");return(n?a:a*this.numberOfChannels)*i}copyTo(e,t){if(!B(e))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if(void 0!==t.format&&!tg.has(t.format))throw TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let{planeIndex:r,format:a,frameCount:i,frameOffset:n}=t,s=a??this.format;if(!s)throw Error("Destination format not determined");let o=this.numberOfFrames,l=this.numberOfChannels,c=n??0;if(c>=o)throw RangeError("frameOffset out of range");let u=void 0!==i?i:o-c;if(u>o-c)throw RangeError("frameCount out of range");let d=tk(s),h=ty(s);if(h&&r>=l||!h&&0!==r)throw RangeError("planeIndex out of range");let m=h?u:u*l;if(e.byteLength0;){let i=Math.min(n,o),l=new Float32Array(r*i);for(let t=0;t0;){let i=Math.min(n,o),c=new Float32Array(r*i);for(let t=0;t{switch(e){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":case"f32":case"f32-planar":return 4;default:throw Error("Unknown AudioSampleFormat")}},ty=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},tw=e=>{switch(e){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/0x80000000;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},tT=e=>{switch(e){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,K((r+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,K(Math.round(32767*r),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,K(Math.round(0x7fffffff*r),-0x80000000,0x7fffffff),!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},tS=e=>"undefined"!=typeof AudioData&&e instanceof AudioData,tv=e=>{if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.metadataOnly&&"boolean"!=typeof e.metadataOnly)throw TypeError("options.metadataOnly, when defined, must be a boolean.");if(void 0!==e.verifyKeyPackets&&"boolean"!=typeof e.verifyKeyPackets)throw TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(e.verifyKeyPackets&&e.metadataOnly)throw TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},tx=e=>{if(!eb(e))throw TypeError("timestamp must be a number.")},tP=(e,t,r)=>r.verifyKeyPackets?t.then(async t=>{if(!t||"delta"===t.type)return t;let r=await e.determinePacketType(t);return r&&(t.type=r),t}):t;class tI{constructor(e){if(!(e instanceof tO))throw TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(tv(e),this._track.input._disposed)throw new a$;return tP(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(tx(e),tv(t),this._track.input._disposed)throw new a$;return tP(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof te))throw TypeError("packet must be an EncodedPacket.");if(tv(t),this._track.input._disposed)throw new a$;return tP(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(tx(e),tv(t),this._track.input._disposed)throw new a$;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let r=await this._track._backing.getKeyPacket(e,t);return r&&(p("key"===r.type),"delta"===await this._track.determinePacketType(r))?this.getKeyPacket(r.timestamp-1/this._track.timeResolution,t):r}async getNextKeyPacket(e,t={}){if(!(e instanceof te))throw TypeError("packet must be an EncodedPacket.");if(tv(t),this._track.input._disposed)throw new a$;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let r=await this._track._backing.getNextKeyPacket(e,t);return r&&(p("key"===r.type),"delta"===await this._track.determinePacketType(r))?this.getNextKeyPacket(r,t):r}packets(e,t,r={}){if(void 0!==e&&!(e instanceof te))throw TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!r?.metadataOnly)throw TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof te))throw TypeError("endPacket must be an EncodedPacket.");if(tv(r),this._track.input._disposed)throw new a$;let a=[],{promise:i,resolve:n}=O(),{promise:s,resolve:o}=O(),l=!1,c=!1,u=null,d=[],h=()=>Math.max(2,d.length);(async()=>{let u=e??await this.getFirstPacket(r);for(;u&&!c&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);){if(a.length>h()){({promise:s,resolve:o}=O()),await s;continue}a.push(u),n(),({promise:i,resolve:n}=O()),u=await this.getNextPacket(u,r)}l=!0,n()})().catch(e=>{u||(u=e,n())});let m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new a$;if(c)return{value:void 0,done:!0};if(u)throw u;if(a.length>0){let e=a.shift(),t=performance.now();for(d.push(t);d.length>0&&t-d[0]>=1e3;)d.shift();return o(),{value:e,done:!1}}else{if(l)return{value:void 0,done:!0};await i}}},return:async()=>(c=!0,o(),n(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class tC{constructor(e,t){this.onSample=e,this.onError=t}}class tE{mediaSamplesInRange(e=0,t=1/0){tx(e),tx(t);let r=[],a=!1,i=null,{promise:n,resolve:s}=O(),{promise:o,resolve:l}=O(),c=!1,u=!1,d=!1,h=null;(async()=>{let m;let f=await this._createDecoder(o=>{if(l(),o.timestamp>=t&&(u=!0),u){o.close();return}i&&(o.timestamp>e?(r.push(i),a=!0):i.close()),o.timestamp>=e&&(r.push(o),a=!0),i=a?null:o,r.length>0&&(s(),{promise:n,resolve:s}=O())},e=>{h||(h=e,s())}),p=this._createPacketSink(),g=await p.getKeyPacket(e,{verifyKeyPackets:!0})??await p.getFirstPacket(),b=g;if(t<1/0){let e=await p.getPacket(t),r=e?"key"===e.type&&e.timestamp===t?e:await p.getNextKeyPacket(e,{verifyKeyPackets:!0}):null;r&&(m=r)}let k=p.packets(g??void 0,m);for(await k.next();b&&!u&&!this._track.input._disposed;){let e=tF(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:o,resolve:l}=O()),await o;continue}f.decode(b);let t=await k.next();if(t.done)break;b=t.value}await k.return(),d||this._track.input._disposed||await f.flush(),f.close(),!a&&i&&r.push(i),c=!0,s()})().catch(e=>{h||(h=e,s())});let m=this._track,f=()=>{for(let e of(i?.close(),r))e.close()};return{async next(){for(;;){if(m.input._disposed)throw f(),new a$;if(d)return{value:void 0,done:!0};if(h)throw f(),h;if(r.length>0){let e=r.shift();return l(),{value:e,done:!1}}else{if(c)return{value:void 0,done:!0};await n}}},return:async()=>(d=!0,u=!0,l(),s(),f(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){$(e);let t=U(e),r=[],a=[],{promise:i,resolve:n}=O(),{promise:s,resolve:o}=O(),l=!1,c=!1,u=null,d=e=>{a.push(e),n(),{promise:i,resolve:n}=O()};(async()=>{let e=await this._createDecoder(e=>{if(o(),c){e.close();return}let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let r=0;r{u||(u=e,n())}),i=this._createPacketSink(),h=null,m=null,f=-1,g=async()=>{p(m);let t=m;for(e.decode(t);t.sequenceNumberr&&!c;)({promise:s,resolve:o}=O()),await s;if(c)break;let n=await i.getNextPacket(t);p(n),e.decode(n),t=n}f=-1},b=async()=>{await e.flush();for(let e=0;e{u||(u=e,n())});let h=this._track,m=()=>{for(let e of a)e?.close()};return{async next(){for(;;){if(h.input._disposed)throw m(),new a$;if(c)return{value:void 0,done:!0};if(u)throw m(),u;if(a.length>0){let e=a.shift();return p(void 0!==e),o(),{value:e,done:!1}}else{if(l)return{value:void 0,done:!0};await i}}},return:async()=>(c=!0,o(),n(),m(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}let tF=e=>0===e?40:8;class tA extends tC{constructor(e,t,r,a,i,n){super(e,t),this.codec=r,this.decoderConfig=a,this.rotation=i,this.timeResolution=n,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new ei,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;let s=e5.find(e=>e.supports(r,a));if(s)this.customDecoder=new s,this.customDecoder.codec=r,this.customDecoder.config=a,this.customDecoder.onSample=e=>{if(!(e instanceof tl))throw TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let e=e=>{if(this.alphaQueue.length>0){let t=this.alphaQueue.shift();p(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if("avc"===r&&this.decoderConfig.description&&eu()){let e=ez(T(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){let t=eV(e.sequenceParameterSets[0]);t&&0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let t=Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(p(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(p(this.decoder),es()||L(this.inputTimestamps,e.timestamp,e=>e),eu()&&0===this.currentPacketIndex&&"avc"===this.codec&&(e=new te(eN(e_(e.data,this.decoderConfig).filter(e=>{let t=eL(e);return!(t>=20&&t<=31)}),this.decoderConfig),e.type,e.timestamp,e.duration)),this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)),this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed){this.pushNullAlphaFrame();return}if(!this.merger)try{this.merger=new tB}catch(t){console.error("Due to an error, only color data will be decoded.",t),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let t=this.colorQueue.shift();p(void 0!==t),this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let e=this.colorQueue.shift();p(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null)},t=Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=e4(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===t),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){return eU(e,this.decoderConfig).some(e=>{let t=e$(e);return t===i.RASL_N||t===i.RASL_R})}sampleHandler(e){if(es()){if(this.sampleQueue.length>0&&e.timestamp>=b(this.sampleQueue).timestamp){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}L(this.sampleQueue,e,e=>e.timestamp)}else{let t=this.inputTimestamps.shift();p(void 0!==t),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,t){if(!t){let t=new tl(e);this.sampleHandler(t);return}p(this.merger),this.merger.update(e,t),e.close(),t.close();let r=new tl(new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}));this.sampleHandler(r)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(p(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),es()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){for(let e of(this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(p(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close()),this.sampleQueue))e.close();this.sampleQueue.length=0}}class tB{constructor(){"undefined"!=typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es in vec2 a_position; in vec2 a_texCoord; out vec2 v_texCoord; void main() { gl_Position = vec4(a_position, 0.0, 1.0); v_texCoord = a_texCoord; } `),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es precision highp float; uniform sampler2D u_colorTexture; uniform sampler2D u_alphaTexture; in vec2 v_texCoord; out vec4 fragColor; void main() { vec3 color = texture(u_colorTexture, v_texCoord).rgb; float alpha = texture(u_alphaTexture, v_texCoord).r; fragColor = vec4(color, alpha); } `),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createShader(e,t){let r=this.gl.createShader(e);return this.gl.shaderSource(r,t),this.gl.compileShader(r),r}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),r=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,r),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let a=this.gl.getAttribLocation(this.program,"a_position"),i=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class tD extends tE{constructor(e){if(!(e instanceof tz))throw TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let r=this._track.codec,a=this._track.rotation,i=await this._track.getDecoderConfig(),n=this._track.timeResolution;return p(r&&i),new tA(e,t,r,i,a,n)}_createPacketSink(){return new tI(this._track)}async getSample(e){for await(let t of(tx(e),this.mediaSamplesAtTimestamps([e])))return t;throw Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}}class tR{constructor(e,t={}){if(this._nextCanvasIndex=0,!(e instanceof tz))throw TypeError("videoTrack must be an InputVideoTrack.");if(t&&"object"!=typeof t)throw TypeError("options must be an object.");if(void 0!==t.alpha&&"boolean"!=typeof t.alpha)throw TypeError("options.alpha, when provided, must be a boolean.");if(void 0!==t.width&&(!Number.isInteger(t.width)||t.width<=0))throw TypeError("options.width, when defined, must be a positive integer.");if(void 0!==t.height&&(!Number.isInteger(t.height)||t.height<=0))throw TypeError("options.height, when defined, must be a positive integer.");if(void 0!==t.fit&&!["fill","contain","cover"].includes(t.fit))throw TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==t.width&&void 0!==t.height&&void 0===t.fit)throw TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(void 0!==t.crop&&th(t.crop,"options."),void 0!==t.poolSize&&("number"!=typeof t.poolSize||!Number.isInteger(t.poolSize)||t.poolSize<0))throw TypeError("poolSize must be a non-negative integer.");let r=t.rotation??e.rotation,[a,i]=r%180==0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],n=t.crop;n&&td(n,a,i);let[s,o]=n?[n.width,n.height]:[a,i],l=s/o;void 0!==t.width&&void 0===t.height?o=Math.round((s=t.width)/l):void 0===t.width&&void 0!==t.height?s=Math.round((o=t.height)*l):void 0!==t.width&&void 0!==t.height&&(s=t.width,o=t.height),this._videoTrack=e,this._alpha=t.alpha??!1,this._width=s,this._height=o,this._rotation=r,this._crop=n,this._fit=t.fit??"fill",this._videoSampleSink=new tD(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex],r=!1;t||("undefined"!=typeof document?((t=document.createElement("canvas")).width=this._width,t.height=this._height):t=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=t),r=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let a=t.getContext("2d",{alpha:this._alpha||el()});p(a),a.resetTransform(),r||(!this._alpha&&el()?(a.fillStyle="black",a.fillRect(0,0,this._width,this._height)):a.clearRect(0,0,this._width,this._height)),e.drawWithFit(a,{fit:this._fit,rotation:this._rotation,crop:this._crop});let i={canvas:t,timestamp:e.timestamp,duration:e.duration};return e.close(),i}async getCanvas(e){tx(e);let t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return W(this._videoSampleSink.samples(e,t),e=>this._videoSampleToWrappedCanvas(e))}canvasesAtTimestamps(e){return W(this._videoSampleSink.samplesAtTimestamps(e),e=>e&&this._videoSampleToWrappedCanvas(e))}}class tM extends tC{constructor(e,t,r,a){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new ei,this.customDecoderQueueSize=0,this.currentTimestamp=null;let i=t=>{(null===this.currentTimestamp||Math.abs(t.timestamp-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=t.timestamp);let r=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames){t.close();return}let i=a.sampleRate;t.setTimestamp(Math.round(r*i)/i),e(t)},n=e9.find(e=>e.supports(r,a));if(n)this.customDecoder=new n,this.customDecoder.codec=r,this.customDecoder.config=a,this.customDecoder.onSample=e=>{if(!(e instanceof tb))throw TypeError("The argument passed to onSample must be an AudioSample.");i(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let e=Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{i(new tb(e))}catch(e){this.onError(e)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(a)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(p(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(p(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(p(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(p(this.decoder),this.decoder.close())}}class t_ extends tC{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,p(ek.includes(r.codec)),this.codec=r.codec;let{dataType:a,sampleSize:i,littleEndian:n}=eE(this.codec);switch(this.inputSampleSize=i,i){case 1:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint8(t)-128:"signed"===a?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===a?this.readInputValue=(e,t)=>tt(e.getUint8(t)):"alaw"===a?this.readInputValue=(e,t)=>tr(e.getUint8(t)):p(!1);break;case 2:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint16(t,n)-32768:"signed"===a?this.readInputValue=(e,t)=>e.getInt16(t,n):p(!1);break;case 3:"unsigned"===a?this.readInputValue=(e,t)=>H(e,t,n)-8388608:"signed"===a?this.readInputValue=(e,t)=>q(e,t,n):p(!1);break;case 4:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint32(t,n)-0x80000000:"signed"===a?this.readInputValue=(e,t)=>e.getInt32(t,n):"float"===a?this.readInputValue=(e,t)=>e.getFloat32(t,n):p(!1);break;case 8:"float"===a?this.readInputValue=(e,t)=>e.getFloat64(t,n):p(!1);break;default:j(i),p(!1)}switch(i){case 1:"ulaw"===a||"alaw"===a?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,r)=>e.setInt16(t,r,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,r)=>e.setUint8(t,r+128));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,r)=>e.setInt16(t,r,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,r)=>e.setInt32(t,r<<8,!0);break;case 4:this.outputSampleSize=4,"float"===a?(this.outputFormat="f32",this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,r)=>e.setInt32(t,r,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,!0);break;default:j(i),p(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=S(e.data),r=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,a=new ArrayBuffer(r*this.decoderConfig.numberOfChannels*this.outputSampleSize),i=new DataView(a);for(let e=0;e=n)&&(this.currentTimestamp=e.timestamp);let s=this.currentTimestamp;this.currentTimestamp+=n;let o=new tb({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:r,timestamp:s});this.onSample(o)}async flush(){}close(){}}class tN extends tE{constructor(e){if(!(e instanceof tV))throw TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let r=this._track.codec,a=await this._track.getDecoderConfig();return(p(r&&a),ek.includes(a.codec))?new t_(e,t,a):new tM(e,t,r,a)}_createPacketSink(){return new tI(this._track)}async getSample(e){for await(let t of(tx(e),this.mediaSamplesAtTimestamps([e])))return t;throw Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}}class tL{constructor(e){if(!(e instanceof tV))throw TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new tN(e)}_audioSampleToWrappedArrayBuffer(e){let t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e){tx(e);let t=await this._audioSampleSink.getSample(e);return t&&this._audioSampleToWrappedArrayBuffer(t)}buffers(e=0,t=1/0){return W(this._audioSampleSink.samples(e,t),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e){return W(this._audioSampleSink.samplesAtTimestamps(e),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class tO{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof tz}isAudioTrack(){return this instanceof tV}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){let t=new tI(this),r=1/0,a=-1/0,i=0,n=0;for await(let s of t.packets(void 0,void 0,{metadataOnly:!0})){if(i>=e&&s.timestamp>=a)break;r=Math.min(r,s.timestamp),a=Math.max(a,s.timestamp+s.duration),i++,n+=s.byteLength}return{packetCount:i,averagePacketRate:i?Number((i/(a-r)).toPrecision(16)):0,averageBitrate:i?Number((8*n/(a-r)).toPrecision(16)):0}}}class tz extends tO{constructor(e,t){super(e,t),this._backing=t}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(){let e=await this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pg"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let e=await this._backing.getDecoderConfig();return e?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=this._backing.getCodec();if(p(null!==t),e5.some(r=>r.supports(t,e)))return!0;if("undefined"==typeof VideoDecoder)return!1;let r=await VideoDecoder.isConfigSupported(e);return!0===r.supported}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof te))throw TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw TypeError("packet must not be metadata-only to determine its type.");if(null===this.codec)return null;let t=await this.getDecoderConfig();return p(t),e4(this.codec,t,e.data)}}class tV extends tO{constructor(e,t){super(e,t),this._backing=t}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(){let e=await this._backing.getDecoderConfig();return e?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=this._backing.getCodec();if(p(null!==t),e9.some(r=>r.supports(t,e))||e.codec.startsWith("pcm-"))return!0;{if("undefined"==typeof AudioDecoder)return!1;let t=await AudioDecoder.isConfigSupported(e);return!0===t.supported}}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof te))throw TypeError("packet must be an EncodedPacket.");return null===this.codec?null:"key"}}let tU=e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");if(e.codecStrings.length>0){let r=[...new Set(e.codecStrings)];t+=`; codecs="${r.join(", ")}"`}return t};class t${constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if("string"!=typeof t)throw TypeError("mimeType must be a string.")}}class tj{constructor(e,t,r,a){if(this.data=e,this.mimeType=t,this.name=r,this.description=a,!(e instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if(void 0!==t&&"string"!=typeof t)throw TypeError("mimeType, when provided, must be a string.");if(void 0!==r&&"string"!=typeof r)throw TypeError("name, when provided, must be a string.");if(void 0!==a&&"string"!=typeof a)throw TypeError("description, when provided, must be a string.")}}let tH={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class tq{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new a$;if(null!==this.fileSize&&e+t>this.fileSize)return null;let r=e+t,a=this.source._read(e,r);return a instanceof Promise?a.then(t=>t?new tX(t.bytes,t.view,t.offset,e,r):null):a?new tX(a.bytes,a.view,a.offset,e,r):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new a$;if(null!==this.fileSize)return this.requestSlice(e,K(this.fileSize-e,t,r));{let a=this.requestSlice(e,r),i=a=>{if(a)return a;let i=a=>(p(null!==a),this.requestSlice(e,K(a-e,t,r))),n=this.source._retrieveSize();return n instanceof Promise?n.then(i):i(n)};return a instanceof Promise?a.then(i):i(a)}}}class tX{constructor(e,t,r,a,i){this.bytes=e,this.view=t,this.offset=r,this.start=a,this.end=i,this.bufferPos=a-r}static tempFromBytes(e){return new tX(e,S(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,t=this.end-e){if(ethis.end)throw RangeError("Slicing outside of original slice.");return new tX(this.bytes,this.view,this.offset,e,e+t)}}let tW=(e,t)=>{if(e.filePose.end)throw RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},tK=(e,t)=>{tW(e,t);let r=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,r},tQ=e=>(tW(e,1),e.view.getUint8(e.bufferPos++)),tG=(e,t)=>{tW(e,2);let r=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,r},tJ=e=>{tW(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},tY=e=>{tW(e,3);let t=H(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},tZ=e=>{tW(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},t0=(e,t)=>{tW(e,4);let r=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,r},t1=e=>{tW(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},t2=e=>{tW(e,4);let t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},t3=e=>{tW(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},t4=e=>{tW(e,4);let t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t},t8=(e,t)=>{let r,a;return t?(r=t0(e,!0),a=t0(e,!0)):(a=t0(e,!1),r=t0(e,!1)),0x100000000*a+r},t6=e=>0x100000000*t1(e)+t1(e),t5=e=>0x100000000*t3(e)+t1(e),t9=e=>{let t=t2(e);return 0x100000000*t4(e)+t},t7=e=>{tW(e,4);let t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},re=e=>{tW(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},rt=(e,t)=>{tW(e,t);let r="";for(let a=0;a{let t=t1(e),r=rt(e,4),a=8;1===t&&(t=t6(e),a=16);let i=t-a;return i<0?null:{name:r,totalSize:t,headerSize:a,contentSize:i}},ra=e=>t3(e)/65536,ri=e=>t3(e)/0x40000000,rn=e=>{let t=0;for(let r=0;r<4;r++){t<<=7;let r=tQ(e);if(t|=127&r,(128&r)==0)break}return t},rs=e=>{let t=tJ(e);return e.skip(2),t=Math.min(t,e.remainingLength),v.decode(tK(e,t))},ro=e=>{let t=rr(e);if(!t||"data"!==t.name||e.remainingLength<8)return null;let r=t1(e);e.skip(4);let a=tK(e,t.contentSize-8);switch(r){case 1:return v.decode(a);case 2:return new TextDecoder("utf-16be").decode(a);case 13:return new t$(a,"image/jpeg");case 14:return new t$(a,"image/png");case 27:return new t$(a,"image/bmp");default:return a}};class rl extends e6{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){let e=await this.getTracks();return Math.max(0,...await Promise.all(e.map(e=>e.computeDuration())))}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(e=>e.inputTrack.getCodecParameterString()));return tU({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>e.info?.type==="video"),hasAudio:this.tracks.some(e=>e.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 t=this.reader.requestSliceRange(e,8,16);if(t instanceof Promise&&(t=await t),!t)break;let r=e,a=rr(t);if(!a)break;if("ftyp"===a.name){let e=rt(t,4);this.isQuickTime="qt "===e}else if("moov"===a.name){let e=this.reader.requestSlice(t.filePos,a.contentSize);if(e instanceof Promise&&(e=await e),!e)break;for(let t of(this.moovSlice=e,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((e,t)=>Number(t.disposition.default)-Number(e.disposition.default)),this.tracks)){let e=t.editListPreviousSegmentDurations/this.movieTimescale;t.editListOffset-=Math.round(e*t.timescale)}break}e=r+a.totalSize}if(this.isFragmented&&null!==this.reader.fileSize){let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),p(e);let t=t1(e),r=this.reader.fileSize-t;if(r>=0&&r<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(r,8,16);if(e instanceof Promise&&(e=await e),e){let t=rr(e);if(t&&"mfra"===t.name){let r=this.reader.requestSlice(e.filePos,t.contentSize);r instanceof Promise&&(r=await r),r&&this.readContiguousBoxes(r)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=t,p(this.moovSlice);let r=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(r),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&ek.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){p(e.info?.type==="audio");let r=eE(e.info.codec),a=[],i=[];for(let n=0;ne.startIndex),u=t.sampleTimingEntries[c],d=N(t.sampleTimingEntries,l,e=>e.startIndex),h=t.sampleTimingEntries[d],m=u.startDecodeTimestamp+(o-u.startIndex)*u.delta,f=h.startDecodeTimestamp+(l-h.startIndex)*h.delta-m,p=b(a);p&&p.delta===f?p.count++:a.push({startIndex:s.startChunkIndex+n,startDecodeTimestamp:m,count:1,delta:f});let g=s.samplesPerChunk*r.sampleSize*e.info.numberOfChannels;i.push(g)}s.startSampleIndex=s.startChunkIndex,s.samplesPerChunk=1}t.sampleTimingEntries=a,t.sampleSizes=i}if(t.sampleCompositionTimeOffsets.length>0){for(let e of(t.presentationTimestamps=[],t.sampleTimingEntries))for(let r=0;re.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;ee.moofOffset===i.moofOffset);if(a)rg(t,a.timestamp);else{let e=N(r,i.moofOffset-1,e=>e.moofOffset);-1!==e&&rg(t,r[e].endTimestamp)}t.startTimestampIsFinal=!0}let a=N(r,t.startTimestamp,e=>e.startTimestamp);(-1===a||r[a].moofOffset!==i.moofOffset)&&r.splice(a+1,0,{moofOffset:i.moofOffset,startTimestamp:t.startTimestamp,endTimestamp:t.endTimestamp})}return i}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8;){let t=e.filePos,r=rr(e);if(!r)break;yield{boxInfo:r,slice:e},e.filePos=t+r.totalSize}}traverseBox(e){let t=e.filePos,r=rr(e);if(!r)return!1;let a=e.filePos,i=t+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"wave":this.readContiguousBoxes(e.slice(a,r.contentSize));break;case"mvhd":{let t=tQ(e);e.skip(3),1===t?(e.skip(16),this.movieTimescale=t1(e),this.movieDurationInTimescale=t6(e)):(e.skip(8),this.movieTimescale=t1(e),this.movieDurationInTimescale=t1(e))}break;case"trak":{let t={id:-1,demuxer:this,inputTrack:null,disposition:{...tH},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:"und",sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};this.currentTrack=t,this.readContiguousBoxes(e.slice(a,r.contentSize)),-1!==t.id&&-1!==t.timescale&&null!==t.info&&("video"===t.info.type&&-1!==t.info.width?(t.inputTrack=new tz(this.input,new ru(t)),this.tracks.push(t)):"audio"===t.info.type&&-1!==t.info.numberOfChannels&&(t.inputTrack=new tV(this.input,new rd(t)),this.tracks.push(t))),this.currentTrack=null}break;case"tkhd":{let t=this.currentTrack;if(!t)break;let r=tQ(e),a=tY(e);if(t.disposition.default=!!(1&a),0===r)e.skip(8),t.id=t1(e),e.skip(4),t.durationInMovieTimescale=t1(e);else if(1===r)e.skip(16),t.id=t1(e),e.skip(4),t.durationInMovieTimescale=t6(e);else throw Error(`Incorrect track header version ${r}.`);e.skip(16);let i=g(G(rb([ra(e),ra(e),ri(e),ra(e),ra(e),ri(e),ra(e),ra(e),ri(e)]),90));p(0===i||90===i||180===i||270===i),t.rotation=i}break;case"elst":{let t=this.currentTrack;if(!t)break;let r=tQ(e);e.skip(3);let a=!1,i=0,n=t1(e);for(let s=0;s0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&a))+t.languageCode,a>>=5;Z(t.languageCode)||(t.languageCode="und")}}break;case"hdlr":{let t=this.currentTrack;if(!t)break;e.skip(8);let r=rt(e,4);"vide"===r?t.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:"soun"===r&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let i=this.currentTrack;if(!i)break;i.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(a,r.contentSize))}break;case"stsd":{let t=this.currentTrack;if(!t||null===t.info||t.sampleTable)break;let r=tQ(e);e.skip(3);let a=t1(e);for(let i=0;i0){if(1===s)e.skip(4),l=8*t1(e),e.skip(8);else if(2===s){e.skip(4),c=re(e),o=t1(e),e.skip(4),l=t1(e);let r=t1(e);if(e.skip(8),"lpcm"===n){let e=l+7>>3,a=!!(1&r),i=!!(2&r),n=4&r?-1:0;l>0&&l<=64&&(a?32===l&&(t.info.codec=i?"pcm-f32be":"pcm-f32"):n&1<>4,chromaSubsampling:i>>1&7,videoFullRangeFlag:1&i,colourPrimaries:n,transferCharacteristics:s,matrixCoefficients:o}}break;case"av1C":{let t=this.currentTrack;if(!t)break;p(t.info?.type==="video"),e.skip(1);let r=tQ(e),a=r>>5,i=tQ(e),n=i>>6&1;t.info.av1CodecInfo={profile:a,level:31&r,tier:i>>7,bitDepth:2===a&&n?i>>5&1?12:10:n?10:8,monochrome:i>>4&1,chromaSubsamplingX:i>>3&1,chromaSubsamplingY:i>>2&1,chromaSamplePosition:3&i}}break;case"colr":{let t=this.currentTrack;if(!t||(p(t.info?.type==="video"),"nclx"!==rt(e,4)))break;let r=tJ(e),a=tJ(e),i=tJ(e),n=!!(128&tQ(e));t.info.colorSpace={primaries:I[r],transfer:E[a],matrix:A[i],fullRange:n}}break;case"esds":{let t=this.currentTrack;if(!t)break;p(t.info?.type==="audio"),e.skip(4),p(3===tQ(e)),rn(e),e.skip(2);let r=tQ(e);if((128&r)!=0&&e.skip(2),(64&r)!=0){let t=tQ(e);e.skip(t)}(32&r)!=0&&e.skip(2),p(4===tQ(e));let a=rn(e),i=e.filePos,n=tQ(e);if(64===n||103===n?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===n}):105===n||107===n?t.info.codec="mp3":221===n?t.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${n}) - discarding track.`),e.skip(12),a>e.filePos-i){p(5===tQ(e));let r=rn(e);if(t.info.codecDescription=tK(e,r),"aac"===t.info.codec){let e=eI(t.info.codecDescription);null!==e.numberOfChannels&&(t.info.numberOfChannels=e.numberOfChannels),null!==e.sampleRate&&(t.info.sampleRate=e.sampleRate)}}}break;case"enda":{let t=this.currentTrack;if(!t)break;p(t.info?.type==="audio"),255&tJ(e)&&("pcm-s16be"===t.info.codec?t.info.codec="pcm-s16":"pcm-s24be"===t.info.codec?t.info.codec="pcm-s24":"pcm-s32be"===t.info.codec?t.info.codec="pcm-s32":"pcm-f32be"===t.info.codec?t.info.codec="pcm-f32":"pcm-f64be"===t.info.codec&&(t.info.codec="pcm-f64"))}break;case"pcmC":{let t=this.currentTrack;if(!t)break;p(t.info?.type==="audio"),e.skip(4);let r=!!(1&tQ(e)),a=tQ(e);"pcm-s16be"===t.info.codec?r?16===a?t.info.codec="pcm-s16":24===a?t.info.codec="pcm-s24":32===a?t.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${a}.`),t.info.codec=null):16===a?t.info.codec="pcm-s16be":24===a?t.info.codec="pcm-s24be":32===a?t.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${a}.`),t.info.codec=null):"pcm-f32be"===t.info.codec&&(r?32===a?t.info.codec="pcm-f32":64===a?t.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${a}.`),t.info.codec=null):32===a?t.info.codec="pcm-f32be":64===a?t.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${a}.`),t.info.codec=null));break}case"dOps":{let t;let r=this.currentTrack;if(!r)break;p(r.info?.type==="audio"),e.skip(1);let a=tQ(e),i=tJ(e),n=t1(e),s=tZ(e),o=tQ(e);t=0!==o?tK(e,2+a):new Uint8Array(0);let l=new Uint8Array(19+t.byteLength),c=new DataView(l.buffer);c.setUint32(0,0x4f707573,!1),c.setUint32(4,0x48656164,!1),c.setUint8(8,1),c.setUint8(9,a),c.setUint16(10,i,!0),c.setUint32(12,n,!0),c.setInt16(16,s,!0),c.setUint8(18,o),l.set(t,19),r.info.codecDescription=l,r.info.numberOfChannels=a}break;case"dfLa":{let t=this.currentTrack;if(!t)break;p(t.info?.type==="audio"),e.skip(4);let r=e.filePos;for(;e.filePos>>12,i=(r>>9&7)+1;t.info.sampleRate=a,t.info.numberOfChannels=i,e.skip(20)}else e.skip(a);if(128&r)break}let a=e.filePos;e.filePos=r;let s=tK(e,a-r),o=new Uint8Array(4+s.byteLength);new DataView(o.buffer).setUint32(0,0x664c6143,!1),o.set(s,4),t.info.codecDescription=o}break;case"stts":{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let r=t1(e),a=0,i=0;for(let n=0;ne.id===r);if(!a)break;let i=t1(e),n=[tQ,tJ,tY,t1],s=n[(48&i)>>4],o=n[(12&i)>>2],l=n[3&i],c=t1(e);for(let r=0;re.timestamp-t.timestamp);for(let e=0;ee.id===r);if(!a)break;let i=this.fragmentTrackDefaults.find(e=>e.trackId===r);this.currentTrack=a,a.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:i?.defaultSampleDescriptionIndex??null,defaultSampleDuration:i?.defaultSampleDuration??null,defaultSampleSize:i?.defaultSampleSize??null,defaultSampleFlags:i?.defaultSampleFlags??null,startTimestamp:null},1&t?a.currentFragmentState.baseDataOffset=t6(e):131072&t&&(a.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),2&t&&(a.currentFragmentState.sampleDescriptionIndex=t1(e)),8&t&&(a.currentFragmentState.defaultSampleDuration=t1(e)),16&t&&(a.currentFragmentState.defaultSampleSize=t1(e)),32&t&&(a.currentFragmentState.defaultSampleFlags=t1(e)),65536&t&&(a.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let t=this.currentTrack;if(!t)break;p(t.currentFragmentState);let r=tQ(e);e.skip(3);let a=0===r?t1(e):t6(e);t.currentFragmentState.startTimestamp=a}break;case"trun":{let t=this.currentTrack;if(!t)break;if(p(this.currentFragment),p(t.currentFragmentState),this.currentFragment.trackData.has(t.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let r=tQ(e),a=tY(e),i=!!(256&a),n=!!(512&a),s=!!(1024&a),o=!!(2048&a),l=t1(e),c=t.currentFragmentState.baseDataOffset;1&a&&(c+=t3(e));let u=null;4&a&&(u=t1(e));let d=c;if(0===l){this.currentFragment.implicitBaseDataOffset=d;break}let h=0,m={track:t,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(t.id,m);for(let a=0;a({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let e=0;e0&&(this.metadataTags.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(this.metadataTags.tracksTotal??=r)}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){let e=S(a),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),r>0&&(this.metadataTags.tracksTotal??=r)}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){let e=S(a),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),r>0&&(this.metadataTags.discsTotal??=r)}}}}return e.filePos=i,!0}}class rc{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){let e=await this.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Q(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let r=this.mapTimestampIntoTimescale(e),a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=rh(a,r),n=await this.fetchPacketForSampleIndex(i,t);return rk(a)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let a=N(t.presentationTimestamps,r,e=>e.presentationTimestamp);return{sampleIndex:-1!==a?t.presentationTimestamps[a].sampleIndex:-1,correctSampleFound:-1!==a&&r{if(e===a.fragment){let t=e.trackData.get(this.internalTrack.id);if(a.sampleIndex+1{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let a=V(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=r);return{sampleIndex:-1!==a?t.presentationTimestamps[a].sampleIndex:-1,correctSampleFound:-1!==a&&r{if(e===a.fragment){let t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>a.sampleIndex);if(-1!==t)return{sampleIndex:t,correctSampleFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){let e=t.samples.findIndex(e=>e.isKeyFrame);return p(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){let r;if(-1===e)return null;let a=rf(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),e);if(!a)return null;if(t.metadataOnly)r=e7;else{let e=this.internalTrack.demuxer.reader.requestSlice(a.sampleOffset,a.sampleSize);e instanceof Promise&&(e=await e),p(e),r=tK(e,a.sampleSize)}let i=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,n=a.duration/this.internalTrack.timescale,s=new te(r,a.isKeyFrame?"key":"delta",i,n,e,a.sampleSize);return this.packetToSampleIndex.set(s,e),s}async fetchPacketInFragment(e,t,r){let a;if(-1===t)return null;let i=e.trackData.get(this.internalTrack.id).samples[t];if(p(i),r.metadataOnly)a=e7;else{let e=this.internalTrack.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);e instanceof Promise&&(e=await e),p(e),a=tK(e,i.byteSize)}let n=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,s=i.duration/this.internalTrack.timescale,o=new te(a,i.isKeyFrame?"key":"delta",n,s,e.moofOffset+t,i.byteSize);return this.packetToFragmentLocation.set(o,{fragment:e,sampleIndex:t}),o}async performFragmentedLookup(e,t,r,a,i){let n;let s=this.internalTrack.demuxer,o=null,l=null,c=-1;if(e){let{sampleIndex:r,correctSampleFound:a}=t(e);if(a)return this.fetchPacketInFragment(e,r,i);-1!==r&&(l=e,c=r)}let u=N(this.internalTrack.fragmentLookupTable,r,e=>e.timestamp),d=-1!==u?this.internalTrack.fragmentLookupTable[u]:null,h=N(this.internalTrack.fragmentPositionCache,r,e=>e.startTimestamp),m=-1!==h?this.internalTrack.fragmentPositionCache[h]:null,f=Math.max(d?.moofOffset??0,m?.moofOffset??0)||null;for(e?null===f||e.moofOffset>=f?(n=e.moofOffset+e.moofSize,o=e):n=f:n=f??0;;){if(o){let e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>a)break}let e=s.reader.requestSliceRange(n,8,16);if(e instanceof Promise&&(e=await e),!e)break;let r=n,u=rr(e);if(!u)break;if("moof"===u.name){let{sampleIndex:e,correctSampleFound:a}=t(o=await s.readFragment(r));if(a)return this.fetchPacketInFragment(o,e,i);-1!==e&&(l=o,c=e)}n=r+u.totalSize}if(d&&(!l||l.moofOffset{if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo){if("av1"===this.internalTrack.info.codec&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&eZ(e.data)}}else{let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&eJ(e.data)}return{codec:eS(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 rd extends rc{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:ev(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}let rh=(e,t)=>{if(e.presentationTimestamps){let r=N(e.presentationTimestamps,t,e=>e.presentationTimestamp);return -1===r?-1:e.presentationTimestamps[r].sampleIndex}{let r=N(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(-1===r)return -1;let a=e.sampleTimingEntries[r];return a.startIndex+Math.min(Math.floor((t-a.startDecodeTimestamp)/a.delta),a.count-1)}},rm=(e,t)=>{if(!e.keySampleIndices)return rh(e,t);if(e.presentationTimestamps){let r=N(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(-1===r)return -1;for(let t=r;t>=0;t--){let r=e.presentationTimestamps[t].sampleIndex;if(-1!==_(e.keySampleIndices,r,e=>e))return r}return -1}{let r=rh(e,t),a=N(e.keySampleIndices,r,e=>e);return e.keySampleIndices[a]??-1}},rf=(e,t)=>{let r=N(e.sampleTimingEntries,t,e=>e.startIndex),a=e.sampleTimingEntries[r];if(!a||a.startIndex+a.count<=t)return null;let i=a.startDecodeTimestamp+(t-a.startIndex)*a.delta,n=N(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),s=e.sampleCompositionTimeOffsets[n];s&&t-s.startIndexe.startSampleIndex),c=e.sampleToChunk[l];p(c);let u=c.startChunkIndex+Math.floor((t-c.startSampleIndex)/c.samplesPerChunk),d=e.chunkOffsets[u],h=c.startSampleIndex+(u-c.startChunkIndex)*c.samplesPerChunk,m=0,f=d;if(1===e.sampleSizes.length)f+=o*(t-h),m+=o*c.samplesPerChunk;else for(let r=h;re)}},rp=(e,t)=>{if(!e.keySampleIndices)return t+1;let r=N(e.keySampleIndices,t,e=>e);return e.keySampleIndices[r+1]??-1},rg=(e,t)=>{for(let r of(e.startTimestamp+=t,e.endTimestamp+=t,e.samples))r.presentationTimestamp+=t;for(let r of e.presentationTimestamps)r.presentationTimestamp+=t},rb=e=>{let[t,,,r]=e,a=Math.hypot(t,r),i=-(180/Math.PI*Math.atan2(r/a,t/a));return Number.isFinite(i)?i:0},rk=e=>0===e.sampleSizes.length;!function(e){e[e.EBML=0x1a45dfa3]="EBML",e[e.EBMLVersion=17030]="EBMLVersion",e[e.EBMLReadVersion=17143]="EBMLReadVersion",e[e.EBMLMaxIDLength=17138]="EBMLMaxIDLength",e[e.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",e[e.DocType=17026]="DocType",e[e.DocTypeVersion=17031]="DocTypeVersion",e[e.DocTypeReadVersion=17029]="DocTypeReadVersion",e[e.Void=236]="Void",e[e.Segment=0x18538067]="Segment",e[e.SeekHead=0x114d9b74]="SeekHead",e[e.Seek=19899]="Seek",e[e.SeekID=21419]="SeekID",e[e.SeekPosition=21420]="SeekPosition",e[e.Duration=17545]="Duration",e[e.Info=0x1549a966]="Info",e[e.TimestampScale=2807729]="TimestampScale",e[e.MuxingApp=19840]="MuxingApp",e[e.WritingApp=22337]="WritingApp",e[e.Tracks=0x1654ae6b]="Tracks",e[e.TrackEntry=174]="TrackEntry",e[e.TrackNumber=215]="TrackNumber",e[e.TrackUID=29637]="TrackUID",e[e.TrackType=131]="TrackType",e[e.FlagEnabled=185]="FlagEnabled",e[e.FlagDefault=136]="FlagDefault",e[e.FlagForced=21930]="FlagForced",e[e.FlagOriginal=21934]="FlagOriginal",e[e.FlagHearingImpaired=21931]="FlagHearingImpaired",e[e.FlagVisualImpaired=21932]="FlagVisualImpaired",e[e.FlagCommentary=21935]="FlagCommentary",e[e.FlagLacing=156]="FlagLacing",e[e.Name=21358]="Name",e[e.Language=2274716]="Language",e[e.LanguageBCP47=2274717]="LanguageBCP47",e[e.CodecID=134]="CodecID",e[e.CodecPrivate=25506]="CodecPrivate",e[e.CodecDelay=22186]="CodecDelay",e[e.SeekPreRoll=22203]="SeekPreRoll",e[e.DefaultDuration=2352003]="DefaultDuration",e[e.Video=224]="Video",e[e.PixelWidth=176]="PixelWidth",e[e.PixelHeight=186]="PixelHeight",e[e.AlphaMode=21440]="AlphaMode",e[e.Audio=225]="Audio",e[e.SamplingFrequency=181]="SamplingFrequency",e[e.Channels=159]="Channels",e[e.BitDepth=25188]="BitDepth",e[e.SimpleBlock=163]="SimpleBlock",e[e.BlockGroup=160]="BlockGroup",e[e.Block=161]="Block",e[e.BlockAdditions=30113]="BlockAdditions",e[e.BlockMore=166]="BlockMore",e[e.BlockAdditional=165]="BlockAdditional",e[e.BlockAddID=238]="BlockAddID",e[e.BlockDuration=155]="BlockDuration",e[e.ReferenceBlock=251]="ReferenceBlock",e[e.Cluster=0x1f43b675]="Cluster",e[e.Timestamp=231]="Timestamp",e[e.Cues=0x1c53bb6b]="Cues",e[e.CuePoint=187]="CuePoint",e[e.CueTime=179]="CueTime",e[e.CueTrackPositions=183]="CueTrackPositions",e[e.CueTrack=247]="CueTrack",e[e.CueClusterPosition=241]="CueClusterPosition",e[e.Colour=21936]="Colour",e[e.MatrixCoefficients=21937]="MatrixCoefficients",e[e.TransferCharacteristics=21946]="TransferCharacteristics",e[e.Primaries=21947]="Primaries",e[e.Range=21945]="Range",e[e.Projection=30320]="Projection",e[e.ProjectionType=30321]="ProjectionType",e[e.ProjectionPoseRoll=30325]="ProjectionPoseRoll",e[e.Attachments=0x1941a469]="Attachments",e[e.AttachedFile=24999]="AttachedFile",e[e.FileDescription=18046]="FileDescription",e[e.FileName=18030]="FileName",e[e.FileMediaType=18016]="FileMediaType",e[e.FileData=18012]="FileData",e[e.FileUID=18094]="FileUID",e[e.Chapters=0x1043a770]="Chapters",e[e.Tags=0x1254c367]="Tags",e[e.Tag=29555]="Tag",e[e.Targets=25536]="Targets",e[e.TargetTypeValue=26826]="TargetTypeValue",e[e.TargetType=25546]="TargetType",e[e.TagTrackUID=25541]="TagTrackUID",e[e.TagEditionUID=25545]="TagEditionUID",e[e.TagChapterUID=25540]="TagChapterUID",e[e.TagAttachmentUID=25542]="TagAttachmentUID",e[e.SimpleTag=26568]="SimpleTag",e[e.TagName=17827]="TagName",e[e.TagLanguage=17530]="TagLanguage",e[e.TagString=17543]="TagString",e[e.TagBinary=17541]="TagBinary",e[e.ContentEncodings=28032]="ContentEncodings",e[e.ContentEncoding=25152]="ContentEncoding",e[e.ContentEncodingOrder=20529]="ContentEncodingOrder",e[e.ContentEncodingScope=20530]="ContentEncodingScope",e[e.ContentCompression=20532]="ContentCompression",e[e.ContentCompAlgo=16980]="ContentCompAlgo",e[e.ContentCompSettings=16981]="ContentCompSettings",e[e.ContentEncryption=20533]="ContentEncryption"}(s||(s={}));let ry=[s.EBML,s.Segment],rw=[s.SeekHead,s.Info,s.Cluster,s.Tracks,s.Cues,s.Attachments,s.Chapters,s.Tags],rT=[...ry,...rw],rS=e=>{let t=tQ(e);if(e.skip(-1),0===t)return null;let r=1,a=128;for(;(t&a)==0;)r++,a>>=1;return r},rv=e=>{let t=tQ(e);if(0===t)return null;let r=1,a=128;for(;(t&a)==0;)r++,a>>=1;let i=t&a-1;for(let t=1;t{if(t<1||t>8)throw Error("Bad unsigned int size "+t);let r=0;for(let a=0;a{if(t<1)throw Error("Bad unsigned int size "+t);let r=0n;for(let a=0;a{let t=rS(e);return null===t?null:rx(e,t)},rC=e=>{let t=tQ(e);return 255===t?t=null:(e.skip(-1),0x100000000000000===(t=rv(e))&&(t=null)),t},rE=e=>{let t=rI(e);return null===t?null:{id:t,size:rC(e)}},rF=(e,t)=>{let r=tK(e,t),a=0;for(;a{let r=tK(e,t),a=0;for(;a{if(0===t)return 0;if(4!==t&&8!==t)throw Error("Bad float size "+t);return 4===t?t7(e):re(e)},rD=async(e,t,r,a)=>{let i=new Set(r),n=t;for(;null===a||nn?a:n,found:!1}},rR=async(e,t,r,a)=>{let i=new Set(r),n=t;for(;n{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");if(e.codecStrings.length>0){let r=[...new Set(e.codecStrings.filter(Boolean))];t+=`; codecs="${r.join(", ")}"`}return t};!function(e){e[e.None=0]="None",e[e.Xiph=1]="Xiph",e[e.FixedSize=2]="FixedSize",e[e.Ebml=3]="Ebml"}(o||(o={})),function(e){e[e.Block=1]="Block",e[e.Private=2]="Private",e[e.Next=4]="Next"}(l||(l={})),function(e){e[e.Zlib=0]="Zlib",e[e.Bzlib=1]="Bzlib",e[e.lzo1x=2]="lzo1x",e[e.HeaderStripping=3]="HeaderStripping"}(c||(c={}));let rL=[{id:s.SeekHead,flag:"seekHeadSeen"},{id:s.Info,flag:"infoSeen"},{id:s.Tracks,flag:"tracksSeen"},{id:s.Cues,flag:"cuesSeen"}];class rO extends e6{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks();return Math.max(0,...await Promise.all(e.map(e=>e.computeDuration())))}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(e=>e.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),t=await Promise.all(e.map(e=>e.getCodecParameterString()));return rN({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>e.info?.type==="video")),hasAudio:this.segments.some(e=>e.tracks.some(e=>e.info?.type==="audio")),codecStrings:t.filter(Boolean)})}async getMetadataTags(){for(let e of(await this.readMetadata(),this.segments))e.metadataTagsCollected||(null!==this.reader.fileSize&&await this.loadSegmentMetadata(e),e.metadataTagsCollected=!0);let e={};for(let t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,16);if(t instanceof Promise&&(t=await t),!t)break;let r=rE(t);if(!r)break;let a=r.id,i=r.size,n=t.filePos;if(a===s.EBML){r_(i);let e=this.reader.requestSlice(n,i);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(a===s.Segment){if(await this.readSegment(n,i),null===i||null===this.reader.fileSize)break}else if(a===s.Cluster){if(null===this.reader.fileSize)break;null===i&&(i=(await rD(this.reader,n,rT,this.reader.fileSize)).pos-n);let e=b(this.segments);e&&(e.elementEndPos=n+i)}r_(i),e=n+i}})()}async readSegment(e,t){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:null===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=e;for(;null===this.currentSegment.elementEndPos||re.id===i);if(-1!==l){let e=rL[l].flag;this.currentSegment[e]=!0,r_(n);let t=this.reader.requestSlice(o,n);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(i===s.Tags||i===s.Attachments){i===s.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,r_(n);let e=this.reader.requestSlice(o,n);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(i===s.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(null===n)break;r=o+n}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(let t of this.currentSegment.seekEntries){let r=rL.find(e=>e.id===t.id);if(!r||this.currentSegment[r.flag])continue;let a=this.reader.requestSliceRange(e+t.segmentPosition,2,16);if(a instanceof Promise&&(a=await a),!a)continue;let i=rE(a);if(!i)continue;let{id:n,size:s}=i;if(n!==r.id)continue;r_(s),this.currentSegment[r.flag]=!0;let o=this.reader.requestSlice(a.filePos,s);o instanceof Promise&&(o=await o),o&&this.readContiguousElements(o)}-1===this.currentSegment.timestampScale&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3),this.currentSegment.tracks.sort((e,t)=>Number(t.disposition.default)-Number(e.disposition.default));let a=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(let e of this.currentSegment.cuePoints){let t=a.get(e.trackId);t&&t.cuePoints.push(e)}for(let e of this.currentSegment.tracks){e.cuePoints.sort((e,t)=>e.time-t.time);for(let t=0;tn&&(n=e.cuePoints.length,i=e);for(let e of this.currentSegment.tracks)0===e.cuePoints.length&&(e.cuePoints=i.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let r=this.reader.requestSliceRange(e,2,16);r instanceof Promise&&(r=await r),p(r);let a=rE(r);p(a),p(a.id===s.Cluster);let i=a.size,n=r.filePos;null===i&&(i=(await rD(this.reader,n,rT,t.elementEndPos)).pos-n);let l=this.reader.requestSlice(n,i);l instanceof Promise&&(l=await l);let c={segment:t,elementStartPos:e,elementEndPos:n+i,dataStartPos:n,timestamp:-1,trackData:new Map};if(this.currentCluster=c,l){let e=this.readContiguousElements(l,rT);c.elementEndPos=e}for(let[,t]of c.trackData){let r=t.track;p(t.blocks.length>0);let a=!1;for(let e=0;e({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));let i=t.blocks[t.presentationTimestamps[0].blockIndex],n=t.blocks[b(t.presentationTimestamps).blockIndex];t.startTimestamp=i.timestamp,t.endTimestamp=n.timestamp+n.duration;let s=N(r.clusterPositionCache,t.startTimestamp,e=>e.startTimestamp);(-1===s||r.clusterPositionCache[s].elementStartPos!==e)&&r.clusterPositionCache.splice(s+1,0,{elementStartPos:c.elementStartPos,startTimestamp:t.startTimestamp})}return t.lastReadCluster=c,c}getTrackDataInCluster(e,t){let r=e.trackData.get(t);if(!r){let a=e.segment.tracks.find(e=>e.id===t);if(!a)return null;r={track:a,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,r)}return r}expandLacedBlocks(e,t){for(let r=0;re.data?.type!=="decompress"||e.scope!==l.Block||e.data.algorithm!==c.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){let e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){this.currentTrack.codecId===rM.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===rM.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===rM.vp8?this.currentTrack.info.codec="vp8":t===rM.vp9?this.currentTrack.info.codec="vp9":t===rM.av1&&(this.currentTrack.info.codec="av1");let e=this.currentTrack,r=new tz(this.input,new rV(e));this.currentTrack.inputTrack=r,this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type&&-1!==this.currentTrack.info.numberOfChannels&&-1!==this.currentTrack.info.sampleRate){t===rM.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===rM.mp3?this.currentTrack.info.codec="mp3":t===rM.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=48e3):t===rM.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===rM.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));let e=this.currentTrack,r=new tV(this.input,new rU(e));this.currentTrack.inputTrack=r,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case s.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=rx(e,i);break;case s.TrackType:{if(!this.currentTrack)break;let t=rx(e,i);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case s.FlagEnabled:if(!this.currentTrack)break;rx(e,i)||(this.currentSegment.tracks.pop(),this.currentTrack=null);break;case s.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!rx(e,i);break;case s.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!rx(e,i);break;case s.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!rx(e,i);break;case s.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!rx(e,i);break;case s.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!rx(e,i);break;case s.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!rx(e,i);break;case s.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=rF(e,i);break;case s.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=tK(e,i);break;case s.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*rx(e,i)/1e9;break;case s.Name:if(!this.currentTrack)break;this.currentTrack.name=rA(e,i);break;case s.Language:if(!this.currentTrack||"und"!==this.currentTrack.languageCode)break;this.currentTrack.languageCode=rF(e,i),Z(this.currentTrack.languageCode)||(this.currentTrack.languageCode="und");break;case s.LanguageBCP47:{if(!this.currentTrack)break;let t=rF(e,i).split("-")[0];t?this.currentTrack.languageCode=t:this.currentTrack.languageCode="und"}break;case s.Video:if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(n,i));break;case s.PixelWidth:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=rx(e,i);break;case s.PixelHeight:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=rx(e,i);break;case s.AlphaMode:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=1===rx(e,i);break;case s.Colour:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(n,i));break;case s.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let t=A[rx(e,i)]??null;this.currentTrack.info.colorSpace.matrix=t}break;case s.Range:if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=2===rx(e,i);break;case s.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let t=E[rx(e,i)]??null;this.currentTrack.info.colorSpace.transfer=t}break;case s.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let t=I[rx(e,i)]??null;this.currentTrack.info.colorSpace.primaries=t}break;case s.Projection:if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(n,i));break;case s.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let t=rB(e,i);try{this.currentTrack.info.rotation=g(-t)}catch{}}break;case s.Audio:if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(n,i));break;case s.SamplingFrequency:if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=rB(e,i);break;case s.Channels:if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=rx(e,i);break;case s.BitDepth:if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=rx(e,i);break;case s.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(n,i)),this.currentCueTime=null;break;case s.CueTime:this.currentCueTime=rx(e,i);break;case s.CueTrackPositions:{if(null===this.currentCueTime)break;p(this.currentSegment);let t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(n,i)),(-1===t.trackId||-1===t.clusterPosition)&&this.currentSegment.cuePoints.pop()}break;case s.CueTrack:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=rx(e,i)}break;case s.CueClusterPosition:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;p(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+rx(e,i)}break;case s.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=rx(e,i);break;case s.SimpleBlock:{if(!this.currentCluster)break;let t=rv(e);if(null===t)break;let r=this.getTrackDataInCluster(this.currentCluster,t);if(!r)break;let a=tZ(e),s=tQ(e),o=!!(128&s);r.track.info?.type==="audio"&&r.track.info.codec&&(o=!0);let l=tK(e,i-(e.filePos-n)),c=r.track.decodingInstructions.length>0;r.blocks.push({timestamp:a,duration:0,isKeyFrame:o,data:l,lacing:s>>1&3,decoded:!c,mainAdditional:null})}break;case s.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(n,i)),this.currentBlock=null;break;case s.Block:{if(!this.currentCluster)break;let t=rv(e);if(null===t)break;let r=this.getTrackDataInCluster(this.currentCluster,t);if(!r)break;let a=tZ(e),s=tQ(e),o=tK(e,i-(e.filePos-n)),l=r.track.decodingInstructions.length>0;this.currentBlock={timestamp:a,duration:0,isKeyFrame:!0,data:o,lacing:s>>1&3,decoded:!l,mainAdditional:null},r.blocks.push(this.currentBlock)}break;case s.BlockAdditions:this.readContiguousElements(e.slice(n,i));break;case s.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(n,i)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case s.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=tK(e,i);break;case s.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=rx(e,i);break;case s.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=rx(e,i);break;case s.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case s.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(n,i));break;case s.Targets:this.readContiguousElements(e.slice(n,i));break;case s.TargetTypeValue:50!==rx(e,i)&&(this.currentTagTargetIsMovie=!1);break;case s.TagTrackUID:case s.TagEditionUID:case s.TagChapterUID:case s.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case s.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(n,i));break;case s.TagName:this.currentSimpleTagName=rA(e,i);break;case s.TagString:{if(!this.currentSimpleTagName)break;let t=rA(e,i);this.processTagValue(this.currentSimpleTagName,t)}break;case s.TagBinary:{if(!this.currentSimpleTagName)break;let t=tK(e,i);this.processTagValue(this.currentSimpleTagName,t)}break;case s.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(n,i));let t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??={},t.raw[this.currentAttachedFile.fileUid.toString()]=new tj(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let e=this.currentAttachedFile.fileName,r="unknown";if(e){let t=e.toLowerCase();t.startsWith("cover.")?r="coverFront":t.startsWith("back.")&&(r="coverBack")}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:r,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case s.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=rP(e,i);break;case s.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=rA(e,i);break;case s.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=rF(e,i);break;case s.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=tK(e,i);break;case s.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=rA(e,i);break;case s.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(n,i)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case s.ContentEncoding:this.currentDecodingInstruction={order:0,scope:l.Block,data:null},this.readContiguousElements(e.slice(n,i)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case s.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=rx(e,i);break;case s.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=rx(e,i);break;case s.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:c.Zlib,settings:null},this.readContiguousElements(e.slice(n,i));break;case s.ContentCompAlgo:if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=rx(e,i);break;case s.ContentCompSettings:if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=tK(e,i);break;case s.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=n+i,!0}decodeBlockData(e,t){p(e.decodingInstructions.length>0);let r=t;for(let t of e.decodingInstructions)if(p(t.data),"decompress"===t.data.type&&t.data.algorithm===c.HeaderStripping&&t.data.settings&&t.data.settings.length>0){let e=t.data.settings,a=new Uint8Array(e.length+r.length);a.set(e,0),a.set(r,e.length),r=a}return r}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let r=this.currentSegment.metadataTags;if(r.raw??={},r.raw[e]??=t,"string"==typeof t)switch(e.toLowerCase()){case"title":r.title??=t;break;case"description":r.description??=t;break;case"artist":r.artist??=t;break;case"album":r.album??=t;break;case"album_artist":r.albumArtist??=t;break;case"genre":r.genre??=t;break;case"comment":r.comment??=t;break;case"lyrics":r.lyrics??=t;break;case"date":{let e=new Date(t);Number.isNaN(e.getTime())||(r.date??=e)}break;case"track_number":case"part_number":{let e=t.split("/"),a=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(a)&&a>0&&(r.trackNumber??=a),i&&Number.isInteger(i)&&i>0&&(r.tracksTotal??=i)}break;case"disc_number":case"disc":{let e=t.split("/"),a=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(a)&&a>0&&(r.discNumber??=a),i&&Number.isInteger(i)&&i>0&&(r.discsTotal??=i)}}}}class rz{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){let e=await this.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Q(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let r=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let a=N(t.presentationTimestamps,r,e=>e.timestamp);return{blockIndex:-1!==a?t.presentationTimestamps[a].blockIndex:-1,correctBlockFound:-1!==a&&r{if(e===r.cluster){let t=e.trackData.get(this.internalTrack.id);if(r.blockIndex+1{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let a=V(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=r);return{blockIndex:-1!==a?t.presentationTimestamps[a].blockIndex:-1,correctBlockFound:-1!==a&&r{if(e===r.cluster){let t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>r.blockIndex);if(-1!==t)return{blockIndex:t,correctBlockFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){let e=t.blocks.findIndex(e=>e.isKeyFrame);return p(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){if(-1===t)return null;let a=e.trackData.get(this.internalTrack.id).blocks[t];p(a),a.decoded||(a.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,a.data),a.decoded=!0);let i=r.metadataOnly?e7:a.data,n=a.timestamp/this.internalTrack.segment.timestampFactor,s=a.duration/this.internalTrack.segment.timestampFactor,o={};a.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(o.alpha=r.metadataOnly?e7:a.mainAdditional,o.alphaByteLength=a.mainAdditional.byteLength);let l=new te(i,a.isKeyFrame?"key":"delta",n,s,e.dataStartPos+t,a.data.byteLength,o);return this.packetToClusterLocation.set(l,{cluster:e,blockIndex:t}),l}async performClusterLookup(e,t,r,a,i){let n;let{demuxer:o,segment:l}=this.internalTrack,c=null,u=null,d=-1;if(e){let{blockIndex:r,correctBlockFound:a}=t(e);if(a)return this.fetchPacketInCluster(e,r,i);-1!==r&&(u=e,d=r)}let h=N(this.internalTrack.cuePoints,r,e=>e.time),m=-1!==h?this.internalTrack.cuePoints[h]:null,f=N(this.internalTrack.clusterPositionCache,r,e=>e.startTimestamp),g=-1!==f?this.internalTrack.clusterPositionCache[f]:null,b=Math.max(m?.clusterPosition??0,g?.elementStartPos??0)||null;for(e?null===b||e.elementStartPos>=b?(n=e.elementEndPos,c=e):n=b:n=b??l.clusterSeekStartPos;null===l.elementEndPos||n<=l.elementEndPos-2;){if(c){let e=c.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>a)break}let e=o.reader.requestSliceRange(n,2,16);if(e instanceof Promise&&(e=await e),!e)break;let r=n,h=rE(e);if(!h||!rw.includes(h.id)&&h.id!==s.Void){let e=await rR(o.reader,r,rw,Math.min(l.elementEndPos??1/0,r+0xa00000));if(e){n=e;continue}break}let m=h.id,f=h.size,g=e.filePos;if(m===s.Cluster){f=(c=await o.readCluster(r,l)).elementEndPos-g;let{blockIndex:e,correctBlockFound:a}=t(c);if(a)return this.fetchPacketInCluster(c,e,i);-1!==e&&(u=c,d=e)}null===f&&(p(m!==s.Cluster),f=(await rD(o.reader,g,rT,l.elementEndPos)).pos-g);let b=g+f;if(null===l.elementEndPos){let e=o.reader.requestSliceRange(b,2,16);if(e instanceof Promise&&(e=await e),!e)break;if(rI(e)===s.Segment){l.elementEndPos=b;break}}n=b}if(m&&(!u||u.elementStartPos{let e=null;return"vp9"!==this.internalTrack.info.codec&&"av1"!==this.internalTrack.info.codec&&("avc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)&&("hevc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)||(e=await this.getFirstPacket({})),{codec:eS({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:"avc"===this.internalTrack.info.codec&&e?eO(e.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&e?ej(e.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&e?eJ(e.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&e?eZ(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 rU extends rz{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:ev({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}}let r$=[44100,48e3,32e3],rj=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],rH=(e,t,r,a,i)=>0===t?0:1===t?Math.floor(144*r/(a<3===e?3===t?21:36:3===t?13:21,rX=(e,t)=>{let r;let a=e>>>24,i=e>>>16&255,n=e>>>8&255,s=255&e;if(255!==a&&255!==i&&255!==n&&255!==s)return{header:null,bytesAdvanced:4};if(255!==a||(224&i)!=224)return{header:null,bytesAdvanced:1};let o=0,l=0;16&i?o=8&i?0:1:(o=1,l=1);let c=i>>3&3,u=i>>1&3,d=(n>>2&3)%3,h=rj[64*o+16*u+(n>>4&15)];if(-1===h)return{header:null,bytesAdvanced:1};let m=1e3*h,f=r$[d]>>o+l,p=rH(o,u,m,f,n>>1&1);return null!==t&&t>6&3,modeExtension:s>>4&3,copyright:s>>3&1,original:s>>2&1,emphasis:3&s,audioSamplesInFrame:r},bytesAdvanced:1})},rW=e=>{let t=0x7f000000,r=0;for(;0!==t;)r>>=1,r|=e&t,t>>=8;return r};!function(e){e[e.Unsynchronisation=128]="Unsynchronisation",e[e.ExtendedHeader=64]="ExtendedHeader",e[e.ExperimentalIndicator=32]="ExperimentalIndicator",e[e.Footer=16]="Footer"}(u||(u={})),function(e){e[e.ISO_8859_1=0]="ISO_8859_1",e[e.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",e[e.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",e[e.UTF_8=3]="UTF_8"}(d||(d={}));let rK=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],rQ=(e,t)=>{let r;let a=e.filePos;t.raw??={},t.raw.TAG??=tK(e,125),e.filePos=a;let i=rG(e,30);i&&(t.title??=i);let n=rG(e,30);n&&(t.artist??=n);let s=rG(e,30);s&&(t.album??=s);let o=Number.parseInt(rG(e,4),10);Number.isInteger(o)&&o>0&&(t.date??=new Date(o,0,1));let l=tK(e,30);if(0===l[28]&&0!==l[29]){let a=l[29];a>0&&(t.trackNumber??=a),e.skip(-30),r=rG(e,28),e.skip(2)}else e.skip(-30),r=rG(e,30);r&&(t.comment??=r);let c=tQ(e);c{let r=tK(e,t),a=em(r.indexOf(0),r.length),i=r.subarray(0,a),n="";for(let e=0;e{let t=e.filePos,r=rt(e,3),a=tQ(e),i=tQ(e),n=tQ(e),s=t1(e);return"ID3"!==r||255===a||255===i||(0x80808080&s)!=0?(e.filePos=t,null):{majorVersion:a,revision:i,flags:n,size:rW(s)}},rY=(e,t,r)=>{if(![2,3,4].includes(t.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let a=tK(e,t.size),i=new rZ(t,a);if(t.flags&u.Footer&&i.removeFooter(),t.flags&u.Unsynchronisation&&3===t.majorVersion&&i.ununsynchronizeAll(),t.flags&u.ExtendedHeader){let e=i.readU32();3===t.majorVersion?i.pos+=e:i.pos+=e-4}for(;i.pos<=i.bytes.length-i.frameHeaderSize();){let e=i.readId3V2Frame();if(!e)break;let a=i.pos,n=i.pos+e.size,s=!1,o=!1,l=!1;if(3===t.majorVersion?(s=!!(64&e.flags),o=!!(128&e.flags)):4===t.majorVersion&&(s=!!(4&e.flags),o=!!(8&e.flags),l=!!(2&e.flags)||!!(t.flags&u.Unsynchronisation)),s){console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),i.pos=n;continue}if(o){console.warn(`Skipping compressed ID3v2 frame ${e.id}`),i.pos=n;continue}switch(l&&i.ununsynchronizeRegion(i.pos,n),r.raw??={},"T"===e.id[0]?r.raw[e.id]??=i.readId3V2EncodingAndText(n):r.raw[e.id]??=i.readBytes(e.size),i.pos=a,e.id){case"TIT2":case"TT2":r.title??=i.readId3V2EncodingAndText(n);break;case"TIT3":case"TT3":r.description??=i.readId3V2EncodingAndText(n);break;case"TPE1":case"TP1":r.artist??=i.readId3V2EncodingAndText(n);break;case"TALB":case"TAL":r.album??=i.readId3V2EncodingAndText(n);break;case"TPE2":case"TP2":r.albumArtist??=i.readId3V2EncodingAndText(n);break;case"TRCK":case"TRK":{let e=i.readId3V2EncodingAndText(n).split("/"),t=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(r.trackNumber??=t),a&&Number.isInteger(a)&&a>0&&(r.tracksTotal??=a)}break;case"TPOS":case"TPA":{let e=i.readId3V2EncodingAndText(n).split("/"),t=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(r.discNumber??=t),a&&Number.isInteger(a)&&a>0&&(r.discsTotal??=a)}break;case"TCON":case"TCO":{let e=i.readId3V2EncodingAndText(n),t=/^\((\d+)\)/.exec(e);if(t){let e=Number.parseInt(t[1]);if(void 0!==rK[e]){r.genre??=rK[e];break}}if(t=/^\d+$/.exec(e)){let e=Number.parseInt(t[0]);if(void 0!==rK[e]){r.genre??=rK[e];break}}r.genre??=e}break;case"TDRC":case"TDAT":{let e=new Date(i.readId3V2EncodingAndText(n));Number.isNaN(e.getTime())||(r.date??=e)}break;case"TYER":case"TYE":{let e=Number.parseInt(i.readId3V2EncodingAndText(n),10);Number.isInteger(e)&&(r.date??=new Date(e,0,1))}break;case"USLT":case"ULT":{let e=i.readU8();i.pos+=3,i.readId3V2Text(e,n),r.lyrics??=i.readId3V2Text(e,n)}break;case"COMM":case"COM":{let e=i.readU8();i.pos+=3,i.readId3V2Text(e,n),r.comment??=i.readId3V2Text(e,n)}break;case"APIC":case"PIC":{let e;let a=i.readId3V2TextEncoding();if(2===t.majorVersion){let t=i.readAscii(3);e="PNG"===t?"image/png":"JPG"===t?"image/jpeg":"image/*"}else e=i.readId3V2Text(a,n);let s=i.readU8(),o=i.readId3V2Text(a,n).trimEnd(),l=n-i.pos;if(l>=0){let t=i.readBytes(l);r.images||(r.images=[]),r.images.push({data:t,mimeType:e,kind:3===s?"coverFront":4===s?"coverBack":"unknown",description:o})}}break;default:i.pos+=e.size}i.pos=n}};class rZ{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return 2===this.header.majorVersion?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t{let t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;let t=this.readAscii(4);if("\0\0\0\0"!==t&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!n(r)){let e=4===this.header.majorVersion?t:rW(t);n(e)&&(r=e)}return this.pos=i,{id:e,size:r,flags:a}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let r=this.pos,a=this.readBytes(t-this.pos);switch(e){case d.ISO_8859_1:{let e="";for(let t=0;t0===e&&0===a[t+1]&&t%2==0),a.length);return this.pos=r+Math.min(t+2,a.length),e.decode(a.subarray(2,t))}if(254===a[0]&&255===a[1]){let e=new TextDecoder("utf-16be"),t=em(a.findIndex((e,t)=>0===e&&0===a[t+1]&&t%2==0),a.length);return this.pos=r+Math.min(t+2,a.length),e.decode(a.subarray(2,t))}{let e=em(a.findIndex(e=>0===e),a.length);return this.pos=r+Math.min(e+1,a.length),v.decode(a.subarray(0,e))}case d.UTF_16_BE_NO_BOM:{let e=new TextDecoder("utf-16be"),t=em(a.findIndex((e,t)=>0===e&&0===a[t+1]&&t%2==0),a.length);return this.pos=r+Math.min(t+2,a.length),e.decode(a.subarray(0,t))}case d.UTF_8:{let e=em(a.findIndex(e=>0===e),a.length);return this.pos=r+Math.min(e+1,a.length),v.decode(a.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}let r0=async(e,t,r)=>{let a=t;for(;null===r||a{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw Error("No valid MP3 frame found.");this.tracks=[new tV(this.input,new r2(this))]})()}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=rJ(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=await r0(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let r=rq(t.mpegVersionId,t.channel),a=this.reader.requestSlice(e.startPos+r,4);if(a instanceof Promise&&(a=await a),a){let e=t1(a);if(0x58696e67===e||0x496e666f===e)return}this.firstFrameHeader||(this.firstFrameHeader=t),t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);let i=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,n={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:i,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(n),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return p(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let r=this.reader.requestSlice(e,10);if(r instanceof Promise&&(r=await r),!r)break;let a=rJ(r);if(!a)break;t=!0;let i=this.reader.requestSlice(r.filePos,a.size);if(i instanceof Promise&&(i=await i),!i)break;rY(i,a,this.metadataTags),e=r.filePos+a.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=128){let e=this.reader.requestSlice(this.reader.fileSize-128,128);e instanceof Promise&&(e=await e),p(e);let t=rt(e,3);"TAG"===t&&rQ(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class r2{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return p(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return"und"}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return p(this.demuxer.firstFrameHeader),3===this.demuxer.firstFrameHeader.channel?1:2}getSampleRate(){return p(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...tH}}async getDecoderConfig(){return p(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:3===this.demuxer.firstFrameHeader.channel?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){let r;if(-1===e)return null;let a=this.demuxer.loadedSamples[e];if(!a)return null;if(t.metadataOnly)r=e7;else{let e=this.demuxer.reader.requestSlice(a.dataStart,a.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=tK(e,a.dataSize)}return new te(r,"key",a.timestamp,a.duration,e,a.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let r=_(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===r)throw Error("Packet was not created from this track.");let a=r+1;for(;a>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(a,t)}finally{r()}}async getPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{for(;;){let r=N(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===r&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||r>=0&&r+1>>0&0xffffffff}let r4=e=>{let t=S(e),r=t.getUint32(22,!0);t.setUint32(22,0,!0);let a=0;for(let t=0;t>>24^e[t]])>>>0;return t.setUint32(22,r,!0),a},r8=(e,t,r)=>{let a=0,i=null;if(e.length>0){if("vorbis"===t.codec){p(t.vorbisInfo);let n=(1<>1;if(s>=t.vorbisInfo.modeBlockflags.length)throw Error("Invalid mode number.");let o=r,l=t.vorbisInfo.modeBlockflags[s];if(i=t.vorbisInfo.blocksizes[l],1===l){let r=e[0]&(1|n)+1?1:0;o=t.vorbisInfo.blocksizes[r]}a=null!==o?o+i>>2:0}else"opus"===t.codec&&(a=e2(e).durationInSamples)}return{durationInSamples:a,vorbisBlockSize:i}},r6=e=>{let t="audio/ogg";if(e.codecStrings){let r=[...new Set(e.codecStrings)];t+=`; codecs="${r.join(", ")}"`}return t},r5=e=>{let t=e.filePos;if(0x5367674f!==t2(e))return null;e.skip(1);let r=tQ(e),a=t9(e),i=t2(e),n=t2(e),s=t2(e),o=tQ(e),l=new Uint8Array(o);for(let t=0;te+t,0);return{headerStartPos:t,totalSize:c+u,dataStartPos:t+c,dataSize:u,headerType:r,granulePosition:a,serialNumber:i,sequenceNumber:n,checksum:s,lacingValues:l}},r9=(e,t)=>{for(;e.filePos>>8&255,i=t>>>16&255,n=t>>>24&255;if(79===r||79===a||79===i||79===n){if(e.skip(-4),0x5367674f===t)return!0;e.skip(1)}}return!1};class r7 extends e6{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,27,282);if(t instanceof Promise&&(t=await t),!t)break;let r=r5(t);if(!r||!(2&r.headerType))break;this.bitstreams.push({serialNumber:r.serialNumber,bosPage:r,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=r.headerStartPos+r.totalSize}for(let e of this.bitstreams){let t=await this.readPacket(e.bosPage,0);t&&(t.data.byteLength>=7&&1===t.data[0]&&118===t.data[1]&&111===t.data[2]&&114===t.data[3]&&98===t.data[4]&&105===t.data[5]&&115===t.data[6]?await this.readVorbisMetadata(t,e):t.data.byteLength>=8&&79===t.data[0]&&112===t.data[1]&&117===t.data[2]&&115===t.data[3]&&72===t.data[4]&&101===t.data[5]&&97===t.data[6]&&100===t.data[7]&&await this.readOpusMetadata(t,e),null!==e.codecInfo.codec&&this.tracks.push(new tV(this.input,new ae(e,this))))}})()}async readVorbisMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;let a=await this.readPacket(r.startPage,r.startSegmentIndex);if(!a||!(r=await this.findNextPacketStart(a)))return;let i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i||3!==a.data[0]||5!==i.data[0])return;let n=[],s=e=>{for(;n.push(Math.min(255,e)),!(e<255);)e-=255};s(e.data.length),s(a.data.length);let o=new Uint8Array(1+n.length+e.data.length+a.data.length+i.data.length);o[0]=2,o.set(n,1),o.set(e.data,1+n.length),o.set(a.data,1+n.length+e.data.length),o.set(i.data,1+n.length+e.data.length+a.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=i;let l=S(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);let c=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&c),1<<(c>>4)],modeBlockflags:e3(i.data).modeBlockflags},e8(a.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;let a=await this.readPacket(r.startPage,r.startSegmentIndex);if(!a)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=a;let i=e0(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=48e3,t.codecInfo.opusInfo={preSkip:i.preSkip},e8(a.data.subarray(8),this.metadataTags)}async readPacket(e,t){p(te+t.length,0)),l=0;for(let e=0;ee.getCodecParameterString()))).filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let e=await this.getTracks();return Math.max(0,...await Promise.all(e.map(e=>e.computeDuration())))}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class ae{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new D,this.internalSampleRate="opus"===e.codecInfo.codec?48e3:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return p(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return"und"}getDisposition(){return{...tH}}async getFirstTimestamp(){return 0}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(p(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;let{durationInSamples:a,vorbisBlockSize:i}=r8(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),n=new te(r.metadataOnly?e7:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,a/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(n,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:a,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:i}),n}async getFirstPacket(e){p(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;"opus"===this.bitstream.codecInfo.codec&&(p(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);let a=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:r,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let r=this.encodedPacketToMetadata.get(e);if(!r)throw Error("Packet was not created from this track.");let a=await this.demuxer.findNextPacketStart(r.packet);if(!a)return null;let i=r.timestampInSamples+r.durationInSamples,n=await this.demuxer.readPacket(a.startPage,a.startSegmentIndex);return this.createEncodedPacketFromOggPacket(n,{timestampInSamples:i,vorbisLastBlocksize:r.vorbisBlockSize},t)}async getPacket(e,t){let r,a;if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);let i=Q(e*this.internalSampleRate);if(0===i)return this.getFirstPacket(t);if(i<0)return null;p(this.bitstream.lastMetadataPacket);let n=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!n)return null;let s=n.startPage,o=this.demuxer.reader.fileSize,l=[s];e:for(;s.headerStartPos+s.totalSizei?o=c.headerStartPos:(s=c,l.push(c));continue e}}let c=n.startPage;for(let e of l){if(e.granulePosition===s.granulePosition)break;(!c||e.headerStartPos>c.headerStartPos)&&(c=e)}let u=c,d=[u];for(;u.serialNumber!==this.bitstream.serialNumber||u.granulePosition!==s.granulePosition;){let e=u.headerStartPos+u.totalSize,t=this.demuxer.reader.requestSliceRange(e,27,282);t instanceof Promise&&(t=await t),p(t);let r=r5(t);p(r),(u=r).serialNumber===this.bitstream.serialNumber&&d.push(u)}p(-1!==u.granulePosition);let h=null,m=u,f=0;if(u.headerStartPos===n.startPage.headerStartPos)r=this.granulePositionToTimestampInSamples(0),a=!0,h=0;else{r=0,a=!1;for(let e=u.lacingValues.length-1;e>=0;e--)if(u.lacingValues[e]<255){h=e+1;break}if(null===h)throw Error("Invalid page with granule position: no packets end on this page.");let e={data:e7,endPage:m,endSegmentIndex:f=h-1};if(await this.demuxer.findNextPacketStart(e)){let e=ar(d,u,h);p(e);let t=at(d,e.page,e.segmentIndex);t&&(u=t.page,h=t.segmentIndex)}else for(;;){let e=ar(d,u,h);if(!e)break;let t=at(d,e.page,e.segmentIndex);if(!t)break;if(u=t.page,h=t.segmentIndex,e.page.headerStartPos!==m.headerStartPos){m=e.page,f=e.segmentIndex;break}}}let g=null,b=null;for(;null!==u;){p(null!==h);let e=await this.demuxer.readPacket(u,h);if(!e)break;if(!(u.headerStartPos===n.startPage.headerStartPos&&hi||Math.max(s.timestampInSamples,0)===i))break}let s=await this.demuxer.findNextPacketStart(e);if(!s)break;u=s.startPage,h=s.startSegmentIndex}return g}async getPacketSequential(e,t){let r=await this.sequentialScanMutex.acquire();try{let r;let a=Q(e*this.internalSampleRate);e=a/this.internalSampleRate;let i=N(this.sequentialScanCache,a,e=>e.timestampInSamples);if(-1!==i){let e=this.sequentialScanCache[i];r=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else r=await this.getFirstPacket(t);let n=0;for(;r&&r.timestampe)break;if(r=a,n++,100===n){n=0;let e=this.encodedPacketToMetadata.get(r);p(e),this.sequentialScanCache.length>0&&p(b(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return r}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}let at=(e,t,r)=>{let a=t,i=r;e:for(;;){for(i--;i>=0;i--)if(a.lacingValues[i]<255){i++;break e}if(p(-1===i),!(1&a.headerType)){i=0;break}let t=z(e,e=>e.headerStartPos{if(r>0)return{page:t,segmentIndex:r-1};let a=z(e,e=>e.headerStartPos{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),p(e);let t=rt(e,4),r="RIFX"!==t,a="RF64"===t,i=t0(e,r),n=a?this.reader.fileSize:Math.min(i+8,this.reader.fileSize??1/0);if("WAVE"!==rt(e,4))throw Error("Invalid WAVE file - wrong format");let s=0,o=null,l=e.filePos;for(;null===n||l=18&&357!==n&&Math.min(t-18,tG(i,r))>=22&&n===h.EXTENSIBLE){i.skip(6);let e=tK(i,16);n=e[0]|e[1]<<8}(n===h.MULAW||n===h.ALAW)&&(a=8),this.audioInfo={format:n,numberOfChannels:s,sampleRate:o,sampleSizeInBytes:Math.ceil(a/8),blockSizeInBytes:l}}async parseListChunk(e,t,r){let a=this.reader.requestSlice(e,t);if(a instanceof Promise&&(a=await a),!a)return;let i=rt(a,4);if("INFO"!==i&&"INF0"!==i)return;let n=a.filePos;for(;n<=e+t-8;){a.filePos=n;let e=rt(a,4),t=t0(a,r),i=tK(a,t),s=0;for(let e=0;e0&&(this.metadataTags.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(this.metadataTags.tracksTotal??=r)}break;case"ICRD":case"IDIT":{let e=new Date(o);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"YEAR":{let e=Number.parseInt(o,10);Number.isInteger(e)&&e>0&&(this.metadataTags.date??=new Date(e,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=o;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=o}n+=8+t+(1&t)}}async parseId3Chunk(e,t){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let a=rJ(r);a&&rY(r.slice(e+10,a.size),a,this.metadataTags)}getCodec(){if(p(this.audioInfo),this.audioInfo.format===h.MULAW)return"ulaw";if(this.audioInfo.format===h.ALAW)return"alaw";if(this.audioInfo.format===h.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}return this.audioInfo.format===h.IEEE_FLOAT&&4===this.audioInfo.sampleSizeInBytes?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return p(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class ai{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(p(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return"und"}getDisposition(){return{...tH}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){let r;p(this.demuxer.audioInfo);let a=2048*e*this.demuxer.audioInfo.blockSizeInBytes;if(a>=this.demuxer.dataSize)return null;let i=Math.min(2048*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-a);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+a,i);if(e instanceof Promise&&(e=await e),!e)return null}if(t.metadataOnly)r=e7;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+a,i);e instanceof Promise&&(e=await e),p(e),r=tK(e,i)}let n=2048*e/this.demuxer.audioInfo.sampleRate,s=i/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,n),new te(r,"key",n,s,e,i)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){p(this.demuxer.audioInfo);let r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/2048,(this.demuxer.dataSize-1)/(2048*this.demuxer.audioInfo.blockSizeInBytes))),a=await this.getPacketAtIndex(r,t);if(a)return a;if(0===r)return null;p(null===this.demuxer.reader.fileSize);let i=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;i;){let e=await this.getNextPacket(i,t);if(!e)break;i=e}return i}getNextPacket(e,t){p(this.demuxer.audioInfo);let r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/2048);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}let an=e=>{let t=e.filePos,r=new k(tK(e,9));if(4095!==r.readBits(12)||(r.skipBits(1),0!==r.readBits(2)))return null;let a=r.readBits(1),i=r.readBits(2)+1,n=r.readBits(4);if(15===n)return null;r.skipBits(1);let s=r.readBits(3);if(0===s)throw Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);let o=r.readBits(13);r.skipBits(11);let l=r.readBits(2)+1;if(1!==l)throw Error("ADTS frames with more than one AAC frame are not supported.");let c=null;return 1===a?e.filePos-=2:c=r.readBits(16),{objectType:i,samplingFrequencyIndex:n,channelConfiguration:s,frameLength:o,numberOfAacFrames:l,crcCheck:c,startPos:t}};class as extends e6{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new D,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();p(this.firstFrameHeader),this.tracks=[new tV(this.input,new ao(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=an(e);if(!t||null!==this.reader.fileSize&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);let r=ex[t.samplingFrequencyIndex];p(void 0!==r);let a=t.crcCheck?9:7,i={timestamp:this.nextTimestampInSamples/r,duration:1024/r,dataStart:t.startPos+a,dataSize:t.frameLength-a};this.loadedSamples.push(i),this.nextTimestampInSamples+=1024,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return p(e),e.computeDuration()}async getMetadataTags(){return{}}}class ao{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/1024}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return"und"}getCodec(){return"aac"}getInternalCodecId(){return p(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){p(this.demuxer.firstFrameHeader);let e=eP[this.demuxer.firstFrameHeader.channelConfiguration];return p(void 0!==e),e}getSampleRate(){p(this.demuxer.firstFrameHeader);let e=ex[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return p(void 0!==e),e}getDisposition(){return{...tH}}async getDecoderConfig(){p(this.demuxer.firstFrameHeader);let e=new Uint8Array(3),t=new k(e),{objectType:r,samplingFrequencyIndex:a,channelConfiguration:i}=this.demuxer.firstFrameHeader;return r>31?(t.writeBits(5,31),t.writeBits(6,r-32)):t.writeBits(5,r),t.writeBits(4,a),t.writeBits(4,i),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((t.pos-1)/8))}}async getPacketAtIndex(e,t){let r;if(-1===e)return null;let a=this.demuxer.loadedSamples[e];if(!a)return null;if(t.metadataOnly)r=e7;else{let e=this.demuxer.reader.requestSlice(a.dataStart,a.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=tK(e,a.dataSize)}return new te(r,"key",a.timestamp,a.duration,e,a.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let r=_(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===r)throw Error("Packet was not created from this track.");let a=r+1;for(;a>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(a,t)}finally{r()}}async getPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{for(;;){let r=N(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===r&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||r>=0&&r+10===e?null:1===e?192:e>=2&&e<=5?144*2**e:6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?2**e:null,ac=(e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},au=e=>{let t=0,r=new k(tK(e,1));for(;1===r.readBits(1);)t++;if(0===t)return r.readBits(7);let a=[],i=t-1,n=new k(tK(e,i)),s=8-t-1;for(let e=0;ee|t<"uncommon-u16"===t?tJ(e)+1:"uncommon-u8"===t?tQ(e)+1:"number"==typeof t?t:void(j(t),p(!1)),ah=(e,t)=>"uncommon-u16"===t?tJ(e):"uncommon-u16-10"===t?10*tJ(e):"uncommon-u8"===t?tQ(e):"number"==typeof t?t:null,am=e=>{let t=0;for(let r of e){t^=r;for(let e=0;e<8;e++)(128&t)!=0?t=t<<1^7:t<<=1,t&=255}return t};class af extends e6{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new D,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),p(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),p(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;null===this.reader.fileSize||ea.end-6)return{num:i.num,blockSize:i.blockSize,sampleRate:i.sampleRate,size:a.end-e,isLastFrame:!0};if(255===tQ(a)){let t=a.filePos;if(tQ(a)!==(1===this.blockingBit?249:248)){a.filePos=t;continue}a.skip(-2);let r=a.filePos-e,n=this.readFlacFrameHeader({slice:a,isFirstPacket:!1});if(!n){a.filePos=t;continue}if(0===this.blockingBit){if(n.num-i.num!=1){a.filePos=t;continue}}else if(n.num-i.num!==i.blockSize){a.filePos=t;continue}return{num:i.num,blockSize:i.blockSize,sampleRate:i.sampleRate,size:r,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let r=e.filePos,a=new k(tK(e,4));if(32764!==a.readBits(15))return null;if(null===this.blockingBit){p(t);let e=a.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){if(p(!t),1!==a.readBits(1))return null}else if(0===this.blockingBit){if(p(!t),0!==a.readBits(1))return null}else throw Error("Invalid blocking bit");let i=al(a.readBits(4));if(!i)return null;p(this.audioInfo);let n=ac(a.readBits(4),this.audioInfo.sampleRate);if(!n||(a.readBits(4),a.readBits(3),0!==a.readBits(1)))return null;let s=au(e),o=ad(e,i),l=ah(e,n);if(null===l||l!==this.audioInfo.sampleRate)return null;let c=e.filePos-r,u=tQ(e);return(e.skip(-c),e.skip(-1),u!==am(tK(e,c)))?null:{num:s,blockSize:o,sampleRate:l}}async advanceReader(){await this.readMetadata(),p(null!==this.lastLoadedPos),p(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!t){this.lastSampleLoaded=!0;return}let r=this.loadedSamples[this.loadedSamples.length-1],a={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(a),t.isLastFrame){this.lastSampleLoaded=!0;return}}}class ap{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return"und"}getTimeResolution(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...tH}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return p(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(p(this.demuxer.audioInfo),e<0)throw Error("Timestamp cannot be negative");let r=await this.demuxer.readingMutex.acquire();try{for(;;){let r=N(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===r){await this.demuxer.advanceReader();continue}let a=this.demuxer.loadedSamples[r],i=a.blockOffset/this.demuxer.audioInfo.sampleRate,n=a.blockSize/this.demuxer.audioInfo.sampleRate;if(i+n<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(r,t)}}finally{r()}}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let r=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&r>=this.demuxer.loadedSamples.length)return null;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let r;let a=this.demuxer.loadedSamples[e];if(!a)return null;if(t.metadataOnly)r=e7;else{let e=this.demuxer.reader.requestSlice(a.byteOffset,a.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;r=tK(e,a.byteSize)}return p(this.demuxer.audioInfo),new te(r,"key",a.blockOffset/this.demuxer.audioInfo.sampleRate,a.blockSize/this.demuxer.audioInfo.sampleRate,e,a.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}class ag{}class ab extends ag{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);return(t instanceof Promise&&(t=await t),t)?(t.skip(4),"ftyp"!==rt(t,4))?null:rt(t,4):null}_createDemuxer(e){return new rl(e)}}class ak extends ab{async _canReadInput(e){let t=await this._getMajorBrand(e);return!!t&&"qt "!==t}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class ay extends ab{async _canReadInput(e){return"qt "===await this._getMajorBrand(e)}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class aw extends ag{async isSupportedEBMLOfDocType(e,t){let r=e._reader.requestSlice(0,16);if(r instanceof Promise&&(r=await r),!r)return!1;let a=rS(r);if(null===a||a<1||a>8||rx(r,a)!==s.EBML)return!1;let i=rC(r);if(null===i)return!1;let n=e._reader.requestSlice(r.filePos,i);if(n instanceof Promise&&(n=await n),!n)return!1;let o=r.filePos;for(;n.filePos<=o+i-2;){let e=rE(n);if(!e)break;let{id:r,size:a}=e,i=n.filePos;if(null===a)return!1;switch(r){case s.EBMLVersion:case s.EBMLReadVersion:if(1!==rx(n,a))return!1;break;case s.DocType:if(rF(n,a)!==t)return!1;break;case s.DocTypeVersion:if(rx(n,a)>4)return!1}n.filePos=i+a}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new rO(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class aT extends aw{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class aS extends ag{async _canReadInput(e){let t=e._reader.requestSlice(0,10);if(t instanceof Promise&&(t=await t),!t)return!1;let r=0,a=!1;for(;;){let t=e._reader.requestSlice(r,10);if(t instanceof Promise&&(t=await t),!t)break;let i=rJ(t);if(!i)break;a=!0,r=t.filePos+i.size}let i=await r0(e._reader,r,r+4096);if(!i)return!1;if(a)return!0;r=i.startPos+i.header.totalSize;let n=await r0(e._reader,r,r+4);if(!n)return!1;let s=i.header,o=n.header;return s.channel===o.channel&&s.sampleRate===o.sampleRate}_createDemuxer(e){return new r1(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class av extends ag{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let r=rt(t,4);return("RIFF"===r||"RIFX"===r||"RF64"===r)&&(t.skip(4),"WAVE"===rt(t,4))}_createDemuxer(e){return new aa(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class ax extends ag{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"OggS"===rt(t,4)}_createDemuxer(e){return new r7(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class aP extends ag{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"fLaC"===rt(t,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new af(e)}}class aI extends ag{async _canReadInput(e){let t=e._reader.requestSliceRange(0,7,9);if(t instanceof Promise&&(t=await t),!t)return!1;let r=an(t);if(!r||((t=e._reader.requestSliceRange(r.frameLength,7,9))instanceof Promise&&(t=await t),!t))return!1;let a=an(t);return!!a&&r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration}_createDemuxer(e){return new as(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}let aC=new ak,aE=new ay,aF=new aw,aA=new aT,aB=new aS,aD=new av,aR=new ax,aM=new aI,a_=[aC,aE,aF,aA,aD,aR,new aP,aB,aM];r(95194);class aN{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new a$;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new a$;let e=await this.getSizeOrNull();if(null===e)throw Error("Cannot determine the size of an unsized source.");return e}}let aL=(e,t,r)=>{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))){let e=null;try{"undefined"!=typeof window&&void 0!==window.location&&(e=new URL(r instanceof Request?r.url:r,window.location.href).origin)}catch{}if(("undefined"==typeof navigator||"boolean"!=typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==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**(e-2),16)};class aO extends aN{constructor(e,t={}){if("string"!=typeof e&&!(e instanceof URL)&&!("undefined"!=typeof Request&&e instanceof Request))throw TypeError("url must be a string, URL or Request.");if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(void 0!==t.requestInit&&(!t.requestInit||"object"!=typeof t.requestInit))throw TypeError("options.requestInit, when provided, must be an object.");if(void 0!==t.getRetryDelay&&"function"!=typeof t.getRetryDelay)throw TypeError("options.getRetryDelay, when provided, must be a function.");if(void 0!==t.maxCacheSize&&(!eb(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.fetchFn&&"function"!=typeof t.fetchFn)throw TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??aL,this._orchestrator=new aV({maxCacheSize:t.maxCacheSize??0x4000000,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:az.network})}async _retrieveSize(){let e,t;let r=new AbortController,a=await ea(this._options.fetchFn??fetch,this._url,et(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:r.signal}),this._getRetryDelay,()=>this._disposed);if(!a.ok)throw Error(`Error fetching ${String(this._url)}: ${a.status} ${a.statusText}`);if(206===a.status)t=this._getTotalLengthFromRangeResponse(a),e=this._orchestrator.createWorker(0,Math.min(t,524288));else{let r=a.headers.get("Content-Length");if(r)t=Number(r),e=this._orchestrator.createWorker(0,t),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 Error(`HTTP response (status ${a.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=t,this._existingResponses.set(e,{response:a,abortController:r}),this._orchestrator.runWorker(e),t}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;;){let t=this._existingResponses.get(e);this._existingResponses.delete(e);let r=t?.abortController,a=t?.response;if(r||(r=new AbortController,a=await ea(this._options.fetchFn??fetch,this._url,et(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:r.signal}),this._getRetryDelay,()=>this._disposed)),p(a),!a.ok)throw Error(`Error fetching ${String(this._url)}: ${a.status} ${a.statusText}`);if(e.currentPos>0&&206!==a.status)throw 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 Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let i=a.body.getReader();for(;;){let t;if(e.currentPos>=e.targetPos||e.aborted){r.abort(),e.running=!1;return}try{t=await i.read()}catch(t){if(this._disposed)throw t;let e=this._getRetryDelay(1,t,this._url);if(null!==e){console.error("Error while reading response stream. Attempting to resume.",t),await new Promise(t=>setTimeout(t,1e3*e));break}throw t}if(e.aborted)continue;let{done:a,value:n}=t;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.forgetWorker(e),e.running=!1;return}break}this.onread?.(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}}}_getTotalLengthFromRangeResponse(e){let t=e.headers.get("Content-Range");if(t){let e=/\/(\d+)/.exec(t);if(e)return Number(e[1])}let r=e.headers.get("Content-Length");if(r)return Number(r);throw Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}}let az={network:(e,t,r)=>{for(let a of(e=Math.max(0,65536*Math.floor((e-65536)/65536)),r))if(ef(e,t,Math.max((a.startPos+a.targetPos)/2,a.targetPos-8388608),a.targetPos)){let e=a.targetPos-a.startPos,r=8388608*Math.ceil((e+1)/8388608),i=Math.min(2**Math.ceil(Math.log2(e+1)),r);t=Math.max(t,a.startPos+i)}return t=Math.max(t,e+524288),{start:e,end:t}}};class aV{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,t){p(null!==this.fileSize);let r=this.options.prefetchProfile(e,t,this.workers),a=Math.max(r.start,0),i=Math.min(r.end,this.fileSize);p(a<=e&&t<=i);let n=null,s=N(this.cache,e,e=>e.start),o=-1!==s?this.cache[s]:null;o&&o.start<=e&&t<=o.end&&(o.age=this.nextAge++,n={bytes:o.bytes,view:o.view,offset:o.start});let l=N(this.cache,a,e=>e.start),c=n?null:new Uint8Array(t-e),u=0,d=a,h=[];if(-1!==l){for(let r=l;r=i)break;if(n.end<=a)continue;let s=Math.max(a,n.start),o=Math.min(i,n.end);if(p(s<=o),d=c.length&&(n={bytes:c,view:S(c),offset:e}),0===h.length)return p(n),n;let{promise:m,resolve:f,reject:g}=O(),b=[];for(let r of h){let a=Math.max(e,r.start),i=Math.min(t,r.end);a===r.start&&i===r.end?b.push(r):a({bytes:t,view:S(t),offset:e}))),n}createWorker(e,t){let r={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(r);this.workers.length>this.options.maxWorkerCount;){let e=0,t=this.workers[0];for(let r=1;r0)break;t.aborted=!0,this.workers.splice(e,1)}return r}runWorker(e){p(!e.running),p(e.currentPos{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0;else throw t})}supplyWorkerData(e,t){p(!e.aborted);let r=e.currentPos,a=r+t.length;this.insertIntoCache({start:r,end:a,bytes:t,view:S(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let i=0;it.start&&(t.start=a),t.end<=t.start&&(n.holes.splice(e,1),e--)}0===n.holes.length&&(n.resolve(n.bytes),e.pendingSlices.splice(i,1),i--)}for(let t=0;te.start)+1;if(t>0){let r=this.cache[t-1];if(r.end>=e.end)return;if(r.end>e.start){let a=new Uint8Array(e.end-r.start);a.set(r.bytes,0),a.set(e.bytes,e.start-r.start),this.currentCacheSize+=e.end-r.end,r.bytes=a,r.view=S(a),r.end=e.end,t--,e=r}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let r=t+1;r=t.end){this.cache.splice(r,1),this.currentCacheSize-=t.bytes.length,r--;continue}let a=new Uint8Array(t.end-e.start);a.set(e.bytes,0),a.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=a,e.view=S(a),e.end=t.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let r=1;r!(e instanceof ag)))throw TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof aN))throw TypeError("options.source must be a Source.");if(e.source._disposed)throw Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new tq(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{for(let e of(this._reader.fileSize=await this._source.getSizeOrNull(),this._formats))if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),p(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(e=>e.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(e=>e.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(e=>e.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(e=>e.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 a$ extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}var aj=r(19002),aH=({loop:e,mediaDurationInSeconds:t,unloopedTimeInSeconds:r,src:a,trimAfter:i,trimBefore:n,fps:s,playbackRate:o,ifNoMediaDuration:l})=>{if(null===t&&e&&"fail"===l)throw Error(`Could not determine duration of ${a}, but "loop" was set.`);let c=r*o%(e?m.Xp.calculateMediaDuration({trimAfter:i,mediaDurationInFrames:t?t*s:1/0,playbackRate:1,trimBefore:n})/s:1/0);return(i??null)!==null&&!e&&c>=(i-(n??0))/s?null:c+(n??0)/s},aq=({mediaDurationInSeconds:e,ifNoMediaDuration:t,src:r,trimAfter:a,trimBefore:i,fps:n})=>{if(null===e&&"fail"===t)throw Error(`Could not determine duration of ${r}, but "loop" was set.`);return m.Xp.calculateMediaDuration({trimAfter:a,mediaDurationInFrames:e?e*n:1/0,playbackRate:1,trimBefore:i})/n+(i??0)/n},aX=e=>Math.round(1e3*e)/1e3,aW=async(e,t)=>{let r=await Promise.race([e,new Promise(e=>{Promise.resolve().then(()=>e())})]);if(!r){let r=t.waitCallback(),a=await e;return r(),a}return r},aK=(e,t)=>{let r=!1,a=t.makeIteratorOrUsePrewarmed(e),i=[],n=[],s=-1/0,o=()=>{for(let e of i)e.node.stop();i.length=0},l=async e=>{let t=a.next(),r=e?await aW(t,e):await Promise.race([t,new Promise(e=>{Promise.resolve().then(()=>e())})]);return r?r.value?(s=Math.max(s,r.value.timestamp+r.value.duration),{type:"got-buffer",buffer:r.value}):{type:"got-end",mostRecentTimestamp:s}:{type:"need-to-wait-for-it",waitPromise:async()=>(await t).value}},c=()=>{let e=i.slice();for(let t of e)t.node.stop();return i.length=0,e},u=(e,t)=>{n.push({buffer:e,timestamp:t})};return{destroy:()=>{o(),r=!0,a.return().catch(()=>{}),n.length=0},getNext:async()=>{let e=await a.next();return e.value&&(s=Math.max(s,e.value.timestamp+e.value.duration)),e},isDestroyed:()=>r,addQueuedAudioNode:(e,t,r)=>{i.push({node:e,timestamp:t,buffer:r})},removeQueuedAudioNode:e=>{let t=i.findIndex(t=>t.node===e);-1!==t&&i.splice(t,1)},getAndClearAudioChunksForAfterResuming:()=>{let e=n.slice();return n.length=0,e},getQueuedPeriod:()=>{let e=-1/0,t=1/0;for(let r of i)e=Math.max(e,r.timestamp+r.buffer.duration),t=Math.min(t,r.timestamp);for(let r of n)e=Math.max(e,r.timestamp+r.buffer.duration),t=Math.min(t,r.timestamp);return Number.isFinite(t)&&Number.isFinite(e)?{from:t,until:e}:null},tryToSatisfySeek:async(t,r,a)=>{if(t=s)return{type:"ended"};return{type:"not-satisfied",reason:"iterator ended before the requested time"}}if("got-buffer"===e.type){let r=aX(e.buffer.timestamp),i=aX(e.buffer.timestamp+e.buffer.duration),n=aX(t);if(aX(t)n)return a(e.buffer),{type:"satisfied"};a(e.buffer);continue}throw Error("Unreachable")}},addChunkForAfterResuming:u,moveQueuedChunksToPauseQueue:()=>{for(let e of c())u(e.buffer,e.timestamp)},getNumberOfChunksAfterResuming:()=>n.length}},aQ=(e,t)=>!!t&&e>=t.from&&e{let t=new Map;return{prewarmIteratorForLooping:({timeToSeek:r})=>{t.has(r)||t.set(r,e.canvases(r))},makeIteratorOrUsePrewarmed:r=>{let a=t.get(r);return a?(t.delete(r),a):e.canvases(r)},destroy:()=>{for(let e of t.values())e.return();t.clear()}}},aJ=e=>{let t=new Map;return{prewarmIteratorForLooping:({timeToSeek:r})=>{t.has(r)||t.set(r,e.buffers(r))},makeIteratorOrUsePrewarmed:r=>{let a=t.get(r);return a?(t.delete(r),a):e.buffers(r)},destroy:()=>{for(let e of t.values())e.return();t.clear()}}},aY=({audioTrack:e,delayPlaybackHandleIfNotPremounting:t,sharedAudioContext:r,getIsLooping:a,getEndTime:i,getStartTime:n,updatePlaybackTime:s})=>{let o=!1,l=1,c=r.createGain();c.connect(r.destination);let u=aJ(new tL(e)),d=null,h=0,m=null,f=({buffer:e,mediaTimestamp:t,playbackRate:a,scheduleAudioNode:i})=>{if(!d)throw Error("Audio buffer iterator not found");let n=r.createBufferSource();n.buffer=e,n.playbackRate.value=a,n.connect(c),i(n,t);let s=d;s.addQueuedAudioNode(n,t,e),n.onended=()=>{setTimeout(()=>{s.removeQueuedAudioNode(n)},30)}},p=({getIsPlaying:e,buffer:t,playbackRate:r,scheduleAudioNode:a})=>{if(e())f({buffer:t.buffer,mediaTimestamp:t.timestamp,playbackRate:r,scheduleAudioNode:a});else{if(!d)throw Error("Audio buffer iterator not found");d.addChunkForAfterResuming(t.buffer,t.timestamp)}},g=async({nonce:e,playbackRate:r,startFromSecond:a,getIsPlaying:i,scheduleAudioNode:n})=>{s(a),d?.destroy();let o=t();m=o;let l=aK(a,u);h++,d=l;try{for(let t=0;t<3;t++){let t=await l.getNext();if(l.isDestroyed()||e.isStale()||!t.value)return;p({getIsPlaying:i,buffer:t.value,playbackRate:r,scheduleAudioNode:n})}}catch(e){if(e instanceof a$)return;throw e}finally{o.unblock(),m=null}},b=async({newTime:e,nonce:t,fps:r,playbackRate:s,getIsPlaying:o,scheduleAudioNode:l,bufferState:c})=>{if(a()&&i()-e<1&&u.prewarmIteratorForLooping({timeToSeek:n()}),!d){await g({nonce:t,playbackRate:s,startFromSecond:e,getIsPlaying:o,scheduleAudioNode:l});return}if(!aQ(e,d.getQueuedPeriod())){let r=await d.tryToSatisfySeek(e,null,e=>{t.isStale()||p({getIsPlaying:o,buffer:e,playbackRate:s,scheduleAudioNode:l})});if(t.isStale()||"ended"===r.type)return;if("not-satisfied"===r.type){await g({nonce:t,playbackRate:s,startFromSecond:e,getIsPlaying:o,scheduleAudioNode:l});return}}let h=e+1/r*Math.max(1,s)*3;if(!aQ(h,d.getQueuedPeriod())){let r=await d.tryToSatisfySeek(h,{type:"allow-wait",waitCallback:()=>{let e=c.delayPlayback();return()=>{e.unblock()}}},e=>{t.isStale()||p({getIsPlaying:o,buffer:e,playbackRate:s,scheduleAudioNode:l})});if(t.isStale()||"ended"===r.type)return;"not-satisfied"===r.type&&await g({nonce:t,playbackRate:s,startFromSecond:e,getIsPlaying:o,scheduleAudioNode:l})}};return{startAudioIterator:g,resumeScheduledAudioChunks:({playbackRate:e,scheduleAudioNode:t})=>{if(d)for(let r of d.getAndClearAudioChunksForAfterResuming())f({buffer:r.buffer,mediaTimestamp:r.timestamp,playbackRate:e,scheduleAudioNode:t})},pausePlayback:()=>{d&&d.moveQueuedChunksToPauseQueue()},getAudioBufferIterator:()=>d,destroyIterator:()=>{u.destroy(),d?.destroy(),d=null,m&&(m.unblock(),m=null)},seek:b,getAudioIteratorsCreated:()=>h,setMuted:e=>{o=e,c.gain.value=o?0:l},setVolume:e=>{l=Math.max(0,e),c.gain.value=o?0:l},scheduleAudioChunk:f}},aZ=({audioSyncAnchor:e,currentTime:t,playbackRate:r})=>(t-e)*r,a0=({context:e,audioTime:t,audioContextState:r,audioSyncAnchor:a,playing:i,audioIteratorManager:n,videoIteratorManager:s})=>{let o=["Debug overlay",`Video iterators created: ${s?.getVideoIteratorsCreated()}`,`Audio iterators created: ${n?.getAudioIteratorsCreated()}`,`Frames rendered: ${s?.getFramesRendered()}`,`Audio context state: ${r}`,`Audio time: ${(t-a).toFixed(3)}s`];if(n){let e=n.getAudioBufferIterator()?.getQueuedPeriod(),r=n?.getAudioBufferIterator()?.getNumberOfChunksAfterResuming();e?o.push(`Audio queued until: ${(e.until-(t-a)).toFixed(3)}s`):r&&o.push(`Audio chunks for after resuming: ${r}`),o.push(`Playing: ${i}`)}let l=30*o.length+20;e.fillStyle="rgba(0, 0, 0, 1)",e.fillRect(20,20,600,l),e.fillStyle="white",e.font="24px sans-serif",e.textBaseline="top";for(let t=0;t{let e=0;return{createAsyncOperation:()=>{let t=++e;return{isStale:()=>e!==t}}}},a3=(e,t)=>{let r=!1,a=t.makeIteratorOrUsePrewarmed(e),i=null,n=!1,s=async()=>{let e=a.next(),t=await Promise.race([e,new Promise(e=>{Promise.resolve().then(()=>e())})]);return t?(t.value?i=t.value:n=!0,{type:"got-frame-or-end",frame:t.value??null}):{type:"need-to-wait-for-it",waitPromise:async()=>{let t=await e;return t.value?i=t.value:n=!0,t.value}}};return{destroy:()=>{r=!0,i=null,a.return().catch(()=>{})},getNext:()=>a.next(),isDestroyed:()=>r,tryToSatisfySeek:async e=>{if(i){let t=aX(i.timestamp);if(aX(e)a)return{type:"satisfied",frame:i}}if(n)return i?{type:"satisfied",frame:i}:{type:"not-satisfied",reason:"iterator ended"};for(;;){let t=await s();if("need-to-wait-for-it"===t.type)return{type:"not-satisfied",reason:"iterator did not have frame ready"};if("got-frame-or-end"===t.type){if(null===t.frame){if(n=!0,i)return{type:"satisfied",frame:i};return{type:"not-satisfied",reason:"iterator ended and did not have frame ready"}}let r=aX(t.frame.timestamp),a=aX(t.frame.timestamp+t.frame.duration),s=aX(e);if(r<=s&&a>s)return{type:"satisfied",frame:t.frame};continue}throw Error("Unreachable")}}}},a4=({delayPlaybackHandleIfNotPremounting:e,canvas:t,context:r,drawDebugOverlay:a,logLevel:i,getOnVideoFrameCallback:n,videoTrack:s,getEndTime:o,getStartTime:l,getIsLooping:c})=>{let u=0,d=null,h=0,f=null;t&&(t.width=s.displayWidth,t.height=s.displayHeight);let p=aG(new tR(s,{poolSize:2,fit:"contain",alpha:!0})),g=e=>{r&&t&&(r.clearRect(0,0,t.width,t.height),r.drawImage(e.canvas,0,0)),h++,a();let s=n();s&&s(e.canvas),m.Xp.Log.trace({logLevel:i,tag:"@remotion/media"},`[MediaPlayer] Drew frame ${e.timestamp.toFixed(3)}s`)},b=async(t,r)=>{let a;d?.destroy();let i=a3(t,p);u++,d=i;let n=e();f=n;try{a=await i.getNext()}finally{n.unblock(),f=null}!(i.isDestroyed()||r.isStale()||d.isDestroyed())&&a.value&&g(a.value)},k=async({newTime:e,nonce:t})=>{if(!d)return;c()&&o()-e<1&&p.prewarmIteratorForLooping({timeToSeek:l()});let r=await d.tryToSatisfySeek(e);if("satisfied"===r.type){g(r.frame);return}t.isStale()||await b(e,t)};return{startVideoIterator:b,getVideoIteratorsCreated:()=>u,seek:k,destroy:()=>{p.destroy(),d?.destroy(),r&&t&&r.clearRect(0,0,t.width,t.height),f&&(f.unblock(),f=null),d=null},getVideoFrameIterator:()=>d,drawFrame:g,getFramesRendered:()=>h}};class a8{canvas;context;src;logLevel;playbackRate;globalPlaybackRate;audioStreamIndex;sharedAudioContext;audioIteratorManager=null;videoIteratorManager=null;audioSyncAnchor=0;playing=!1;loop=!1;fps;trimBefore;trimAfter;totalDuration;debugOverlay=!1;nonceManager;onVideoFrameCallback=null;initializationPromise=null;bufferState;isPremounting;isPostmounting;seekPromiseChain=Promise.resolve();constructor({canvas:e,src:t,logLevel:r,sharedAudioContext:a,loop:i,trimBefore:n,trimAfter:s,playbackRate:o,globalPlaybackRate:l,audioStreamIndex:c,fps:u,debugOverlay:d,bufferState:h,isPremounting:m,isPostmounting:f,onVideoFrameCallback:p,playing:g}){if(this.canvas=e??null,this.src=t,this.logLevel=r??window.remotion_logLevel,this.sharedAudioContext=a,this.playbackRate=o,this.globalPlaybackRate=l,this.loop=i,this.trimBefore=n,this.trimAfter=s,this.audioStreamIndex=c??0,this.fps=u,this.debugOverlay=d,this.bufferState=h,this.isPremounting=m,this.isPostmounting=f,this.nonceManager=a2(),this.onVideoFrameCallback=p,this.playing=g,this.input=new aU({source:new aO(this.src),formats:a_}),e){let t=e.getContext("2d",{alpha:!0,desynchronized:!0});if(!t)throw Error("Could not get 2D context from canvas");this.context=t}else this.context=null}input;isDisposalError(){return!0===this.input.disposed}initialize(e){let t=this._initialize(e);return this.initializationPromise=t,this.seekPromiseChain=t,t}getStartTime(){return(this.trimBefore??0)/this.fps}getEndTime(){return aq({mediaDurationInSeconds:this.totalDuration,ifNoMediaDuration:"fail",src:this.src,trimAfter:this.trimAfter,trimBefore:this.trimBefore,fps:this.fps})}async _initialize(e){let t=this.delayPlaybackHandleIfNotPremounting();try{if(this.input.disposed)return{type:"disposed"};try{await this.input.getFormat()}catch(e){if(this.isDisposalError())return{type:"disposed"};if(a1(e))throw e;return m.Xp.Log.error({logLevel:this.logLevel,tag:"@remotion/media"},`[MediaPlayer] Failed to recognize format for ${this.src}`,e),{type:"unknown-container-format"}}let[t,r,a]=await Promise.all([this.input.computeDuration(),this.input.getPrimaryVideoTrack(),this.input.getAudioTracks()]);if(this.input.disposed)return{type:"disposed"};this.totalDuration=t;let i=a[this.audioStreamIndex]??null;if(!r&&!i)return{type:"no-tracks"};if(r){if(!await r.canDecode())return{type:"cannot-decode"};if(this.input.disposed)return{type:"disposed"};this.videoIteratorManager=a4({videoTrack:r,delayPlaybackHandleIfNotPremounting:this.delayPlaybackHandleIfNotPremounting,context:this.context,canvas:this.canvas,getOnVideoFrameCallback:()=>this.onVideoFrameCallback,logLevel:this.logLevel,drawDebugOverlay:this.drawDebugOverlay,getEndTime:()=>this.getEndTime(),getStartTime:()=>this.getStartTime(),getIsLooping:()=>this.loop})}let n=aH({unloopedTimeInSeconds:e,playbackRate:this.playbackRate,loop:this.loop,trimBefore:this.trimBefore,trimAfter:this.trimAfter,mediaDurationInSeconds:this.totalDuration,fps:this.fps,ifNoMediaDuration:"infinity",src:this.src});if(null===n)throw Error("should have asserted that the time is not null");this.setPlaybackTime(n,this.playbackRate*this.globalPlaybackRate),i&&(this.audioIteratorManager=aY({audioTrack:i,delayPlaybackHandleIfNotPremounting:this.delayPlaybackHandleIfNotPremounting,sharedAudioContext:this.sharedAudioContext,getIsLooping:()=>this.loop,getEndTime:()=>this.getEndTime(),getStartTime:()=>this.getStartTime(),updatePlaybackTime:e=>this.setPlaybackTime(e,this.playbackRate*this.globalPlaybackRate)}));let s=this.nonceManager.createAsyncOperation();try{await Promise.all([this.audioIteratorManager?this.audioIteratorManager.startAudioIterator({nonce:s,playbackRate:this.playbackRate*this.globalPlaybackRate,startFromSecond:n,getIsPlaying:()=>this.playing,scheduleAudioNode:this.scheduleAudioNode}):Promise.resolve(),this.videoIteratorManager?this.videoIteratorManager.startVideoIterator(n,s):Promise.resolve()])}catch(e){if(this.isDisposalError())return{type:"disposed"};m.Xp.Log.error({logLevel:this.logLevel,tag:"@remotion/media"},"[MediaPlayer] Failed to start audio and video iterators",e)}return{type:"success",durationInSeconds:t}}catch(e){if(a1(e))return m.Xp.Log.error({logLevel:this.logLevel,tag:"@remotion/media"},`[MediaPlayer] Network/CORS error for ${this.src}`,e),{type:"network-error"};throw m.Xp.Log.error({logLevel:this.logLevel,tag:"@remotion/media"},"[MediaPlayer] Failed to initialize",e),e}finally{t.unblock()}}async seekTo(e){let t=aH({unloopedTimeInSeconds:e,playbackRate:this.playbackRate,loop:this.loop,trimBefore:this.trimBefore,trimAfter:this.trimAfter,mediaDurationInSeconds:this.totalDuration??null,fps:this.fps,ifNoMediaDuration:"infinity",src:this.src});if(null===t)throw Error("should have asserted that the time is not null");let r=this.nonceManager.createAsyncOperation();await this.seekPromiseChain,this.seekPromiseChain=this.seekToDoNotCallDirectly(t,r),await this.seekPromiseChain}async seekToDoNotCallDirectly(e,t){t.isStale()||this.getPlaybackTime()===e||await Promise.all([this.videoIteratorManager?.seek({newTime:e,nonce:t}),this.audioIteratorManager?.seek({newTime:e,nonce:t,fps:this.fps,playbackRate:this.playbackRate*this.globalPlaybackRate,getIsPlaying:()=>this.playing,scheduleAudioNode:this.scheduleAudioNode,bufferState:this.bufferState})])}async play(e){if(this.playing)return;let t=aH({unloopedTimeInSeconds:e,playbackRate:this.playbackRate,loop:this.loop,trimBefore:this.trimBefore,trimAfter:this.trimAfter,mediaDurationInSeconds:this.totalDuration??null,fps:this.fps,ifNoMediaDuration:"infinity",src:this.src});if(null===t)throw Error("should have asserted that the time is not null");this.setPlaybackTime(t,this.playbackRate*this.globalPlaybackRate),this.playing=!0,this.audioIteratorManager&&this.audioIteratorManager.resumeScheduledAudioChunks({playbackRate:this.playbackRate*this.globalPlaybackRate,scheduleAudioNode:this.scheduleAudioNode}),"suspended"===this.sharedAudioContext.state&&await this.sharedAudioContext.resume(),this.drawDebugOverlay()}delayPlaybackHandleIfNotPremounting=()=>this.isPremounting||this.isPostmounting?{unblock:()=>{}}:this.bufferState.delayPlayback();pause(){this.playing&&(this.playing=!1,this.audioIteratorManager?.pausePlayback(),this.drawDebugOverlay())}setMuted(e){this.audioIteratorManager?.setMuted(e)}setVolume(e){this.audioIteratorManager&&this.audioIteratorManager.setVolume(e)}updateAfterTrimChange(e){if(!this.audioIteratorManager&&!this.videoIteratorManager)return;let t=aH({unloopedTimeInSeconds:e,playbackRate:this.playbackRate,loop:this.loop,trimBefore:this.trimBefore,trimAfter:this.trimAfter,mediaDurationInSeconds:this.totalDuration??null,fps:this.fps,ifNoMediaDuration:"infinity",src:this.src});null!==t&&this.setPlaybackTime(t,this.playbackRate*this.globalPlaybackRate),this.audioIteratorManager?.destroyIterator()}setTrimBefore(e,t){this.trimBefore!==e&&(this.trimBefore=e,this.updateAfterTrimChange(t))}setTrimAfter(e,t){this.trimAfter!==e&&(this.trimAfter=e,this.updateAfterTrimChange(t))}setDebugOverlay(e){this.debugOverlay=e}updateAfterPlaybackRateChange(){if(!this.audioIteratorManager)return;this.setPlaybackTime(this.getPlaybackTime(),this.playbackRate*this.globalPlaybackRate);let e=this.audioIteratorManager.getAudioBufferIterator();e&&(e.moveQueuedChunksToPauseQueue(),this.playing&&this.audioIteratorManager.resumeScheduledAudioChunks({playbackRate:this.playbackRate*this.globalPlaybackRate,scheduleAudioNode:this.scheduleAudioNode}))}setPlaybackRate(e){this.playbackRate=e,this.updateAfterPlaybackRateChange()}setGlobalPlaybackRate(e){this.globalPlaybackRate=e,this.updateAfterPlaybackRateChange()}setFps(e){this.fps=e}setIsPremounting(e){this.isPremounting=e}setIsPostmounting(e){this.isPostmounting=e}setLoop(e){this.loop=e}async dispose(){if(this.initializationPromise)try{await this.initializationPromise}catch{}this.nonceManager.createAsyncOperation(),this.videoIteratorManager?.destroy(),this.audioIteratorManager?.destroyIterator(),this.input.dispose()}scheduleAudioNode=(e,t)=>{let r=(t-this.getPlaybackTime())/(this.playbackRate*this.globalPlaybackRate);r>=0?e.start(this.sharedAudioContext.currentTime+r):e.start(this.sharedAudioContext.currentTime,-r)};getPlaybackTime(){return aZ({audioSyncAnchor:this.audioSyncAnchor,currentTime:this.sharedAudioContext.currentTime,playbackRate:this.playbackRate*this.globalPlaybackRate})}setPlaybackTime(e,t){this.audioSyncAnchor=this.sharedAudioContext.currentTime-e/t}setVideoFrameCallback(e){this.onVideoFrameCallback=e}drawDebugOverlay=()=>{this.debugOverlay&&this.context&&this.canvas&&a0({context:this.context,audioTime:this.sharedAudioContext.currentTime,audioContextState:this.sharedAudioContext.state,audioSyncAnchor:this.audioSyncAnchor,audioIteratorManager:this.audioIteratorManager,playing:this.playing,videoIteratorManager:this.videoIteratorManager})}}var a6=({loop:e,mediaDurationInSeconds:t,playbackRate:r,trimAfter:a,trimBefore:i})=>{let{durationInFrames:n,fps:s}=(0,m.Bk)();return(0,f.useMemo)(()=>{if(!e||!t)return;let o=m.Xp.calculateMediaDuration({mediaDurationInFrames:t*s,playbackRate:r,trimAfter:a,trimBefore:i});return{numberOfTimes:n/o,startOffset:0,durationInFrames:o}},[n,s,e,t,r,a,i])},a5=({volume:e,mediaVolume:t,src:r,mediaType:a,playbackRate:i,displayName:n,stack:s,showInTimeline:o,premountDisplay:l,postmountDisplay:c,loopDisplay:u,trimBefore:d,trimAfter:h})=>{let p=(0,f.useContext)(m.Xp.SequenceContext),g=m.Xp.useMediaStartsAt(),{registerSequence:b,unregisterSequence:k}=(0,f.useContext)(m.Xp.SequenceManager),[y]=(0,f.useState)(()=>String(Math.random())),[w]=(0,f.useState)(()=>String(Math.random())),T=(0,m.UC)(),{volumes:S,duration:v,doesVolumeChange:x,nonce:P,rootId:I,isStudio:C,finalDisplayName:E}=m.Xp.useBasicMediaInTimeline({volume:e,mediaVolume:t,mediaType:a,src:r,displayName:n,trimBefore:d,trimAfter:h,playbackRate:i});return(0,f.useEffect)(()=>{if(!r)throw Error("No src passed");if(!C&&window.process?.env?.NODE_ENV!=="test"||!o)return;let e=u?Math.floor(T/u.durationInFrames):0;return u&&b({type:"sequence",premountDisplay:l,postmountDisplay:c,parent:p?.id??null,displayName:E,rootId:I,showInTimeline:!0,nonce:P,loopDisplay:u,stack:s,from:0,duration:v,id:y}),b({type:a,src:r,id:w,duration:u?.durationInFrames??v,from:u?e*u.durationInFrames:0,parent:u?y:p?.id??null,displayName:E,rootId:I,volume:S,showInTimeline:!0,nonce:P,startMediaFrom:0-g,doesVolumeChange:x,loopDisplay:void 0,playbackRate:i,stack:s,premountDisplay:null,postmountDisplay:null}),()=>{u&&k(y),k(w)}},[x,v,E,C,u,w,a,P,p?.id,i,c,l,b,I,y,o,r,s,g,k,S,T]),{id:w}},{useUnsafeVideoConfig:a9,Timeline:a7,SharedAudioContext:ie,useMediaMutedState:it,useMediaVolumeState:ir,useFrameForVolumeProp:ia,evaluateVolume:ii,warnAboutTooHighVolume:is,usePreload:io,SequenceContext:il}=m.Xp,ic=({src:e,playbackRate:t,logLevel:r,muted:a,volume:i,loopVolumeCurveBehavior:n,loop:s,trimAfter:o,trimBefore:l,name:c,showInTimeline:u,stack:d,disallowFallbackToHtml5Audio:h,toneFrequency:p,audioStreamIndex:g,fallbackHtml5AudioProps:b})=>{let k=a9(),y=(0,m.UC)(),w=(0,f.useRef)(null),T=(0,f.useRef)(l),S=(0,f.useRef)(o),[v,x]=(0,f.useState)(!1),[P,I]=(0,f.useState)(!1),[C]=a7.usePlayingState(),E=(0,f.useContext)(m.Xp.TimelineContext).playbackRate,F=(0,f.useContext)(ie),A=(0,m.Fx)(),[B]=it(),[D]=ir(),[R,M]=(0,f.useState)(null),_=ii({frame:ia(n??"repeat"),volume:i,mediaVolume:D});if(is(_),!k)throw Error("No video config found");if(!e)throw TypeError("No `src` was passed to .");let N=y/k.fps,L=(0,f.useRef)(N);L.current=N;let O=io(e),z=(0,f.useContext)(il),V=!!z?.premounting,U=!!z?.postmounting,$=a6({loop:s,mediaDurationInSeconds:R,playbackRate:t,trimAfter:o,trimBefore:l});a5({volume:i,mediaVolume:D,mediaType:"audio",src:e,playbackRate:t,displayName:c??null,stack:d,showInTimeline:u,premountDisplay:z?.premountDisplay??null,postmountDisplay:z?.postmountDisplay??null,loopDisplay:$,trimAfter:o,trimBefore:l});let j=(0,f.useContext)(m.Xp.BufferingContextReact);if(!j)throw Error("useMediaPlayback must be used inside a ");let H=m.Xp.useIsPlayerBuffering(j),q=(0,f.useRef)(C&&!H),X=(0,f.useRef)(V),W=(0,f.useRef)(U),K=(0,f.useRef)(E),Q=(0,f.useRef)(t);(0,f.useEffect)(()=>{if(F&&F.audioContext){try{let e=new a8({src:O,logLevel:r,sharedAudioContext:F.audioContext,loop:s,trimAfter:S.current,trimBefore:T.current,fps:k.fps,canvas:null,playbackRate:Q.current,audioStreamIndex:g??0,debugOverlay:!1,bufferState:A,isPostmounting:W.current,isPremounting:X.current,globalPlaybackRate:K.current,onVideoFrameCallback:null,playing:q.current});w.current=e,e.initialize(L.current).then(e=>{if("disposed"!==e.type){if("unknown-container-format"===e.type){if(h)throw Error(`Unknown container format ${O}, and 'disallowFallbackToHtml5Audio' was set.`);m.Xp.Log.warn({logLevel:r,tag:"@remotion/media"},`Unknown container format for ${O} (Supported formats: https://www.remotion.dev/docs/mediabunny/formats), falling back to `),I(!0);return}if("network-error"===e.type){if(h)throw Error(`Network error fetching ${O}, and 'disallowFallbackToHtml5Audio' was set.`);m.Xp.Log.warn({logLevel:r,tag:"@remotion/media"},`Network error fetching ${O}, falling back to `),I(!0);return}if("cannot-decode"===e.type){if(h)throw Error(`Cannot decode ${O}, and 'disallowFallbackToHtml5Audio' was set.`);m.Xp.Log.warn({logLevel:r,tag:"@remotion/media"},`Cannot decode ${O}, falling back to `),I(!0);return}if("no-tracks"===e.type){if(h)throw Error(`No video or audio tracks found for ${O}, and 'disallowFallbackToHtml5Audio' was set.`);m.Xp.Log.warn({logLevel:r,tag:"@remotion/media"},`No video or audio tracks found for ${O}, falling back to `),I(!0);return}"success"===e.type&&(x(!0),M(e.durationInSeconds),m.Xp.Log.trace({logLevel:r,tag:"@remotion/media"},"[AudioForPreview] MediaPlayer initialized successfully"))}}).catch(e=>{m.Xp.Log.error({logLevel:r,tag:"@remotion/media"},"[AudioForPreview] Failed to initialize MediaPlayer",e),I(!0)})}catch(e){m.Xp.Log.error({logLevel:r,tag:"@remotion/media"},"[AudioForPreview] MediaPlayer initialization failed",e),I(!0)}return()=>{w.current&&(m.Xp.Log.trace({logLevel:r,tag:"@remotion/media"},"[AudioForPreview] Disposing MediaPlayer"),w.current.dispose(),w.current=null),x(!1),I(!1)}}},[O,r,F,L,s,k.fps,g,h,A]),(0,f.useLayoutEffect)(()=>{let e=w.current;e&&(C&&!H?e.play(L.current):e.pause())},[H,r,C]),(0,f.useLayoutEffect)(()=>{let e=w.current;e&&v&&e.setTrimBefore(l,L.current)},[l,v]),(0,f.useLayoutEffect)(()=>{let e=w.current;e&&v&&e.setTrimAfter(o,L.current)},[o,v]);let G=a||B||_<=0;return((0,f.useLayoutEffect)(()=>{let e=w.current;e&&v&&e.setMuted(G)},[G,v]),(0,f.useEffect)(()=>{let e=w.current;e&&v&&e.setVolume(_)},[_,v]),(0,f.useEffect)(()=>{let e=w.current;e&&v&&e.setPlaybackRate(t)},[t,v]),(0,f.useLayoutEffect)(()=>{let e=w.current;e&&v&&e.setGlobalPlaybackRate(E)},[E,v]),(0,f.useLayoutEffect)(()=>{let e=w.current;e&&v&&e.setFps(k.fps)},[k.fps,v]),(0,f.useLayoutEffect)(()=>{let e=w.current;e&&v&&e.setLoop(s)},[s,v]),(0,f.useLayoutEffect)(()=>{let e=w.current;e&&v&&e.setIsPremounting(V)},[V,v]),(0,f.useLayoutEffect)(()=>{let e=w.current;e&&v&&e.setIsPostmounting(U)},[U,v]),(0,f.useLayoutEffect)(()=>{let e=w.current;e&&v&&(e.seekTo(N).catch(()=>{}),m.Xp.Log.trace({logLevel:r,tag:"@remotion/media"},`[AudioForPreview] Updating target time to ${N.toFixed(3)}s`))},[N,r,v]),P&&!h)?(0,aj.jsx)(m.fP,{src:e,muted:a,volume:i,startFrom:l,endAt:o,playbackRate:t,loopVolumeCurveBehavior:n,name:c,loop:s,showInTimeline:u,stack:d??void 0,toneFrequency:p,audioStreamIndex:g,pauseWhenBuffering:b?.pauseWhenBuffering,crossOrigin:b?.crossOrigin,...b}):null},iu=({loop:e,src:t,logLevel:r,muted:a,name:i,volume:n,loopVolumeCurveBehavior:s,playbackRate:o,trimAfter:l,trimBefore:c,showInTimeline:u,stack:d,disallowFallbackToHtml5Audio:h,toneFrequency:p,audioStreamIndex:g,fallbackHtml5AudioProps:b})=>{let k=io(t),y=(0,m.UC)(),w=(0,m.Bk)(),T=y/w.fps;return(0,f.useMemo)(()=>null!==aH({unloopedTimeInSeconds:T,playbackRate:o??1,loop:e??!1,trimBefore:c,trimAfter:l,mediaDurationInSeconds:1/0,fps:w.fps,ifNoMediaDuration:"infinity",src:t}),[T,e,o,t,l,c,w.fps])?(0,aj.jsx)(ic,{audioStreamIndex:g??0,src:k,playbackRate:o??1,logLevel:r??("undefined"!=typeof window?window.remotion_logLevel??"info":"info"),muted:a??!1,volume:n??1,loopVolumeCurveBehavior:s??"repeat",loop:e??!1,trimAfter:l,trimBefore:c,name:i,showInTimeline:u??!0,stack:d,disallowFallbackToHtml5Audio:h??!1,toneFrequency:p,fallbackHtml5AudioProps:b}):null},id=()=>{let e=[],t={};return{addFrame:r=>{e.push(r.timestamp),t[r.timestamp]=r},clearBeforeThreshold:r=>{for(let a of e.slice())if(a+t[a].duration{for(let r of e)t[r].close(),delete t[r];e.length=0},getSamples:(r,a)=>{let i=[];for(let n=0;n=r+a-1e-10)break;i.push(s)}}return i},getOldestTimestamp:()=>e[0],getNewestTimestamp:()=>{if(0===e.length)return null;let r=t[e[e.length-1]];return r.timestamp+r.duration},getOpenTimestamps:()=>e}},ih={},im=(e,t)=>{ih[e]||(ih[e]=!0,m.Xp.Log.warn({logLevel:t,tag:"@remotion/media"},`Audio from ${e} will need to be read from the beginning. https://www.remotion.dev/docs/media/support#matroska-limitation`))},ip=({audioSampleSink:e,isMatroska:t,startTimestamp:r,src:a,actualMatroskaTimestamps:i,logLevel:n})=>{let s=e.samples(t?0:Math.max(0,r-1.5));t&&im(a,n);let o=null,l=id(),c=Date.now(),u=async()=>{c=Date.now();let{value:e,done:t}=await s.next();if(t)return o=l.getNewestTimestamp(),null;let r=i.getRealTimestamp(e.timestamp);return null!==r&&r!==e.timestamp&&e.setTimestamp(r),i.observeTimestamp(e.timestamp),i.observeTimestamp(e.timestamp+e.duration),l.addFrame(e),e},d=async(e,t)=>{if(c=Date.now(),null!==o&&e>o)return l.clearBeforeThreshold(o-iI),[];let r=l.getSamples(e,t),a=l.getNewestTimestamp();if(null!==a&&a>=e+t-1e-10)return r;for(;;){let a=await u(),i=null===o?e:Math.min(e,o);if(l.clearBeforeThreshold(i-iI),null===a)break;if(!(a.timestamp+a.duration-1e-10<=e)){if(a.timestamp>=e+t-1e-10)break;r.push(a)}}return r},h=Promise.resolve([]);return{src:a,getSamples:(e,t)=>h=h.then(()=>d(e,t)),waitForCompletion:async()=>(await h,!0),canSatisfyRequestedTime:e=>{let t=l.getOldestTimestamp()??r;return null!==o&&e>o||tMath.abs(t-e)},logOpenFrames:()=>{let e=l.getOpenTimestamps();if(e.length>0){let t=e[0],r=e[e.length-1];m.Xp.Log.verbose({logLevel:n,tag:"@remotion/media"},"Open audio samples for src",a,`${t.toFixed(3)}...${r.toFixed(3)}`)}},getCacheStats:()=>({count:l.getOpenTimestamps().length,size:l.getOpenTimestamps().reduce((e,t)=>e+t,0)}),getLastUsed:()=>c,prepareForDeletion:()=>{l.deleteAll(),s.return().then(e=>{e.value&&e.value.close()}),o=null},startTimestamp:r,clearBeforeThreshold:l.clearBeforeThreshold,getOldestTimestamp:l.getOldestTimestamp,getNewestTimestamp:l.getNewestTimestamp}},ig=null,ib=()=>null!==new OffscreenCanvas(1,1).getContext("webgl2"),ik=()=>null!==ig?ig:ig=ib(),iy=e=>0===e.length?"(none)":1===e.length?e[0].toFixed(3):`${e[0].toFixed(3)}...${e[e.length-1].toFixed(3)}`,iw=({startTimestampInSeconds:e,endTimestampInSeconds:t,sampleIterator:r,logLevel:a,src:i})=>{m.Xp.Log.verbose({logLevel:a,tag:"@remotion/media"},`Creating keyframe bank from ${e}sec to ${t}sec`);let n={},s=[],o=Date.now(),l=0,c=({logLevel:e,timestampInSeconds:t})=>{let r=[];for(let e of s.slice())if(e!==s[s.length-1]&&e0&&m.Xp.Log.verbose({logLevel:e,tag:"@remotion/media"},`Deleted ${r.length} frame${1===r.length?"":"s"} ${iy(r)} for src ${i} because it is lower than ${t}. Remaining: ${iy(s)}`)},u=e=>{let t=s[s.length-1];if(!t)return!1;let r=n[t];return!r||aX(r.timestamp+r.duration)>aX(e)+.001},d=e=>{n[e.timestamp]=e,s.push(e.timestamp),l+=e.allocationSize(),o=Date.now()},h=async e=>{for(;!u(e);){let t=await r.next();if(t.value&&d(t.value),t.done)break;c({logLevel:a,timestampInSeconds:e-iI})}o=Date.now()},f=async r=>{o=Date.now();let a=r;if(aX(r)aX(t))return Promise.reject(Error(`Timestamp is after end timestamp (requested: ${r}sec, end: ${t}sec)`));await h(a);for(let e=s.length-1;e>=0;e--){let t=n[s[e]];if(!t)break;if(aX(t.timestamp)<=aX(a)||.001>=Math.abs(t.timestamp-a))return t}return null},p=async e=>await f(e)!==null,g=Promise.resolve(void 0);return{startTimestampInSeconds:e,endTimestampInSeconds:t,getFrameFromTimestamp:e=>g=g.then(()=>f(e)),prepareForDeletion:a=>{m.Xp.Log.verbose({logLevel:a,tag:"@remotion/media"},`Preparing for deletion of keyframe bank from ${e}sec to ${t}sec`),r.return().then(e=>(e.value&&e.value.close(),null));let i=0;for(let e of s)n[e]&&(l-=n[e].allocationSize(),n[e].close(),delete n[e],i++);return s.length=0,{framesDeleted:i}},hasTimestampInSecond:p,addFrame:d,deleteFramesBeforeTimestamp:c,src:i,getOpenFrameCount:()=>({size:l,timestamps:s}),getLastUsed:()=>o}},iT=e=>{let t=[];return{observeTimestamp:r=>{e&&t.push(r)},getRealTimestamp:r=>e?t.find(e=>.001>Math.abs(r-e))??null:r}},iS=()=>null,iv=async e=>{try{return await e.getFormat()}catch(e){if(a1(e))return"network-error";return null}},ix=async e=>{let t=new aU({formats:a_,source:new aO(e,{getRetryDelay:iS})}),r=await iv(t),a=r===aF||r===aA,i=async()=>{if("network-error"===r)return"network-error";if(null===r)return"unknown-container-format";let e=await t.getPrimaryVideoTrack();return e?await e.canDecode()?{sampleSink:new tD(e),packetSink:new tI(e)}:"cannot-decode":"no-video-track"},n=null,s=()=>n||(n=i()),o={},l=async e=>{if(null===r)return"unknown-container-format";if("network-error"===r)return"network-error";let a=(await t.getAudioTracks())[e];return a?await a.canDecode()?{sampleSink:new tN(a)}:"cannot-decode-audio":"no-audio-track"},c=e=>(o[e]||(o[e]=l(e)),o[e]);return{getVideo:()=>s(),getAudio:e=>c(e),actualMatroskaTimestamps:iT(a),isMatroska:a,getDuration:()=>t.computeDuration()}},iP=async({packetSink:e,videoSampleSink:t,startPacket:r,logLevel:a,src:i})=>{let n=await e.getNextKeyPacket(r,{verifyKeyPackets:!0}),s=t.samples(r.timestamp,n?n.timestamp:1/0);return iw({startTimestampInSeconds:r.timestamp,endTimestampInSeconds:n?n.timestamp:1/0,sampleIterator:s,logLevel:a,src:i})},iI=1,iC=(()=>{let e={},t=({src:t,bank:r,startTimestampInSeconds:a})=>{e[t]=e[t]??{},e[t][a]=r},r=async t=>{let r=0,a=0;for(let i in e)for(let n in e[i]){let{size:s,timestamps:o}=(await e[i][n]).getOpenFrameCount();r+=o.length,a+=s,0!==s&&m.Xp.Log.verbose({logLevel:t,tag:"@remotion/media"},`Open frames for src ${i}: ${iy(o)}`)}m.Xp.Log.verbose({logLevel:t,tag:"@remotion/media"},`Video cache stats: ${r} open frames, ${a} bytes`)},a=async()=>{let t=0,r=0;for(let a in e)for(let i in e[a]){let{timestamps:n,size:s}=(await e[a][i]).getOpenFrameCount();if(t+=n.length,r+=s,0===s)continue}return{count:t,totalSize:r}},i=async()=>{let t=null,r=null,a=0;for(let i in e)for(let n in e[i]){let s=await e[i][n],o=s.getLastUsed();(null===t||o{let{mostInThePastBank:{bank:r,src:a},numberOfBanks:n}=await i();if(n<2)return{finish:!0};if(r){let{framesDeleted:i}=r.prepareForDeletion(t);delete e[a][r.startTimestampInSeconds],m.Xp.Log.verbose({logLevel:t,tag:"@remotion/media"},`Deleted ${i} frames for src ${a} from ${r.startTimestampInSeconds}sec to ${r.endTimestampInSeconds}sec to free up memory.`)}return{finish:!1}},s=async(e,t)=>{let r=await iF();for(;r.totalSize>t;){let{finish:a}=await n(e);if(a)break;m.Xp.Log.verbose({logLevel:e,tag:"@remotion/media"},"Deleted oldest keyframe bank to stay under max cache size",(r.totalSize/1024/1024).toFixed(1),"out of",(t/1024/1024).toFixed(1)),r=await iF()}},o=async({timestampInSeconds:t,src:a,logLevel:i})=>{let n=t-iI;if(e[a]){for(let t of Object.keys(e[a])){let r=await e[a][t],{endTimestampInSeconds:s,startTimestampInSeconds:o}=r;s{let o=await r.getKeyPacket(a,{verifyKeyPackets:!0})??await r.getFirstPacket({verifyKeyPackets:!0});if(o?.sideData.alpha&&!ik())return"has-alpha";if(!o)return null;let l=o.timestamp,c=e[n]?.[l];if(!c){let e=iP({packetSink:r,videoSampleSink:i,startPacket:o,logLevel:s,src:n});return t({src:n,bank:e,startTimestampInSeconds:l}),e}if(await (await c).hasTimestampInSecond(a))return c;m.Xp.Log.verbose({logLevel:s,tag:"@remotion/media"},`Keyframe bank exists but frame at time ${a} does not exist anymore.`),await (await c).prepareForDeletion(s),delete e[n][l];let u=iP({packetSink:r,videoSampleSink:i,startPacket:o,logLevel:s,src:n});return t({src:n,bank:u,startTimestampInSeconds:l}),u},c=async({packetSink:e,timestamp:t,videoSampleSink:r,src:a,logLevel:i,maxCacheSize:n})=>(await s(i,n),await o({timestampInSeconds:t,src:a,logLevel:i}),await l({packetSink:e,timestamp:t,videoSampleSink:r,src:a,logLevel:i})),u=async t=>{for(let r of Object.keys(e))for(let a of Object.keys(e[r]))(await e[r][a]).prepareForDeletion(t),delete e[r][a]},d=Promise.resolve(void 0);return{requestKeyframeBank:({packetSink:e,timestamp:t,videoSampleSink:r,src:a,logLevel:i,maxCacheSize:n})=>d=d.then(()=>c({packetSink:e,timestamp:t,videoSampleSink:r,src:a,logLevel:i,maxCacheSize:n})),getCacheStats:a,clearAll:u}})(),iE=(()=>{let e=[],t=({timeInSeconds:t,src:r,audioSampleSink:a,isMatroska:i,actualMatroskaTimestamps:n,logLevel:s})=>{let o=ip({audioSampleSink:a,isMatroska:i,startTimestamp:t,src:r,actualMatroskaTimestamps:n,logLevel:s});return e.push(o),o},r=()=>{let t=null,r=null;for(let a of e){let e=a.getLastUsed();(null===t||e{let t=r();t&&(t.prepareForDeletion(),e.splice(e.indexOf(t),1))},i=t=>{let r=new Set;for(let a=0;a{for(;(await iF()).totalSize>u;)a();for(let t of e)if(t.src===r&&await t.waitForCompletion()&&t.canSatisfyRequestedTime(n))return t;for(let t=0;ts=s.then(()=>n({src:e,timeInSeconds:t,audioSampleSink:r,isMatroska:a,actualMatroskaTimestamps:i,logLevel:o,maxCacheSize:l})),getCacheStats:()=>{let t=0,r=0;for(let a of e){let{count:e,size:i}=a.getCacheStats();t+=e,r+=i}return{count:t,totalSize:r}},getIteratorMostInThePast:r,logOpenFrames:()=>{for(let t of e)t.logOpenFrames()},deleteDuplicateIterators:i}})(),iF=async()=>{let e=await iC.getCacheStats(),t=iE.getCacheStats();return{count:e.count+t.count,totalSize:e.totalSize+t.totalSize}},iA=e=>{if("undefined"!=typeof window&&void 0!==window.remotion_mediaCacheSizeInBytes&&null!==window.remotion_mediaCacheSizeInBytes)return window.remotion_mediaCacheSizeInBytes<0xf000000&&(0,m.zo)(Error(`The minimum value for the "mediaCacheSizeInBytes" prop is 240MB (251658240), got: ${window.remotion_mediaCacheSizeInBytes}`)),window.remotion_mediaCacheSizeInBytes>2097152e4&&(0,m.zo)(Error(`The maximum value for the "mediaCacheSizeInBytes" prop is 20GB (20971520000), got: ${window.remotion_mediaCacheSizeInBytes}`)),m.Xp.Log.verbose({logLevel:e,tag:"@remotion/media"},`Using cache size set using "mediaCacheSizeInBytes": ${(window.remotion_mediaCacheSizeInBytes/1024/1024).toFixed(1)} MB`),window.remotion_mediaCacheSizeInBytes;if("undefined"!=typeof window&&void 0!==window.remotion_initialMemoryAvailable&&null!==window.remotion_initialMemoryAvailable){let t=window.remotion_initialMemoryAvailable/2;return t<524288e3?(m.Xp.Log.verbose({logLevel:e,tag:"@remotion/media"},"Using cache size set based on minimum value of 500MB (which is more than half of the available system memory!)"),524288e3):t>2097152e4?(m.Xp.Log.verbose({logLevel:e,tag:"@remotion/media"},"Using cache size set based on maximum value of 20GB (which is less than half of the available system memory)"),2097152e4):(m.Xp.Log.verbose({logLevel:e,tag:"@remotion/media"},`Using cache size set based on available memory (50% of available memory): ${(t/1024/1024).toFixed(1)} MB`),t)}return 1e9},iB=null,iD=e=>null!==iB?iB:iB=iA(e),iR=e=>{let t=f.useContext(m.Xp.MaxMediaCacheSizeContext);return null===t?iD(e):t},iM=(e,t)=>{if(1!==t)for(let r=0;r32767?e[r]=32767:e[r]=a}},i_=e=>e%1<1e-7?Math.floor(e):e%1>.9999999?Math.ceil(e):e,iN=({srcNumberOfChannels:e,sourceChannels:t,destination:r,targetFrames:a,chunkSize:i})=>{let n=(r,a,i)=>{let n=i_(r),s=i_(a),o=Math.floor(n),l=Math.ceil(n),c=n-o,u=s-Math.floor(s),d=Math.floor(s),h=0,m=0;c>0&&(h+=t[o*e+i]*(1-c),m+=1-c);for(let r=l;r0&&(h+=t[d*e+i]*u,m+=u),h/m};for(let t=0;tt&&"extend"!==e?i%(Math.floor(r*a)-n)+n:i+n,iO=e=>{let t=Math.abs(e%1);return t<1e-7?e<0?Math.ceil(e):Math.floor(e):t>.9999999?e<0?Math.floor(e):Math.ceil(e):e},iz=e=>Math.ceil(iO(e)),iV=({audioData:e,trimStartInSeconds:t,trimEndInSeconds:r,playbackRate:a,audioDataTimestamp:i,isLast:n})=>{let{numberOfChannels:s,sampleRate:o,numberOfFrames:l}=e,c=o/48e3,u=Math.floor(iO(t*e.sampleRate)),d=l-r*e.sampleRate-u,h=n?iz(d):Math.round(d),m=n?iz(d/c/a):Math.round(d/c/a);if(0===m)throw Error("Cannot resample - the given sample rate would result in less than 1 sample");let f=new Int16Array(s*h);e.copyTo(f,{planeIndex:0,format:"s16",frameOffset:u,frameCount:h});let p=new Int16Array(2*m),g=u/e.sampleRate*1e6;return m===h&&2===s&&1===a?{data:f,numberOfFrames:m,timestamp:1e6*i+iO(g),durationInMicroSeconds:iO(m/48e3*1e6)}:(iN({srcNumberOfChannels:s,sourceChannels:f,destination:p,targetFrames:m,chunkSize:h/m}),{data:p,numberOfFrames:m,timestamp:1e6*i+iO(g),durationInMicroSeconds:iO(m/48e3*1e6)})},iU=e=>{let t=0,r=0,{timestamp:a}=e[0];for(let a of e)t+=a.numberOfFrames,r+=a.durationInMicroSeconds;let i=new Int16Array(2*t),n=0;for(let t of e)i.set(t.data,n),n+=t.data.length;return{data:i,numberOfFrames:t,timestamp:iO(a),durationInMicroSeconds:iO(r)}},i$={},ij=(e,t)=>{let r=i$[e];return r||(m.Xp.Log.verbose({logLevel:t,tag:"@remotion/media"},`Sink for ${e} was not found, creating new sink`),r=ix(e),i$[e]=r),r},iH=async({src:e,timeInSeconds:t,durationInSeconds:r,logLevel:a,loop:i,playbackRate:n,audioStreamIndex:s,trimBefore:o,trimAfter:l,fps:c,maxCacheSize:u})=>{let{getAudio:d,actualMatroskaTimestamps:h,isMatroska:m,getDuration:f}=await ij(e,a),p=null;i&&(p=await f());let g=await d(s);if("network-error"===g)return"network-error";if("no-audio-track"===g)return{data:null,durationInSeconds:null};if("cannot-decode-audio"===g)return"cannot-decode";if("unknown-container-format"===g)return"unknown-container-format";let b=aH({loop:i,mediaDurationInSeconds:p,unloopedTimeInSeconds:t,src:e,trimAfter:l,playbackRate:n,trimBefore:o,fps:c,ifNoMediaDuration:"fail"});if(null===b)return{data:null,durationInSeconds:p};try{let t=await iE.getIterator({src:e,timeInSeconds:b,audioSampleSink:g.sampleSink,isMatroska:m,actualMatroskaTimestamps:h,logLevel:a,maxCacheSize:u}),i=r*n,s=await t.getSamples(b,i);iE.logOpenFrames();let o=[];for(let e=0;eiq=iq.then(()=>iH(e)),iW=async({src:e,timeInSeconds:t,logLevel:r,loop:a,trimAfter:i,trimBefore:n,playbackRate:s,fps:o,maxCacheSize:l})=>{let c=await ij(e,r),u=await c.getVideo();if("no-video-track"===u)throw Error(`No video track found for ${e}`);if("cannot-decode"===u)return{type:"cannot-decode",durationInSeconds:await c.getDuration()};if("unknown-container-format"===u)return{type:"unknown-container-format"};if("network-error"===u)return{type:"network-error"};let d=null;a&&(d=await c.getDuration());let h=aH({loop:a,mediaDurationInSeconds:d,unloopedTimeInSeconds:t,src:e,trimAfter:i,playbackRate:s,trimBefore:n,fps:o,ifNoMediaDuration:"fail"});if(null===h)return{type:"success",frame:null,durationInSeconds:await c.getDuration()};let m=await iC.requestKeyframeBank({packetSink:u.packetSink,videoSampleSink:u.sampleSink,timestamp:h,src:e,logLevel:r,maxCacheSize:l});return"has-alpha"===m?{type:"cannot-decode-alpha",durationInSeconds:await c.getDuration()}:m?{type:"success",frame:await m.getFrameFromTimestamp(h),durationInSeconds:await c.getDuration()}:{type:"success",frame:null,durationInSeconds:await c.getDuration()}},iK=Promise.resolve(void 0),iQ=e=>iK=iK.then(()=>iW(e)),iG=async({frame:e,rotation:t})=>{if(0===t){let t=await createImageBitmap(e);return e.close(),t}let r=90===t||270===t?e.displayHeight:e.displayWidth,a=90===t||270===t?e.displayWidth:e.displayHeight,i=new OffscreenCanvas(r,a),n=i.getContext("2d");if(!n)throw Error("Could not get 2d context");i.width=r,i.height=a,90===t?n.translate(r,0):180===t?n.translate(r,a):270===t&&n.translate(0,a),n.rotate(Math.PI/180*t),n.drawImage(e,0,0);let s=await createImageBitmap(i);return e.close(),s},iJ=async({src:e,timeInSeconds:t,logLevel:r,durationInSeconds:a,playbackRate:i,includeAudio:n,includeVideo:s,loop:o,audioStreamIndex:l,trimAfter:c,trimBefore:u,fps:d,maxCacheSize:h})=>{try{let[m,f]=await Promise.all([s?iQ({src:e,timeInSeconds:t,logLevel:r,loop:o,trimAfter:c,playbackRate:i,trimBefore:u,fps:d,maxCacheSize:h}):null,n?iX({src:e,timeInSeconds:t,durationInSeconds:a,logLevel:r,loop:o,playbackRate:i,audioStreamIndex:l,trimAfter:c,fps:d,trimBefore:u,maxCacheSize:h}):null]);if(m?.type==="cannot-decode")return{type:"cannot-decode",durationInSeconds:m.durationInSeconds};if(m?.type==="unknown-container-format")return{type:"unknown-container-format"};if(m?.type==="cannot-decode-alpha")return{type:"cannot-decode-alpha",durationInSeconds:m.durationInSeconds};if(m?.type==="network-error")return{type:"network-error"};if("unknown-container-format"===f)return null!==m&&m?.frame?.close(),{type:"unknown-container-format"};if("network-error"===f)return null!==m&&m?.frame?.close(),{type:"network-error"};if("cannot-decode"===f)return m?.type==="success"&&null!==m.frame&&m?.frame.close(),{type:"cannot-decode",durationInSeconds:m?.type==="success"?m.durationInSeconds:null};if(!m?.frame)return{type:"success",frame:null,audio:f?.data??null,durationInSeconds:f?.durationInSeconds??null};return{type:"success",frame:await iG({frame:m.frame.toVideoFrame(),rotation:m.frame.rotation}),audio:f?.data??null,durationInSeconds:f?.durationInSeconds??null}}catch(e){if(a1(e))return{type:"network-error"};throw e}},iY=null,iZ=e=>iY||(iY=new Promise(t=>{let r=a=>{"main-tab-ready"===a.data.type&&(t(),e.removeEventListener("message",r))};e.addEventListener("message",r)}));"undefined"!=typeof window&&window.remotion_broadcastChannel&&window.remotion_isMainTab&&(window.remotion_broadcastChannel.addEventListener("message",async e=>{let t=e.data;if("request"===t.type)try{let e=await iJ({src:t.src,timeInSeconds:t.timeInSeconds,logLevel:t.logLevel,durationInSeconds:t.durationInSeconds,playbackRate:t.playbackRate,includeAudio:t.includeAudio,includeVideo:t.includeVideo,loop:t.loop,audioStreamIndex:t.audioStreamIndex,trimAfter:t.trimAfter,trimBefore:t.trimBefore,fps:t.fps,maxCacheSize:t.maxCacheSize});if("cannot-decode"===e.type){let r={type:"response-cannot-decode",id:t.id,durationInSeconds:e.durationInSeconds};window.remotion_broadcastChannel.postMessage(r);return}if("cannot-decode-alpha"===e.type){let r={type:"response-cannot-decode-alpha",id:t.id,durationInSeconds:e.durationInSeconds};window.remotion_broadcastChannel.postMessage(r);return}if("network-error"===e.type){let e={type:"response-network-error",id:t.id};window.remotion_broadcastChannel.postMessage(e);return}if("unknown-container-format"===e.type){let e={type:"response-unknown-container-format",id:t.id};window.remotion_broadcastChannel.postMessage(e);return}let{frame:r,audio:a,durationInSeconds:i}=e,n=r?await createImageBitmap(r):null;r&&r.close();let s={type:"response-success",id:t.id,frame:n,audio:a,durationInSeconds:i??null};window.remotion_broadcastChannel.postMessage(s)}catch(r){let e={type:"response-error",id:t.id,errorStack:r.stack??"No stack trace"};window.remotion_broadcastChannel.postMessage(e)}else throw Error("Invalid message: "+JSON.stringify(t))}),(e=>{e.postMessage({type:"main-tab-ready"});let t=0,r=setInterval(()=>{e.postMessage({type:"main-tab-ready"}),++t>30&&clearInterval(r)},300)})(window.remotion_broadcastChannel));var i0=async({src:e,timeInSeconds:t,logLevel:r,durationInSeconds:a,playbackRate:i,includeAudio:n,includeVideo:s,isClientSideRendering:o,loop:l,audioStreamIndex:c,trimAfter:u,trimBefore:d,fps:h,maxCacheSize:m})=>{let f;if(o||window.remotion_isMainTab)return iJ({logLevel:r,src:e,timeInSeconds:t,durationInSeconds:a,playbackRate:i,includeAudio:n,includeVideo:s,loop:l,audioStreamIndex:c,trimAfter:u,trimBefore:d,fps:h,maxCacheSize:m});await iZ(window.remotion_broadcastChannel);let p=crypto.randomUUID(),g=new Promise((e,t)=>{let r=a=>{let i=a.data;if(i&&"main-tab-ready"!==i.type&&i.id===p){if("response-success"===i.type){e({type:"success",frame:i.frame?i.frame:null,audio:i.audio?i.audio:null,durationInSeconds:i.durationInSeconds?i.durationInSeconds:null}),window.remotion_broadcastChannel.removeEventListener("message",r);return}if("response-error"===i.type){t(i.errorStack),window.remotion_broadcastChannel.removeEventListener("message",r);return}if("response-cannot-decode"===i.type){e({type:"cannot-decode",durationInSeconds:i.durationInSeconds}),window.remotion_broadcastChannel.removeEventListener("message",r);return}if("response-network-error"===i.type){e({type:"network-error"}),window.remotion_broadcastChannel.removeEventListener("message",r);return}if("response-unknown-container-format"===i.type){e({type:"unknown-container-format"}),window.remotion_broadcastChannel.removeEventListener("message",r);return}if("response-cannot-decode-alpha"===i.type){e({type:"cannot-decode-alpha",durationInSeconds:i.durationInSeconds}),window.remotion_broadcastChannel.removeEventListener("message",r);return}throw Error(`Invalid message: ${JSON.stringify(i)}`)}};window.remotion_broadcastChannel.addEventListener("message",r)});return window.remotion_broadcastChannel.postMessage({type:"request",src:e,timeInSeconds:t,id:p,logLevel:r,durationInSeconds:a,playbackRate:i,includeAudio:n,includeVideo:s,loop:l,audioStreamIndex:c,trimAfter:u,trimBefore:d,fps:h,maxCacheSize:m}),Promise.race([g.then(e=>(clearTimeout(f),e)),new Promise((r,a)=>{f=setTimeout(()=>{a(Error(`Timeout while extracting frame at time ${t}sec from ${e}`))},Math.max(3e3,window.remotion_puppeteerTimeout-5e3))})])},i1=({volume:e,playbackRate:t,src:r,muted:a,loopVolumeCurveBehavior:i,delayRenderRetries:n,delayRenderTimeoutInMilliseconds:s,logLevel:o=window.remotion_logLevel??"info",loop:l,fallbackHtml5AudioProps:c,audioStreamIndex:u,showInTimeline:d,style:h,name:p,disallowFallbackToHtml5Audio:g,toneFrequency:b,trimAfter:k,trimBefore:y})=>{let w=(0,m.UC)(),T=m.Xp.useTimelinePosition(),S=m.Xp.useUnsafeVideoConfig(),{registerRenderAsset:v,unregisterRenderAsset:x}=(0,f.useContext)(m.Xp.RenderAssetManager),P=m.Xp.useMediaStartsAt(),I=(0,m.OK)();if(!S)throw Error("No video config found");if(!r)throw TypeError("No `src` was passed to