PageSourceSearch

https://wan-3.io/assets/index-B0i0hUUa.js

js wan-3.io collected 2026-10-09 00:03:34 UTC 537,251 bytes, 13 lines download raw bytes

1function g(r){if(!r)throw new Error("Assertion failed.")}const Cr=r=>{const e=(r%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${r}.`)},re=r=>r&&r[r.length-1],Tt=r=>r>=0&&r<2**32,z=r=>{let e=0;for(;r.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+r.readBits(e)},ct=r=>{const e=z(r);return(e&1)===0?-(e>>1):e+1>>1},ke=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),K=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),xe=new TextDecoder,Ke=new TextEncoder,In=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),nr={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},rt=In(nr),sr={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},it=In(sr),ar={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},nt=In(ar),En=r=>!!r&&!!r.primaries&&!!r.transfer&&!!r.matrix&&r.fullRange!==void 0,ec=r=>!r||r.primaries==null&&r.transfer==null&&r.matrix==null&&r.fullRange==null,wa={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},ui=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r);class or{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const t=new Promise(n=>{let s=!1;e=()=>{s||(n(),this.pending--,s=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,await i,e}}const tc=/^[0-9a-fA-F]+$/,Ir=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),rc=r=>{g(r.length%2===0);const e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.slice(t,t+2),16);return e},es=r=>(r=r>>1&1431655765|(r&1431655765)<<1,r=r>>2&858993459|(r&858993459)<<2,r=r>>4&252645135|(r&252645135)<<4,r=r>>8&16711935|(r&16711935)<<8,r=r>>16&65535|(r&65535)<<16,r>>>0),Mr=(r,e,t)=>{let i=0,n=r.length-1,s=-1;for(;i<=n;){const a=i+n>>1,o=t(r[a]);o===e?(s=a,n=a-1):o<e?i=a+1:n=a-1}return s},X=(r,e,t)=>{let i=0,n=r.length-1,s=-1;for(;i<=n;){const a=i+(n-i+1)/2|0;t(r[a])<=e?(s=a,i=a+1):n=a-1}return s},ts=(r,e,t)=>{const i=X(r,t(e),t);r.splice(i+1,0,e)},se=()=>{let r,e;return{promise:new Promise((i,n)=>{r=i,e=n}),resolve:r,reject:e}},an=(r,e)=>{const t=r.indexOf(e);t!==-1&&r.splice(t,1)},ka=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return r[t]},_n=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1},ic=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},nc=r=>{if(!(Symbol.iterator in r)&&!(Symbol.asyncIterator in r))throw new TypeError("Argument must be an iterable or async iterable.")},Fe=r=>{throw new Error(`Unexpected value: ${r}`)},di=(r,e,t)=>{const i=r.getUint8(e),n=r.getUint8(e+1),s=r.getUint8(e+2);return t?i|n<<8|s<<16:i<<16|n<<8|s},sc=(r,e,t)=>di(r,e,t)<<8>>8,vn=(r,e,t,i)=>{t=t>>>0,t=t&16777215,i?(r.setUint8(e,t&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t>>>16&255)):(r.setUint8(e,t>>>16&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t&255))},ac=(r,e,t,i)=>{t=oe(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),vn(r,e,t,i)},oe=(r,e,t)=>Math.max(e,Math.min(t,r)),oc=(r,e,t)=>r+(e-r)*t,ye="und",Er=r=>{const e=Math.round(r);return Math.abs(r/e-1)<10*Number.EPSILON?e:r},on=(r,e)=>Math.round(r/e)*e,ei=(r,e)=>Math.round(r*e)/e,_i=(r,e)=>Math.floor(r/e)*e,rs=(r,e)=>Math.floor(r*e)/e,cc=r=>{let e=0;for(;r;)e++,r>>=1;return e},cn=r=>{let e=0;for(;r!==0;)r&=r-1,e++;return e},lc=/^[a-z]{3}$/,_r=r=>lc.test(r),wt=1e6*(1+Number.EPSILON),uc=(r,e)=>{const t=r<0?-1:1;r=Math.abs(r);let i=0,n=1,s=1,a=0,o=r;for(;;){const c=Math.floor(o),l=c*s+i,u=c*a+n;if(u>e)return{num:t*s,den:a};if(i=s,n=a,s=l,a=u,o=1/(o-c),!isFinite(o))break}return{num:t*s,den:a}};class fi{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let vi=null;const Tr=()=>vi!==null?vi:vi=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let Ai=null;const ba=()=>Ai!==null?Ai:Ai=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox");let Bi=null;const ln=()=>Bi!==null?Bi:Bi=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),hi=r=>typeof globalThis.isSecureContext<"u"&&!globalThis.isSecureContext?`${r} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`:`${r} is not available in this environment.`,dc=(async()=>{})().constructor,A=r=>r instanceof dc||r instanceof Promise?!0:typeof r?.then=="function",Vt=(r,e)=>r!==-1?r:e,is=(r,e,t,i)=>r<=i&&t<=e,Ta=function*(r){for(const e in r){const t=r[e];t!==void 0&&(yield{key:e,value:t})}},Sa=r=>{const e=atob(r),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t},fc=(r,e)=>{if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0},An=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},zr=r=>typeof r=="number"&&!Number.isNaN(r),yt=(r,e)=>{if(e.includes("://"))return e;if(r.includes("://")){const o=r.indexOf("?");o!==-1&&(r=r.slice(0,o))}let t;if(e.startsWith("/")){const o=r.indexOf("://");if(o===-1)t=e;else{const c=r.indexOf("/",o+3);c===-1?t=r+e:t=r.slice(0,c)+e}}else{const o=r.lastIndexOf("/");o===-1?t=e:t=r.slice(0,o+1)+e}let i="";const n=t.indexOf("://");if(n!==-1){const o=t.indexOf("/",n+3);o!==-1&&(i=t.slice(0,o),t=t.slice(o))}const s=t.split("/"),a=[];for(const o of s)o===".."?a.pop():o!=="."&&a.push(o);return i+a.join("/")},wr=(r,e)=>{let t=0;for(let i=0;i<r.length;i++)e(r[i])&&t++;return t},Bn=(r,e)=>{let t=-1,i=1/0;for(let n=0;n<r.length;n++){const s=e(r[n]);s<i&&(i=s,t=n)}return t},vr=r=>{g(Number.isInteger(r.num)),g(Number.isInteger(r.den)),g(r.den!==0);let e=Math.abs(r.num),t=Math.abs(r.den);for(;t!==0;){const n=e%t;e=t,t=n}const i=e||1;return{num:r.num/i,den:r.den/i}},Fi=(r,e)=>{if(typeof r!="object"||!r)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)},xa=r=>new Promise(e=>setTimeout(e,r)),ns=r=>Array.isArray(r)?r:[r];class Or{constructor(){this._listeners=new Map}on(e,t,i){this._listeners.has(e)||this._listeners.set(e,new Set);const n={fn:t,once:i?.once??!1};return this._listeners.get(e).add(n),()=>{this._listeners.get(e)?.delete(n)}}_emit(...e){const[t,i]=e,n=this._listeners.get(t);if(n)for(const s of n){try{s.fn(i)}catch(a){console.error(a)}s.once&&n.delete(s)}}}const Nt=r=>Math.ceil(r/2)*2,hc=r=>r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype&&Object.values(r).every(e=>typeof e=="string");var He;(function(r){r[r.Silent=0]="Silent",r[r.Errors=1]="Errors",r[r.Warnings=2]="Warnings",r[r.Info=3]="Info"})(He||(He={}));class H{constructor(){}static get level(){return H._level}static set level(e){if(e!==He.Silent&&e!==He.Errors&&e!==He.Warnings&&e!==He.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");H._level=e}static get _emitter(){return H._emitterInstance??=new Or}static on(e,t,i){return H._emitter.on(e,t,i)}
1static _error(...e){H._emitter._emit("error",e),H._level>=He.Errors&&console.error(...e)}static _warn(...e){H._emitter._emit("warn",e),H._level>=He.Warnings&&console.warn(...e)}static _info(...e){H._emitter._emit("info",e),H._level>=He.Info&&console.info(...e)}}H._level=He.Info;H._emitterInstance=null;class Yt{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof t!="string")throw new TypeError("mimeType must be a string.")}}class Pa{constructor(e,t,i,n){if(this.data=e,this.mimeType=t,this.name=i,this.description=n,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("description, when provided, must be a string.")}}const un=r=>{if(!r||typeof r!="object")throw new TypeError("tags must be an object.");if(r.title!==void 0&&typeof r.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(r.description!==void 0&&typeof r.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(r.artist!==void 0&&typeof r.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(r.album!==void 0&&typeof r.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(r.albumArtist!==void 0&&typeof r.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(r.trackNumber!==void 0&&(!Number.isInteger(r.trackNumber)||r.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(r.tracksTotal!==void 0&&(!Number.isInteger(r.tracksTotal)||r.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(r.discNumber!==void 0&&(!Number.isInteger(r.discNumber)||r.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(r.discsTotal!==void 0&&(!Number.isInteger(r.discsTotal)||r.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(r.genre!==void 0&&typeof r.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(r.date!==void 0&&(!(r.date instanceof Date)||Number.isNaN(r.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(r.lyrics!==void 0&&typeof r.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(r.images!==void 0){if(!Array.isArray(r.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of r.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(r.comment!==void 0&&typeof r.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(r.raw!==void 0){if(!r.raw||typeof r.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(r.raw))if(e!==null&&typeof e!="string"&&!(e instanceof Uint8Array)&&!(e instanceof Yt)&&!(e instanceof Pa)&&!hc(e))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}},ft={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},mc=r=>{if(!r||typeof r!="object")throw new TypeError("disposition must be an object.");if(r.default!==void 0&&typeof r.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(r.primary!==void 0&&typeof r.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(r.forced!==void 0&&typeof r.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(r.original!==void 0&&typeof r.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(r.commentary!==void 0&&typeof r.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(r.hearingImpaired!==void 0&&typeof r.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(r.visuallyImpaired!==void 0&&typeof r.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};class G{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,i=7-(this.pos&7),n=(t&1<<i)>>i;return this.pos++,n}readBits(e){if(e===1)return this.readBit();let t=0;for(let i=0;i<e;i++)t<<=1,t|=this.readBit();return t}writeBits(e,t){const i=this.pos+e;for(let n=this.pos;n<i;n++){const s=Math.floor(n/8);let a=this.bytes[s];const o=7-(n&7);a&=~(1<<o),a|=(t&1<<i-n-1)>>i-n-1<<o,this.bytes[s]=a}this.pos=i}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}
1getBitsLeft(){return this.bytes.length*8-this.pos}clone(){const e=new G(this.bytes);return e.pos=this.pos,e}}const Ot=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Dr=[-1,1,2,3,4,5,6,8],Fn=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new G(r),t=Ri(e),{frequencyIndex:i,sampleRate:n}=Mi(e),s=e.readBits(4);let a=null;s>=1&&s<=7&&(a=Dr[s]);let o=t,c=!1,l=n;if(t===5||t===29)c=t===29,l=Mi(e).sampleRate,o=Ri(e),o===22&&e.skipBits(4);else for(;e.getBitsLeft()>15;){const u=e.pos;if(e.readBits(11)!==695){e.pos=u+1;continue}Ri(e)===5&&e.readBits(1)&&(l=Mi(e).sampleRate,e.getBitsLeft()>11&&e.readBits(11)===1352&&(c=!!e.readBits(1)));break}return a!==null&&a>1&&(c=!1),{objectType:t,coreObjectType:o,frequencyIndex:i,channelConfiguration:s,outputSampleRate:l,outputNumberOfChannels:c&&a===1?2:a}},Ri=r=>{const e=r.readBits(5);return e===31?32+r.readBits(6):e},Mi=r=>{const e=r.readBits(4);return e===15?{frequencyIndex:e,sampleRate:r.readBits(24)}:{frequencyIndex:e,sampleRate:e<Ot.length?Ot[e]:null}},Ca=r=>{const e=r.objectType===5||r.objectType===29,t=r.objectType===29,i=e?r.outputSampleRate/2:r.outputSampleRate,n=t?1:r.outputNumberOfChannels,s=Dr.indexOf(n);if(s===-1)throw new TypeError(`Unsupported number of channels: ${r.outputNumberOfChannels}`);let a=16;r.objectType>=32&&(a+=6),dn(i)===15&&(a+=24),e&&(a+=9,dn(r.outputSampleRate)===15&&(a+=24));const o=Math.ceil(a/8),c=new Uint8Array(o),l=new G(c);return ss(l,r.objectType),as(l,i),l.writeBits(4,s),e&&(as(l,r.outputSampleRate),ss(l,2)),l.writeBits(3,0),c},ss=(r,e)=>{e<32?r.writeBits(5,e):(r.writeBits(5,31),r.writeBits(6,e-32))},as=(r,e)=>{const t=dn(e);r.writeBits(4,t),t===15&&r.writeBits(24,e)},dn=r=>{const e=Ot.indexOf(r);return e===-1?15:e};const mi=[48e3,44100,32e3],Ia=[24e3,22050,16e3];var fe;(function(r){r[r.NON_IDR_SLICE=1]="NON_IDR_SLICE",r[r.SLICE_DPA=2]="SLICE_DPA",r[r.SLICE_DPB=3]="SLICE_DPB",r[r.SLICE_DPC=4]="SLICE_DPC",r[r.IDR=5]="IDR",r[r.SEI=6]="SEI",r[r.SPS=7]="SPS",r[r.PPS=8]="PPS",r[r.AUD=9]="AUD",r[r.SPS_EXT=13]="SPS_EXT"})(fe||(fe={}));var ce;(function(r){r[r.RASL_N=8]="RASL_N",r[r.RASL_R=9]="RASL_R",r[r.BLA_W_LP=16]="BLA_W_LP",r[r.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",r[r.VPS_NUT=32]="VPS_NUT",r[r.SPS_NUT=33]="SPS_NUT",r[r.PPS_NUT=34]="PPS_NUT",r[r.AUD_NUT=35]="AUD_NUT",r[r.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",r[r.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(ce||(ce={}));const Nr=function*(r){let e=0,t=-1;for(;e<r.length-2;){const i=r.indexOf(0,e);if(i===-1||i>=r.length-2)break;e=i;let n=0;if(e+3<r.length&&r[e+1]===0&&r[e+2]===0&&r[e+3]===1?n=4:r[e+1]===0&&r[e+2]===1&&(n=3),n===0){e++;continue}t!==-1&&e>t&&(yield{offset:t,length:e-t}),t=e+n,e=t}t!==-1&&t<r.length&&(yield{offset:t,length:r.length-t})},Ea=function*(r,e){let t=0;const i=new DataView(r.buffer,r.byteOffset,r.byteLength);for(;t+e<=r.length;){let n;e===1?n=i.getUint8(t):e===2?n=i.getUint16(t,!1):e===3?n=di(i,t,!1):(g(e===4),n=i.getUint32(t,!1)),t+=e,yield{offset:t,length:n},t+=n}},_a=(r,e)=>{if(e.description){const n=(ke(e.description)[4]&3)+1;return Ea(r,n)}else return Nr(r)},pi=r=>r&31,gi=r=>{const e=[],t=r.length;for(let i=0;i<t;i++)i+2<t&&r[i]===0&&r[i+1]===0&&r[i+2]===3?(e.push(0,0),i+=2):e.push(r[i]);return new Uint8Array(e)},zi=new Uint8Array([0,0,0,1]),va=r=>{const e=r.reduce((n,s)=>n+zi.byteLength+s.byteLength,0),t=new Uint8Array(e);let i=0;for(const n of r)t.set(zi,i),i+=zi.byteLength,t.set(n,i),i+=n.byteLength;return t},Rn=(r,e)=>{const t=r.reduce((s,a)=>s+e+a.byteLength,0),i=new Uint8Array(t);let n=0;for(const s of r){const a=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(e){case 1:a.setUint8(n,s.byteLength);break;case 2:a.setUint16(n,s.byteLength,!1);break;case 3:vn(a,n,s.byteLength,!1);break;case 4:a.setUint32(n,s.byteLength,!1);break}n+=e,i.set(s,n),n+=s.byteLength}return i},pc=(r,e)=>{if(e.description){const n=(ke(e.description)[4]&3)+1;return Rn(r,n)}else return va(r)},yi=r=>{try{const e=[],t=[],i=[];for(const o of Nr(r)){const c=r.subarray(o.offset,o.offset+o.length),l=pi(c[0]);l===fe.SPS?e.push(c):l===fe.PPS?t.push(c):l===fe.SPS_EXT&&i.push(c)}if(e.length===0||t.length===0)return null;const n=e[0],s=wi(n);g(s!==null);const a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:t,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?i:null}}catch(e){return H._error("Error building AVC Decoder Configuration Record:",e),null}},gc=r=>{const e=[];e.push(r.configurationVersion),e.push(r.avcProfileIndication),e.push(r.profileCompatibility),e.push(r.avcLevelIndication),e.push(252|r.lengthSizeMinusOne&3),e.push(224|r.sequenceParameterSets.length&31);for(const t of r.sequenceParameterSets){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(t[n])}e.push(r.pictureParameterSets.length);for(const t of r.pictureParameterSets){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(t[n])}if(r.avcProfileIndication===100||r.avcProfileIndication===110||r.avcProfileIndication===122||r.avcProfileIndication===144){g(r.chromaFormat!==null),g(r.bitDepthLumaMinus8!==null),g(r.bitDepthChromaMinus8!==null),g(r.sequenceParameterSetExt!==null),e.push(252|r.chromaFormat&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.sequenceParameterSetExt.length);for(const t of r.sequenceParameterSetExt){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(t[n])}}return new Uint8Array(e)},Aa=r=>{try{const e=K(r);let t=0;const i=e.getUint8(t++),n=e.getUint8(t++),s=e.getUint8(t++),a=e.getUint8(t++),o=e.getUint8(t++)&3,c=e.getUint8(t++)&31,l=[];for(let h=0;h<c;h++){const p=e.getUint16(t,!1);t+=2,l.push(r.subarray(t,t+p)),t+=p}const u=e.getUint8(t++),d=[];for(let h=0;h<u;h++){const p=e.getUint16(t,!1);t+=2,d.push(r.subarray(t,t+p)),t+=p}const f={configurationVersion:i,avcProfileIndication:n,profileCompatibility:s,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((n===100||n===110||n===122||n===144)&&t+4<=r.length){const h=e.getUint8(t++)&3,p=e.getUint8(t++)&7,m=e.getUint8(t++)&7,y=e.getUint8(t++);f.chromaFormat=h,f.bitDepthLumaMinus8=p,f.bitDepthChromaMinus8=m;const w=[];for(let k=0;k<y;k++){const b=e.getUint16(t,!1);t+=2,w.push(r.subarray(t,t+b)),t+=b}f.sequenceParameterSetExt=w}return f}catch(e){return H._error("Error deserializing AVC Decoder Configuration Record:",e),null}},Ba={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},wi=r=>{try{const e=new G(gi(r));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;const i=e.readAlignedByte(),n=e.readAlignedByte(),s=e.readAlignedByte();z(e);let a=1,o=0,c=0,l=0;if((i===100||i===110||i===122||i===244||i===44||i===83||i===86||i===118||i===128)&&(a=z(e),a===3&&(l=e.readBits(1)),o=z(e),c=z(e),e.skipBits(1),e.readBits(1))){for(let v=0;v<(a!==3?8:12);v++)if(e.readBits(1)){const O=v<6?16:64;let N=8,D=8;for(let $=0;$<O;$++){if(D!==0){const J=ct(e);D=(N+J+256)%256}N=D===0?N:D}}}z(e);const u=z(e);
1if(u===0)z(e);else if(u===1){e.skipBits(1),ct(e),ct(e);const _=z(e);for(let v=0;v<_;v++)ct(e)}z(e),e.skipBits(1);const d=z(e),f=z(e),h=16*(d+1),p=16*(f+1);let m=h,y=p;const w=e.readBits(1);if(w||e.skipBits(1),e.skipBits(1),e.readBits(1)){const _=z(e),v=z(e),R=z(e),O=z(e);let N,D;if((l===0?a:0)===0)N=1,D=2-w;else{const J=a===3?1:2,ue=a===1?2:1;N=J,D=ue*(2-w)}m-=N*(_+v),y-=D*(R+O)}let b=2,S=2,T=2,P=0,I={num:1,den:1},C=null,x=null;if(e.readBits(1)){if(e.readBits(1)){const ue=e.readBits(8);if(ue===255)I={num:e.readBits(16),den:e.readBits(16)};else{const Ae=Ba[ue];Ae&&(I=Ae)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),P=e.readBits(1),e.readBits(1)&&(b=e.readBits(8),S=e.readBits(8),T=e.readBits(8))),e.readBits(1)&&(z(e),z(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));const D=e.readBits(1);D&&os(e);const $=e.readBits(1);$&&os(e),(D||$)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),z(e),z(e),z(e),z(e),C=z(e),x=z(e))}if(C===null){g(x===null);const _=n&16;if((i===44||i===86||i===100||i===110||i===122||i===244)&&_)C=0,x=0;else{const v=d+1,R=f+1,O=(2-w)*R,N=ii.find($=>$.level>=s)??re(ii),D=Math.min(Math.floor(N.maxDpbMbs/(v*O)),16);C=D,x=D}}return g(x!==null),{profileIdc:i,constraintFlags:n,levelIdc:s,frameMbsOnlyFlag:w,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:h,codedHeight:p,displayWidth:m,displayHeight:y,pixelAspectRatio:I,colourPrimaries:b,matrixCoefficients:T,transferCharacteristics:S,fullRangeFlag:P,numReorderFrames:C,maxDecFrameBuffering:x}}catch(e){return H._error("Error parsing AVC SPS:",e),null}},os=r=>{const e=z(r);r.skipBits(4),r.skipBits(4);for(let t=0;t<=e;t++)z(r),z(r),r.skipBits(1);r.skipBits(5),r.skipBits(5),r.skipBits(5),r.skipBits(5)},yc=(r,e)=>{if(e.description){const n=(ke(e.description)[21]&3)+1;return Rn(r,n)}else return va(r)},ti=(r,e)=>{if(e.description){const n=(ke(e.description)[21]&3)+1;return Ea(r,n)}else return Nr(r)},tr=r=>r>>1&63,Mn=r=>{try{const e=new G(gi(r));e.skipBits(16),e.readBits(4);const t=e.readBits(3),i=e.readBits(1),{general_profile_space:n,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:l}=wc(e,t);z(e);const u=z(e);let d=0;u===3&&(d=e.readBits(1));const f=z(e),h=z(e);let p=f,m=h;if(e.readBits(1)){const v=z(e),R=z(e),O=z(e),N=z(e);let D=1,$=1;const J=d===0?u:0;J===1?(D=2,$=2):J===2&&(D=2,$=1),p-=(v+R)*D,m-=(O+N)*$}const y=z(e),w=z(e);z(e);const b=e.readBits(1)?0:t;let S=0;for(let v=b;v<=t;v++)z(e),S=z(e),z(e);z(e),z(e),z(e),z(e),z(e),z(e),e.readBits(1)&&e.readBits(1)&&kc(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),z(e),z(e),e.skipBits(1));const T=z(e);if(bc(e,T),e.readBits(1)){const v=z(e);for(let R=0;R<v;R++)z(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let P=2,I=2,C=2,x=0,E=0,_={num:1,den:1};if(e.readBits(1)){const v=Sc(e,t);_=v.pixelAspectRatio,P=v.colourPrimaries,I=v.transferCharacteristics,C=v.matrixCoefficients,x=v.fullRangeFlag,E=v.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:_,colourPrimaries:P,transferCharacteristics:I,matrixCoefficients:C,fullRangeFlag:x,maxDecFrameBuffering:S+1,spsMaxSubLayersMinus1:t,spsTemporalIdNestingFlag:i,generalProfileSpace:n,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:y,bitDepthChromaMinus8:w,minSpatialSegmentationIdc:E}}catch(e){return H._error("Error parsing HEVC SPS:",e),null}},ki=r=>{try{const e=[],t=[],i=[],n=[];for(const l of Nr(r)){const u=r.subarray(l.offset,l.offset+l.length),d=tr(u[0]);d===ce.VPS_NUT?e.push(u):d===ce.SPS_NUT?t.push(u):d===ce.PPS_NUT?i.push(u):(d===ce.PREFIX_SEI_NUT||d===ce.SUFFIX_SEI_NUT)&&n.push(u)}if(t.length===0||i.length===0)return null;const s=Mn(t[0]);if(!s)return null;let a=0;if(i.length>0){const l=i[0],u=new G(gi(l));u.skipBits(16),z(u),z(u),u.skipBits(1),u.skipBits(1),u.skipBits(3),u.skipBits(1),u.skipBits(1),z(u),z(u),ct(u),u.skipBits(1),u.skipBits(1),u.readBits(1)&&z(u),ct(u),ct(u),u.skipBits(1),u.skipBits(1),u.skipBits(1),u.skipBits(1);const d=u.readBits(1),f=u.readBits(1);!d&&!f?a=0:d&&!f?a=2:!d&&f?a=3:a=0}const o=[...e.length?[{arrayCompleteness:1,nalUnitType:ce.VPS_NUT,nalUnits:e}]:[],...t.length?[{arrayCompleteness:1,nalUnitType:ce.SPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:ce.PPS_NUT,nalUnits:i}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:tr(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(e){return H._error("Error building HEVC Decoder Configuration Record:",e),null}},wc=(r,e)=>{const t=r.readBits(2),i=r.readBits(1),n=r.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|r.readBits(1);const a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=r.readBits(8);const o=r.readBits(8),c=[],l=[];for(let u=0;u<e;u++)c.push(r.readBits(1)),l.push(r.readBits(1));if(e>0)for(let u=e;u<8;u++)r.skipBits(2);for(let u=0;u<e;
1u++)c[u]&&r.skipBits(88),l[u]&&r.skipBits(8);return{general_profile_space:t,general_tier_flag:i,general_profile_idc:n,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:o}},kc=r=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!r.readBits(1))z(r);else{const n=Math.min(64,1<<4+(e<<1));e>1&&ct(r);for(let s=0;s<n;s++)ct(r)}},bc=(r,e)=>{const t=[];for(let i=0;i<e;i++)t[i]=Tc(r,i,e,t)},Tc=(r,e,t,i)=>{let n=0,s=0,a=0;if(e!==0&&(s=r.readBits(1)),s){if(e===t){const c=z(r);a=e-(c+1)}else a=e-1;r.readBits(1),z(r);const o=i[a]??0;for(let c=0;c<=o;c++)r.readBits(1)||r.readBits(1);n=i[a]}else{const o=z(r),c=z(r);for(let l=0;l<o;l++)z(r),r.readBits(1);for(let l=0;l<c;l++)z(r),r.readBits(1);n=o+c}return n},Sc=(r,e)=>{let t=2,i=2,n=2,s=0,a=0,o={num:1,den:1};if(r.readBits(1)){const c=r.readBits(8);if(c===255)o={num:r.readBits(16),den:r.readBits(16)};else{const l=Ba[c];l&&(o=l)}}return r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),s=r.readBits(1),r.readBits(1)&&(t=r.readBits(8),i=r.readBits(8),n=r.readBits(8))),r.readBits(1)&&(z(r),z(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(z(r),z(r),z(r),z(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&z(r),r.readBits(1)&&xc(r,!0,e)),r.readBits(1)&&(r.readBits(1),r.readBits(1),r.readBits(1),a=z(r),z(r),z(r),z(r),z(r)),{pixelAspectRatio:o,colourPrimaries:t,transferCharacteristics:i,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},xc=(r,e,t)=>{let i=!1,n=!1,s=!1;i=r.readBits(1)===1,n=r.readBits(1)===1,(i||n)&&(s=r.readBits(1)===1,s&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),s&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5));for(let a=0;a<=t;a++){const o=r.readBits(1)===1;let c=!0;o||(c=r.readBits(1)===1);let l=!1;c?z(r):l=r.readBits(1)===1;let u=1;l||(u=z(r)+1),i&&cs(r,u,s),n&&cs(r,u,s)}},cs=(r,e,t)=>{for(let i=0;i<e;i++)z(r),z(r),t&&(z(r),z(r)),r.readBits(1)},Pc=r=>{const e=[];e.push(r.configurationVersion),e.push((r.generalProfileSpace&3)<<6|(r.generalTierFlag&1)<<5|r.generalProfileIdc&31),e.push(r.generalProfileCompatibilityFlags>>>24&255),e.push(r.generalProfileCompatibilityFlags>>>16&255),e.push(r.generalProfileCompatibilityFlags>>>8&255),e.push(r.generalProfileCompatibilityFlags&255),e.push(...r.generalConstraintIndicatorFlags),e.push(r.generalLevelIdc&255),e.push(240|r.minSpatialSegmentationIdc>>8&15),e.push(r.minSpatialSegmentationIdc&255),e.push(252|r.parallelismType&3),e.push(252|r.chromaFormatIdc&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.avgFrameRate>>8&255),e.push(r.avgFrameRate&255),e.push((r.constantFrameRate&3)<<6|(r.numTemporalLayers&7)<<3|(r.temporalIdNested&1)<<2|r.lengthSizeMinusOne&3),e.push(r.arrays.length&255);for(const t of r.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nalUnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(const i of t.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let n=0;n<i.length;n++)e.push(i[n])}}return new Uint8Array(e)},Cc=r=>{try{const e=K(r);let t=0;const i=e.getUint8(t++),n=e.getUint8(t++),s=n>>6&3,a=n>>5&1,o=n&31,c=e.getUint32(t,!1);t+=4;const l=r.subarray(t,t+6);t+=6;const u=e.getUint8(t++),d=(e.getUint8(t++)&15)<<8|e.getUint8(t++),f=e.getUint8(t++)&3,h=e.getUint8(t++)&3,p=e.getUint8(t++)&7,m=e.getUint8(t++)&7,y=e.getUint16(t,!1);t+=2;const w=e.getUint8(t++),k=w>>6&3,b=w>>3&7,S=w>>2&1,T=w&3,P=e.getUint8(t++),I=[];for(let C=0;C<P;C++){const x=e.getUint8(t++),E=x>>7&1,_=x&63,v=e.getUint16(t,!1);t+=2;const R=[];for(let O=0;O<v;O++){const N=e.getUint16(t,!1);t+=2,R.push(r.subarray(t,t+N)),t+=N}I.push({arrayCompleteness:E,nalUnitType:_,nalUnits:R})}return{configurationVersion:i,generalProfileSpace:s,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:u,minSpatialSegmentationIdc:d,parallelismType:f,chromaFormatIdc:h,bitDepthLumaMinus8:p,bitDepthChromaMinus8:m,avgFrameRate:y,constantFrameRate:k,numTemporalLayers:b,temporalIdNested:S,lengthSizeMinusOne:T,arrays:I}}catch(e){return H._error("Error deserializing HEVC Decoder Configuration Record:",e),null}};var me;
1(function(r){r[r.audAllowed=0]="audAllowed",r[r.beforeFirstVcl=1]="beforeFirstVcl",r[r.afterFirstVcl=2]="afterFirstVcl",r[r.eoBitstreamAllowed=3]="eoBitstreamAllowed",r[r.noMoreDataAllowed=4]="noMoreDataAllowed"})(me||(me={}));const Ic=(r,e)=>{const t=new Set;let i=me.audAllowed;for(const s of ti(r,e)){if(i===me.noMoreDataAllowed){t.add(s.offset);continue}const a=tr(r[s.offset]);if(i===me.eoBitstreamAllowed&&a!==37){t.add(s.offset);continue}let o=!1;a===35?i>me.audAllowed?o=!0:i=me.beforeFirstVcl:a<=31?i>me.afterFirstVcl?o=!0:i=me.afterFirstVcl:a===36?i!==me.afterFirstVcl?o=!0:i=me.eoBitstreamAllowed:a===37?i<me.afterFirstVcl?o=!0:i=me.noMoreDataAllowed:a===32||a===33||a===34||a===39||a>=41&&a<=44||a>=48&&a<=55?i>me.beforeFirstVcl?o=!0:i=me.beforeFirstVcl:(a===38||a===40||a>=45&&a<=47||a>=56&&a<=63)&&i<me.afterFirstVcl&&(o=!0),o&&t.add(s.offset)}if(t.size===0)return null;const n=[];for(const s of ti(r,e))t.has(s.offset)||n.push(r.subarray(s.offset,s.offset+s.length));return yc(n,e)},Ec={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},Fa=r=>{const e=new G(r);if(e.readBits(2)!==2)return null;const i=e.readBits(1),s=(e.readBits(1)<<1)+i;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;s>=2&&(l=e.readBits(1)?12:10);const u=e.readBits(3);let d=0,f=0;if(u!==7)if(f=e.readBits(1),s===1||s===3){const C=e.readBits(1),x=e.readBits(1);d=!C&&!x?3:C&&!x?2:1,e.skipBits(1)}else d=1;else d=3,f=1;const h=e.readBits(16),p=e.readBits(16),m=h+1,y=p+1,w=m*y;let k=re(kt).level;for(const I of kt)if(w<=I.maxPictureSize){k=I.level;break}const b=Ec[u],S=b?.colourPrimaries??2,T=b?.transferCharacteristics??2,P=b?.matrixCoefficients??2;return{profile:s,level:k,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:S,transferCharacteristics:T,matrixCoefficients:P}},_c=r=>r.colourPrimaries!==2||r.transferCharacteristics!==2||r.matrixCoefficients!==2,Ra=function*(r){const e=new G(r),t=()=>{let i=0;for(let n=0;n<8;n++){const s=e.readAlignedByte();if(i+=(s&127)*2**(n*7),!(s&128))break;if(n===7&&s&128)return null}return i>2**32-1?null:i};for(;e.getBitsLeft()>=8;){e.skipBits(1);const i=e.readBits(4),n=e.readBits(1),s=e.readBits(1);e.skipBits(1),n&&e.skipBits(8);let a;if(s){const o=t();if(o===null)return;a=o}else a=Math.floor(e.getBitsLeft()/8);g(e.pos%8===0),yield{type:i,data:r.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},zn=r=>{for(const{type:e,data:t}of Ra(r)){if(e!==1)continue;const i=new G(t),n=i.readBits(3);i.readBits(1);const s=i.readBits(1);let a=0,o=0,c=0;if(s)a=i.readBits(5);else{const x=i.readBits(1);let E=0;if(x){if(i.skipBits(32),i.skipBits(32),i.readBits(1)){let O=0;for(;O<32&&!i.readBits(1);)O++;O<32&&i.skipBits(O)}E=i.readBits(1),E&&(c=i.readBits(5),i.skipBits(32),i.skipBits(5),i.skipBits(5))}const _=i.readBits(1),v=i.readBits(5);for(let R=0;R<=v;R++){i.skipBits(12);const O=i.readBits(5);if(R===0&&(a=O),O>7){const N=i.readBits(1);R===0&&(o=N)}if(E&&i.readBits(1)){const D=c+1;i.skipBits(D),i.skipBits(D),i.skipBits(1)}_&&i.readBits(1)&&i.skipBits(4)}}const l=i.readBits(4),u=i.readBits(4),d=l+1;i.skipBits(d);const f=u+1;i.skipBits(f);let h=0;if(s?h=0:h=i.readBits(1),h&&(i.skipBits(4),i.skipBits(3)),i.skipBits(1),i.skipBits(1),i.skipBits(1),!s){i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const x=i.readBits(1);x&&(i.skipBits(1),i.skipBits(1));const E=i.readBits(1);let _=0;E?_=2:_=i.readBits(1),_>0&&(i.readBits(1)||i.skipBits(1)),x&&i.skipBits(3)}i.skipBits(1),i.skipBits(1),i.skipBits(1);const p=i.readBits(1);let m=8;n===2&&p?m=i.readBits(1)?12:10:n<=2&&(m=p?10:8);let y=0;n!==1&&(y=i.readBits(1));let w=2,k=2,b=2;i.readBits(1)&&(w=i.readBits(8),k=i.readBits(8),b=i.readBits(8));let T=0,P=1,I=1,C=0;return y?T=i.readBits(1):w===1&&k===13&&b===0?(T=1,P=0,I=0):(T=i.readBits(1),n===0?(P=1,I=1):n===1?(P=0,I=0):m===12?(P=i.readBits(1),I=P?i.readBits(1):0):(P=1,I=0),P&&I&&(C=i.readBits(2))),{profile:n,level:a,tier:o,bitDepth:m,monochrome:y,chromaSubsamplingX:P,chromaSubsamplingY:I,chromaSamplePosition:C,videoFullRangeFlag:T,colourPrimaries:w,transferCharacteristics:k,matrixCoefficients:b}}return null},vc=r=>r.colourPrimaries!==2||r.transferCharacteristics!==2||r.matrixCoefficients!==2,Ma=r=>{if(r.length<36)return null;const t=K(r);return t.getUint32(4)!==1768124518||t.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},za=r=>{const e=K(r),t=e.getUint8(9),i=e.getUint16(10,!0),n=e.getUint32(12,!0),s=e.getInt16(16,!0),a=e.getUint8(18);let o=null;return a&&(o=r.subarray(19,21+t)),{outputChannelCount:t,preSkip:i,inputSampleRate:n,outputGain:s,channelMappingFamily:a,channelMappingTable:o}},Ac=[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],Bc=r=>{const e=r[0]>>3,t=r[0]&3;let i;return t===0?i=1:t===1||t===2?i=2:i=r[1]&63,{durationInSamples:Ac[e]*i}},Fc=r=>{if(r.length<7)throw new Error("Setup header is too short.");if(r[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...r.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");const t=r.length,i=new Uint8Array(t);for(let d=0;d<t;d++)i[d]=r[t-1-d];const n=new G(i);let s=0;for(;n.getBitsLeft()>97;)if(n.readBits(1)===1){s=n.pos;break}if(s===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,o=!1,c=0;for(;n.getBitsLeft()>=97;){const d=n.pos,f=n.readBits(8),h=n.readBits(16),p=n.readBits(16);if(f>63||h!==0||p!==0){n.pos=d;break}if(n.skipBits(1),a++,a>64)break;n.clone().readBits(6)+1===a&&(o=!0,c=a)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);const l=c;n.pos=0,n.skipBits(s);const u=Array(l).fill(0);for(let d=l-1;d>=0;d--)n.skipBits(40),u[d]=n.readBits(1);return{modeBlockflags:u}},bi=(r,e,t)=>{switch(r){case"avc":{for(const i of _a(t,e)){const n=t[i.offset],s=pi(n);if(s>=fe.NON_IDR_SLICE&&s<=fe.SLICE_DPC)return"delta";
1if(s===fe.IDR)return"key";if(s===fe.SEI&&!ln()){const a=t.subarray(i.offset,i.offset+i.length),o=gi(a);let c=1;do{let l=0;for(;;){const f=o[c++];if(f===void 0||(l+=f,f<255))break}let u=0;for(;;){const f=o[c++];if(f===void 0||(u+=f,f<255))break}if(l===6){const f=new G(o);f.pos=8*c;const h=z(f),p=f.readBits(1);if(h===0&&p===1)return"key"}c+=u}while(c<o.length-1)}}return"delta"}case"hevc":{for(const i of ti(t,e)){const n=tr(t[i.offset]);if(n<ce.BLA_W_LP)return"delta";if(n<=ce.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{const i=new G(t);if(i.readBits(2)!==2)return null;const n=i.readBits(1);return(i.readBits(1)<<1)+n===3&&i.skipBits(1),i.readBits(1)?null:i.readBits(1)===0?"key":"delta"}case"av1":{let i=!1;for(const{type:n,data:s}of Ra(t))if(n===1){const a=new G(s);a.skipBits(4),i=!!a.readBits(1)}else if(n===3||n===6||n===7){if(i)return"key";const a=new G(s);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}case"prores":return"key";default:Fe(r),g(!1)}};var Zt;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(Zt||(Zt={}));const fn=(r,e)=>{const t=K(r);let i=0;const n=t.getUint32(i,!0);i+=4;const s=xe.decode(r.subarray(i,i+n));i+=n,n>0&&(e.raw??={},e.raw.vendor??=s);const a=t.getUint32(i,!0);i+=4;for(let o=0;o<a;o++){const c=t.getUint32(i,!0);i+=4;const l=xe.decode(r.subarray(i,i+c));i+=c;const u=l.indexOf("=");if(u===-1)continue;const d=l.slice(0,u).toUpperCase(),f=l.slice(u+1);switch(e.raw??={},e.raw[d]??=f,d){case"TITLE":e.title??=f;break;case"DESCRIPTION":e.description??=f;break;case"ARTIST":e.artist??=f;break;case"ALBUM":e.album??=f;break;case"ALBUMARTIST":e.albumArtist??=f;break;case"COMMENT":e.comment??=f;break;case"LYRICS":e.lyrics??=f;break;case"TRACKNUMBER":{const h=f.split("/"),p=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),m&&Number.isInteger(m)&&m>0&&(e.tracksTotal??=m)}break;case"TRACKTOTAL":{const h=Number.parseInt(f,10);Number.isInteger(h)&&h>0&&(e.tracksTotal??=h)}break;case"DISCNUMBER":{const h=f.split("/"),p=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),m&&Number.isInteger(m)&&m>0&&(e.discsTotal??=m)}break;case"DISCTOTAL":{const h=Number.parseInt(f,10);Number.isInteger(h)&&h>0&&(e.discsTotal??=h)}break;case"DATE":{const h=new Date(f);Number.isNaN(h.getTime())||(e.date??=h)}break;case"GENRE":e.genre??=f;break;case"METADATA_BLOCK_PICTURE":{const h=Sa(f),p=K(h),m=p.getUint32(0,!1),y=p.getUint32(4,!1),w=String.fromCharCode(...h.subarray(8,8+y)),k=p.getUint32(8+y,!1),b=xe.decode(h.subarray(12+y,12+y+k)),S=p.getUint32(y+k+28),T=h.subarray(y+k+32,y+k+32+S);e.images??=[],e.images.push({data:T,mimeType:w,kind:m===3?"coverFront":m===4?"coverBack":"unknown",name:void 0,description:b||void 0})}break}}},On=[2,1,2,3,3,4,4,5],Oa=r=>{if(r.length<7||r[0]!==11||r[1]!==119)return null;const e=new G(r);e.skipBits(16),e.skipBits(16);const t=e.readBits(2);if(t===3)return null;const i=e.readBits(6),n=e.readBits(5);if(n>8)return null;const s=e.readBits(3),a=e.readBits(3);(a&1)!==0&&a!==1&&e.skipBits(2),(a&4)!==0&&e.skipBits(2),a===2&&e.skipBits(2);const o=e.readBits(1),c=Math.floor(i/2);return{fscod:t,bsid:n,bsmod:s,acmod:a,lfeon:o,bitRateCode:c}},Rc=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],Mc=1536,Da=[1,2,3,6],Na=r=>{if(r.length<6||r[0]!==11||r[1]!==119)return null;const e=new G(r);e.skipBits(16);const t=e.readBits(2);if(e.skipBits(3),t!==0&&t!==2)return null;const i=e.readBits(11),n=e.readBits(2);let s=0,a;n===3?(s=e.readBits(2),a=3):a=e.readBits(2);const o=e.readBits(3),c=e.readBits(1),l=e.readBits(5);if(l<11||l>16)return null;const u=Da[a];let d;return n<3?d=mi[n]/1e3:d=Ia[s]/1e3,{dataRate:Math.round((i+1)*d/(u*16)),substreams:[{fscod:n,fscod2:s,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},zc=r=>{if(r.length<2)return null;const e=new G(r),t=e.readBits(13),i=e.readBits(3),n=[];for(let s=0;s<=i&&!(Math.ceil(e.pos/8)+3>r.length);s++){const a=e.readBits(2),o=e.readBits(5);e.skipBits(1),e.skipBits(1);const c=e.readBits(3),l=e.readBits(3),u=e.readBits(1);e.skipBits(3);const d=e.readBits(4);let f=0;d>
10?f=e.readBits(9):e.skipBits(1),n.push({fscod:a,fscod2:null,bsid:o,bsmod:c,acmod:l,lfeon:u,numDepSub:d,chanLoc:f})}return n.length===0?null:{dataRate:t,substreams:n}},Ua=r=>{const e=r.substreams[0];return g(e),e.fscod<3?mi[e.fscod]:e.fscod2!==null&&e.fscod2<3?Ia[e.fscod2]:null},Wa=r=>{const e=r.substreams[0];g(e);let t=On[e.acmod]+e.lfeon;if(e.numDepSub>0){const i=[2,2,1,1,2,2,2,1,1];for(let n=0;n<9;n++)e.chanLoc&1<<8-n&&(t+=i[n])}return t},Oc=1683496997,Xr=18,hn=10,Dc=4096,ls=32,Dn=20,Nc=8,Uc=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Wc=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],Vc=[16,16,20,20,0,24,24,0],ri=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Lc=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Hc=8,qc=44646,jc=[32e3,44100,48e3,0],$c=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Va=[512,1024,2048,4096],Nn=r=>{const e=Ha(r),t=K(r);let i=e?Math.ceil(e.frameSize/4)*4:0,n=null;for(;i+4<=r.length&&t.getUint32(i)===Oc;){const a=Qr(r.subarray(i));if(!a)break;n??=a,i+=a.frameSize}if(e)return{frameSize:n?i:e.frameSize,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,sampleCount:e.sampleCount,channelLayout:e.channelLayout,pcmResolution:e.pcmResolution,bitRate:e.bitRate,core:e,hasExtensions:n!==null};if(!n?.asset)return null;const{asset:s}=n;return{frameSize:i,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,sampleCount:s.sampleCount,channelLayout:s.channelLayout,pcmResolution:s.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},La=r=>{const e=Nn(r);return e?.core?e.hasExtensions?"dtsh":"dtsc":null},Ha=r=>{if(r.length<Xr||r[0]!==127||r[1]!==254||r[2]!==128||r[3]!==1)return null;const e=new G(r);if(e.skipBits(32),e.skipBits(1),e.readBits(5)!==ls-1)return null;const t=e.readBits(1),i=e.readBits(7)+1;if(i%Nc!==0)return null;const n=e.readBits(14)+1;if(n<96)return null;const s=e.readBits(6);if(s>=ri.length)return null;const a=Uc[e.readBits(4)];if(a===0)return null;const o=Wc[e.readBits(5)];if(e.readBits(1)!==0)return null;e.skipBits(4),e.skipBits(5);const c=e.readBits(2);if(c===3)return null;e.skipBits(1),t&&e.skipBits(16),e.skipBits(7);const l=Vc[e.readBits(3)];if(l===0)return null;const u=c!==0;return{frameSize:n,sampleRate:a,numberOfChannels:ri[s]+(u?1:0),sampleCount:i*ls,channelLayout:Lc[s]|(u?Hc:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:l}},Qr=r=>{if(r.length<hn||r[0]!==100||r[1]!==88||r[2]!==32||r[3]!==37)return null;const e=new G(r);e.skipBits(32),e.skipBits(8);const t=e.readBits(2),i=e.readBits(1),n=8+4*i,s=16+4*i;e.skipBits(n);const a=e.readBits(s)+1,o={frameSize:a,asset:null};if(!e.readBits(1))return o;const c=jc[e.readBits(2)],l=512*(e.readBits(3)+1);e.readBits(1)&&e.skipBits(36);const u=e.readBits(3)+1,d=e.readBits(3)+1,f=[];for(let w=0;w<u;w++)f.push(e.readBits(t+1));for(const w of f)e.skipBits(8*cn(w));if(e.readBits(1)){e.skipBits(2);const w=e.readBits(2)+1<<2,k=e.readBits(2)+1;e.skipBits(k*w)}for(let w=0;w<d;w++)e.skipBits(s);e.skipBits(9),e.skipBits(3),e.readBits(1)&&e.skipBits(4),e.readBits(1)&&e.skipBits(24),e.readBits(1)&&e.skipBits(8*(e.readBits(10)+1));const h=e.readBits(5)+1,p=$c[e.readBits(4)],m=e.readBits(8)+1;let y=0;if(e.readBits(1)&&(m>2&&e.skipBits(1),m>6&&e.skipBits(1),e.readBits(1))){const w=e.readBits(2)+1<<2;y=e.readBits(w)}return c===0||e.getBitsLeft()<0?o:{frameSize:a,asset:{sampleRate:p,numberOfChannels:m,sampleCount:Math.round(l*p/c),channelLayout:y,pcmResolution:h}}},Kc=r=>{if(r.length<Dn)return null;const e=K(r),t=e.getUint32(0);if(t===0)return null;const i=new G(r);i.seekToByte(13);const n=i.readBits(2);i.skipBits(5);const s=i.readBits(1),a=i.readBits(6);i.skipBits(14),i.skipBits(1),i.skipBits(3);const o=i.readBits(16);let c=null;return o!==0?c=Xc(o):a<ri.length&&(c=ri[a]+s),{sampleRate:t,maxBitrate:e.getUint32(4),avgBitrate:e.getUint32(8),pcmSampleDepth:r[12],sampleCount:Va[n],channelLayout:o,numberOfChannels:c}},Gc=r=>{const e=new Uint8Array(Dn),t=K(e);t.setUint32(0,r.sampleRate),t.setUint32(4,r.bitRate),t.setUint32(8,r.bitRate),e[12]=r.pcmResolution;const i=r.core&&!r.hasExtensions?1:0,n=new G(e);return n.seekToByte(13),n.writeBits(2,Math.max(Va.indexOf(r.sampleC
vendor: 5,292 bytes, line 1
1ount),0)),n.writeBits(5,i),n.writeBits(1,r.core?.lfePresent?1:0),n.writeBits(6,r.core?.amode??0),n.writeBits(14,r.core?r.core.frameSize-1:0),n.writeBits(1,0),n.writeBits(3,0),n.writeBits(16,r.channelLayout),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(5,0),e},Xc=r=>cn(r)+cn(r&qc);const _e=["avc","hevc","vp9","av1","vp8","prores"],be=["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"],Jt=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],Re=[...Jt,...be],Ar=["webvtt"],ii=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],us=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],kt=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],ds=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],fs=".01.01.01.01.00",hs=".0.110.01.01.01.0",Ft=["ap4x","ap4h","apch","apcn","apcs","apco"],ni=["dtsc","dtsh","dtsl","dtse"],Qc=[{fourCc:"apco",bitrate:45e6,alph
1a:!1},{fourCc:"apcs",bitrate:102e6,alpha:!1},{fourCc:"apcn",bitrate:147e6,alpha:!1},{fourCc:"apch",bitrate:22e7,alpha:!1},{fourCc:"ap4h",bitrate:33e7,alpha:!0},{fourCc:"ap4x",bitrate:5e8,alpha:!0}],Yc=(r,e,t,i,n)=>{if(r==="avc"){const a=Math.ceil(e/16)*Math.ceil(t/16),o=ii.find(f=>a<=f.maxMacroblocks&&i<=f.maxBitrate)??re(ii),c=o?o.level:0,l="64".padStart(2,"0"),u="00",d=c.toString(16).padStart(2,"0");return`avc1.${l}${u}${d}`}else if(r==="hevc"){const c=e*t,l=us.find(d=>c<=d.maxPictureSize&&i<=d.maxBitrate)??re(us);return`hev1.1.6.${l.tier}${l.level}.B0`}else{if(r==="vp8")return"vp8";if(r==="vp9"){const a=e*t;return`vp09.00.${(kt.find(l=>a<=l.maxPictureSize&&i<=l.maxBitrate)??re(kt)).level.toString().padStart(2,"0")}.08`}else if(r==="av1"){const a=e*t,o=ds.find(u=>a<=u.maxPictureSize&&i<=u.maxBitrate)??re(ds);return`av01.0.${o.level.toString().padStart(2,"0")}${o.tier}.08`}else if(r==="prores"){const a=Math.pow(e*t/2073600,.95),o=Qc.filter(u=>u.alpha===n);let c=o[0].fourCc,l=1/0;for(const{fourCc:u,bitrate:d}of o){const f=Math.abs(d*a-i);f<l&&(l=f,c=u)}return c}else Fe(r)}throw new TypeError(`Unhandled codec '${String(r)}'.`)},Zc=r=>{const e=r.split("."),n=(1<<7)+1,s=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),c=(s<<5)+o,l=a.slice(-1)==="H"?1:0,u=Number(e[3]),d=u===8?0:1,f=u===12?1:0,h=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,m=e[5]?Number(e[5][1]):1,y=e[5]?Number(e[5][2]):0,w=(l<<7)+(d<<6)+(f<<5)+(h<<4)+(p<<3)+(m<<2)+y;return[n,c,w,0]},Un=r=>{const{codec:e,codecDescription:t,colorSpace:i,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:c}=r;if(e==="avc"){if(g(r.avcType!==null),n){const l=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${r.avcType}.${Ir(l)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${r.avcType}.${Ir(t.subarray(1,4))}`}else if(e==="hevc"){let l,u,d,f,h,p;if(s)l=s.generalProfileSpace,u=s.generalProfileIdc,d=es(s.generalProfileCompatibilityFlags),f=s.generalTierFlag,h=s.generalLevelIdc,p=[...s.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const y=K(t),w=y.getUint8(1);l=w>>6&3,u=w&31,d=es(y.getUint32(2)),f=w>>5&1,h=y.getUint8(12),p=[];for(let k=0;k<6;k++)p.push(y.getUint8(6+k))}let m="hev1.";for(m+=["","A","B","C"][l]+u,m+=".",m+=d.toString(16).toUpperCase(),m+=".",m+=f===0?"L":"H",m+=h;p.length>0&&p[p.length-1]===0;)p.pop();return p.length>0&&(m+=".",m+=p.map(y=>y.toString(16).toUpperCase()).join(".")),m}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){const k=r.width*r.height;let b=re(kt).level;for(const S of kt)if(k<=S.maxPictureSize){b=S.level;break}return`vp09.00.${b.toString().padStart(2,"0")}.08`}const l=a.profile.toString().padStart(2,"0"),u=a.level.toString().padStart(2,"0"),d=a.bitDepth.toString().padStart(2,"0"),f=a.chromaSubsampling.toString().padStart(2,"0"),h=a.colourPrimaries.toString().padStart(2,"0"),p=a.transferCharacteristics.toString().padStart(2,"0"),m=a.matrixCoefficients.toString().padStart(2,"0"),y=a.videoFullRangeFlag.toString().padStart(2,"0");let w=`vp09.${l}.${u}.${d}.${f}`;return w+=`.${h}.${p}.${m}.${y}`,w.endsWith(fs)&&(w=w.slice(0,-fs.length)),w}else if(e==="av1"){if(!o){const S=r.width*r.height;let T=re(kt).level;for(const P of kt)if(S<=P.maxPictureSize){T=P.level;break}return`av01.0.${T.toString().padStart(2,"0")}M.08`}const l=o.profile,u=o.level.toString().padStart(2,"0"),d=o.tier?"H":"M",f=o.bitDepth.toString().padStart(2,"0"),h=o.monochrome?"1":"0",p=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),m=i?.primaries?nr[i.primaries]:1,y=i?.transfer?sr[i.transfer]:1,w=i?.matrix?ar[i.matrix]:1,k=i?.fullRange?1:0;let b=`av01.${l}.${u}${d}.${f}`;return b+=`.${h}.${p.toString().padStart(3,"0")}`,b+=`.${m.toString().padStart(2,"0")}`,b+=`.${y.toString().padStart(2,"0")}`,b+=`.${w.toString().padStart(2,"0")}`,b+=`.${k}`,b.endsWith(hs)&&(b=b.slice(0,-hs.length)),b}else{if(e==="prores")return c??"apch";e!==null&&Fe(e)}}throw new TypeError(`Unhandled codec '${e}'.`)},qa=r=>{switch(r.codec){case"avc":{let e=r.avcCodecInfo?.sequenceParameterSets[0];if(!e&&r.codecDescription&&(e=Aa(r.codecDescription)?.sequenceParameterSets[0]),e){const t=wi(e);if(t)return{primaries:rt[t.colourPrimaries],transfer:it[t.transferCharacteristics],matrix:nt[t.matrixCoefficients],fullRange:!!t.fullRangeFlag}}}break;case"hevc":{let e=r.hevcCodecInfo?.arrays.find(t=>t.nalUnitType===ce.SPS_NUT)?.nalUnits[0];if(!e&&r.codecDescription&&(e=Cc(r.codecDescription)?.arrays.find(t=>t.nalUnitType===ce.SPS_NUT)?.nalUnits[0]),e){const t=Mn(e);if(t)return{primaries:rt[t.colourPrimaries],transfer:it[t.transferCharacteristics],matrix:nt[t.matrixCoefficients],fullRange:!!t.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(r.vp9CodecInfo)return{primaries:rt[r.vp9CodecInfo.colourPrimaries],transfer:it[r.vp9CodecInfo.transferCharacteristics],matrix:nt[r.vp9CodecInfo.matrixCoefficients],fullRange:!!r.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(r.av1CodecInfo)return{primaries:rt[r.av1CodecInfo.colourPrimaries],transfer:it[r.av1CodecInfo.transferCharacteristics],matrix:nt[r.av1CodecInfo.matrixCoefficients],fullRange:!!r.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(r.proresCodecInfo)return{primaries:rt[r.proresCodecInfo.colourPrimaries],transfer:it[r.proresCodecInfo.transferCharacteristics],matrix:nt[r.proresCodecInfo.matrixCoefficients],fullRange:r.proresCodecInfo.fullRange};break}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},Jc=(r,e,t)=>{if(r==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(r==="mp3")return"mp3";if(r==="opus")return"opus";if(r==="vorbis")return"vorbis";if(r==="flac")return"flac";if(r==="ac3")return"ac-3";if(r==="eac3")return"ec-3";if(r==="dts")return"dtsc";if(be.includes(r))return r;throw new TypeError(`Unhandled codec '${r}'.`)},Wn=r=>{const{codec:e,codecDescription:t,aacCodecInfo:i,dtsFormat:n}=r;if(e==="aac"){if(!i)throw new TypeError("AAC codec info must be provided.");if(i.isMpeg2)return"mp4a.67";{let s;return i.objectType!==null?s=i.objectType:s=Fn(t).objectType,`mp4a.40.${s}`}}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e==="ac3")return"ac-3";if(e==="eac3")return"ec-3";if(e==="dts")return n??"dtsc";if(e&&be.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},Ti=48e3,ja=/^pcm-([usf])(\d+)(be)?$/,ut=r=>
vendor: 9,383 bytes, line 1
1{if(g(be.includes(r)),r==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(r==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=ja.exec(r);g(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";const i=Number(e[2])/8,n=e[3]!=="be",s=r==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:i,littleEndian:n,silentValue:s}},lt=r=>r.startsWith("avc1")||r.startsWith("avc3")?"avc":r.startsWith("hev1")||r.startsWith("hvc1")?"hevc":r==="vp8"?"vp8":r.startsWith("vp09")?"vp9":r.startsWith("av01")?"av1":Ft.includes(r)?"prores":r==="mp3"||r==="mp4a.69"||r==="mp4a.6B"||r==="mp4a.6b"||r==="mp4a.40.34"?"mp3":r.startsWith("mp4a.40.")||r==="mp4a.67"?"aac":r==="opus"?"opus":r==="vorbis"?"vorbis":r==="flac"?"flac":r==="ac-3"||r==="ac3"?"ac3":r==="ec-3"||r==="eac3"?"eac3":ni.includes(r)?"dts":r==="ulaw"?"ulaw":r==="alaw"?"alaw":ja.test(r)?r:r==="webvtt"?"webvtt":null,el=r=>r==="avc"?{avc:{format:"avc"}}:r==="hevc"?{hevc:{format:"hevc"}}:{},tl=r=>r==="aac"?{aac:{format:"aac"}}:r==="opus"?{opus:{format:"opus"}}:{},rl=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Ft],il=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,nl=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,sl=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,al=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,$a=(r,e)=>{if(!r)throw new TypeError("Video chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Video chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!rl.some(t=>r.decoderConfig.codec.startsWith(t)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.codedWidth)||r.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(r.decoderConfig.codedHeight)||r.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(r.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectWidth)||r.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectHeight)||r.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectWidth!==void 0!=(r.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(r.decoderConfig.description!==void 0&&!ui(r.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.colorSpace!==void 0){const{colorSpace:t}=r.decoderConfig;if(typeof t!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const i=Object.keys(nr);if(t.primaries!=null&&!i.includes(t.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);const n=Object.keys(sr);if(t.transfer!=null&&!n.includes(t.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${n.join(", ")}.`);const s=Object.keys(ar);if(t.matrix!=null&&!s.includes(t.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${s.join(", ")}.`);if(t.fullRange!=null&&typeof t.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(r.decoderConfig.codec.startsWith("avc1")||r.decoderConfig.codec.startsWith("avc3")){if(!il.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(r.decoderConfig.codec.startsWith("hev1")||r.decoderConfig.codec.startsWith("hvc1")){if(!nl.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(r.decoderConfig.codec.startsWith("vp8")){if(r.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(r.decoderConfig.codec.startsWith("vp09")){if(!sl.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(r.decoderConfig.codec.startsWith("av01")){if(!al.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if(Ft.some(t=>r.decoderConfig.codec.startsWith(t))&&!Ft.some(t=>r.decoderConfig.codec===t))throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${Ft.join(", ")}.`);if(e!==null&&lt(r.decoderConfig.codec)!==e)throw new TypeError(`Video chunk metadata decoder configuration codec string '${r.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},ol=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],Ka=(r,e)=>{if(!r)throw new TypeError("Audio chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!ol.some(t=>r.decoderConfig.codec.startsWith(t)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.sampleRate)||r.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(r.decoderConfig.numberOfChannels)||r.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(r.decoderConfig.description!==void 0&&!ui(r.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.codec.startsWith("mp4a")&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(r.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("mp3")||r.decoderConfig.codec.startsWith("mp4a")){if(r.decoderConfig.codec!=="mp3"&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(r.decoderConfig.codec.startsWith("opus")){if(r.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(r.decoderConfig.description&&r.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(r.decoderConfig.codec.startsWith("vorbis")){if(r.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!r.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described 
1in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("flac")){if(r.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!r.decoderConfig.description||r.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("ac-3")||r.decoderConfig.codec.startsWith("ac3")){if(r.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(r.decoderConfig.codec.startsWith("ec-3")||r.decoderConfig.codec.startsWith("eac3")){if(r.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if(r.decoderConfig.codec.startsWith("dts")){if(!ni.includes(r.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${ni.join(", ")}.`)}else if((r.decoderConfig.codec.startsWith("pcm")||r.decoderConfig.codec.startsWith("ulaw")||r.decoderConfig.codec.startsWith("alaw"))&&!be.includes(r.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${be.join(", ")}).`);if(e!==null&&lt(r.decoderConfig.codec)!==e)throw new TypeError(`Audio chunk metadata decoder configuration codec string '${r.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},cl=r=>{if(!r)throw new TypeError("Subtitle metadata must be provided.");if(typeof r!="object")throw new TypeError("Subtitle metadata must be an object.");if(!r.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof r.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof r.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};const Rt=4,ll=[44100,48e3,32e3],ul=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],Ga=1483304551,Xa=1231971951,dl=(r,e,t,i,n)=>e===0?0:e===1?Math.floor(144*t/(i<<r))+n:e===2?Math.floor(144*t/i)+n:(Math.floor(12*t/i)+n)*4,fl=(r,e,t,i)=>e===0?0:e===1?144*t/(i<<r):e===2?144*t/i:12*t/i*4,Qa=(r,e)=>r===3?e===3?21:36:e===3?13:21,Vn=(r,e)=>{const t=r>>>24,i=r>>>16&255,n=r>>>8&255,s=r&255;if(t!==255&&i!==255&&n!==255&&s!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((i&224)!==224)return{header:null,bytesAdvanced:1};let a=0,o=0;i&16?a=i&8?0:1:(a=1,o=1);const c=i>>3&3,l=i>>1&3,u=n>>4&15,d=(n>>2&3)%3,f=n>>1&1,h=s>>6&3,p=s>>4&3,m=s>>3&1,y=s>>2&1,w=s&3,k=ul[a*16*4+l*16+u];if(k===-1)return{header:null,bytesAdvanced:1};const b=k*1e3,S=ll[d]>>a+o,T=dl(a,l,b,S,f);if(e!==null&&e<T)return{header:null,bytesAdvanced:1};let P;return c===3?P=l===3?384:1152:l===3?P=384:l===2?P=1152:P=576,{header:{totalSize:T,mpegVersionId:c,lowSamplingFrequency:a,layer:l,bitrate:b,frequencyIndex:d,sampleRate:S,channel:h,modeExtension:p,copyright:m,original:y,emphasis:w,audioSamplesInFrame:P},bytesAdvanced:1}},mn=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t};var si;(function(r){r[r.FrameCount=1]="FrameCount",r[r.FileSize=2]="FileSize",r[r.Toc=4]="Toc"})(si||(si={}));const Br=r=>r===3?1:2;class ht{constructor(e){this.input=e}dispose(){}}const ve=new Uint8Array(0);class Z{constructor(e,t,i,n,s=-1,a,o){if(this.data=e,this.type=t,this.timestamp=i,this.duration=n,this.sequenceNumber=s,e===ve&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");
vendor: 1,418 bytes, line 1
1if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(n)||n<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===ve}get microsecondTimestamp(){return Math.trunc(wt*this.timestamp)}get microsecondDuration(){return Math.trunc(wt*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");
1return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("EncodedAudioChunk is not available in this environment.");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 new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new Z(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new Z(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}}const Ya=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isQuickTime?"quicktime":"mp4");if(r.codecStrings.length>0){const i=[...new Set(r.codecStrings)];t+=`; codecs="${i.join(", ")}"`}return t},Za=r=>{const e=K(r);let t=0;const i=e.getUint8(t);t+=1,t+=3;const n=Ir(r.subarray(t,t+16));t+=16;let s=null;if(i>0){const o=e.getUint32(t);if(t+=4,o>0){s=[];for(let c=0;c<o;c++)s.push(Ir(r.subarray(t,t+16))),t+=16}}const a=e.getUint32(t);return t+=4,{systemId:n,keyIds:s,data:r.slice(t,t+a)}},Ja=(r,e)=>r.systemId===e.systemId&&fc(r.data,e.data);const st=8,_t=16,gt=r=>{let e=M(r);const t=ne(r,4);let i=8;e===1&&(e=Ce(r),i=16);const s=e-i;return s<0?null:{name:t,totalSize:e,headerSize:i,contentSize:s}},St=r=>At(r)/65536,Oi=r=>At(r)/1073741824,Di=r=>{let e=0;for(let t=0;t<4;t++){e<<=7;const i=U(r);if(e|=i&127,(i&128)===0)break}return e},We=r=>{let e=ae(r);return r.skip(2),e=Math.min(e,r.remainingLength),xe.decode(W(r,e))},hl=r=>{const e=gt(r);if(!e||e.name!=="data"||r.remainingLength<8)return null;const t=M(r);r.skip(4);const i=W(r,e.contentSize-8);switch(t){case 1:return xe.decode(i);case 2:return new TextDecoder("utf-16be").decode(i);case 13:return new Yt(i,"image/jpeg");case 14:return new Yt(i,"image/png");case 27:return new Yt(i,"image/bmp");default:return i}};const qe=16,Ye=new Uint32Array(256),Lt=new Uint32Array(256),Ht=new Uint32Array(256),qt=new Uint32Array(256),jt=new Uint32Array(256),de=new Uint32Array(256),eo=new Uint32Array(10);let to=!1;const ml=()=>{const r=new Uint8Array(256),e=new Uint8Array(256),t=new Uint8Array(256);for(let s=0,a=1;s<256;s++)t[s]=a,e[a]=s,a=a^a<<1^(a&128?283:0);const i=(s,a)=>s&&a?t[(e[s]+e[a])%255]:0;r[0]=99;for(let s=1;s<256;s++){const a=t[255-e[s]];let o=a^a<<1^a<<2^a<<3^a<<4;o=o>>>8^o&255^99,r[s]=o}for(let s=0;s<256;s++){const a=r[s],o=r.indexOf(s);Ye[s]=a<<24|a<<16|a<<8|a,de[s]=o<<24|o<<16|o<<8|o;const c=i(o,14),l=i(o,9),u=i(o,13),d=i(o,11),f=c<<24|l<<16|u<<8|d;Lt[s]=f,Ht[s]=f>>>8|f<<24,qt[s]=f>>>16|f<<16,jt[s]=f>>>24|f<<8}let n=1;for(let s=0;s<10;s++)eo[s]=n<<24,n=n<<1^(n&128?283:0);to=!0};class ro{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(qe/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(qe),this.out=new Uint8Array(qe),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){g(e.byteLength===16),g(t.byteLength===16),to||ml();const i=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=i.getUint32(0,!1),this.roundkey[1]=i.getUint32(4,!1),this.roundkey[2]=i.getUint32(8,!1),this.roundkey[3]=i.getUint32(12,!1),this.iv[0]=n.getUint32(0,!1),this.iv[1]=n.getUint32(4,!1),this.iv[2]=n.getUint32(8,!1),this.iv[3]=n.getUint32(12,!1);for(let s=4;s<44;s+=4){const a=this.roundkey[s-1];this.roundkey[s]=this.roundkey[s-4]^Ye[a>>>16&255]&4278190080^Ye[a>>>8&255]&16711680^Ye[a>>>0&255]&65280^Ye[a>>>24&255]&255^eo[s/4-1],this.roundkey[s+1]=this.roundkey[s-3]^this.roundkey[s],this.roundkey[s+2]=this.roundkey[s-2]^this.roundkey[s+1],this.roundkey[s+3]=this.roundkey[s-1]^this.roundkey[s+2]}for(let s=0,a=40;s<a;s+=4,a-=4)for(let o=0;o<4;o++){const c=this.roundkey[s+o];this.roundkey[s+o]=this.roundkey[a+o],this.roundkey[a+o]=c}for(let s=4;s<40;s+=4)for(let a=0;a<4;a++){const o=this.roundkey[s+a];this.roundkey[s+a]=Lt[Ye[o>>>24&255]&255]^Ht[Ye[o>>>16&255]&255]^qt[Ye[o>>>8&255]&255]^jt[Ye[o>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],n=this.inView.getUint32(12,!1)^this.roundkey[3];const s=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),c=this.inView.getUint32(12,!1);let l,u,d,f;for(let w=1;w<10;w++){const k=w*4;l=Lt[e>>>24]^Ht[n>>>16&255]^qt[i>>>8&255]^jt[t&255]^this.roundkey[k],u=Lt[t>>>24]^Ht[e>>>16&255]^qt[n>>>8&255]^jt[i&255]^this.roundkey[k+1],d=Lt[i>>>24]^Ht[t>>>16&255]^qt[e>>>8&255]^jt[n&255]^this.roundkey[k+2],f=Lt[n>>>24]^Ht[i>>>16&255]^qt[t>>>8&255]^jt[e&255]^this.roundkey[k+3],e=l,t=u,i=d,n=f}const h=de[e>>>24&255]&4278190080^de[n>>>16&255]&16711680^de[i>>>8&255]&65280^de[t>>>0&255]&255^this.roundkey[40],p=de[t>>>24&255]&4278190080^de[e>>>16&255]&16711680^de[n>>>8&255]&65280^de[i>>>0&255]&255^this.roundkey[41],m=de[i>>>24&255]&4278190080^de[t>>>16&255]&16711680^de[e>>>8&255]&65280^de[n>>>0&255]&255^this.roundkey[42],y=de[n>>>24&255]&4278190080^de[i>>>16&255]&16711680^de[t>>>8&255]&65280^de[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,h^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,y^this.iv[3],!1),this.iv[0]=s,this.iv[1]=a,this.iv[2]=o,this.iv[3]=c}}const pl=(r,e,t)=>{let i=!1,n=0;const s=2**16,a=16,o=new ro;return new ReadableStream({pull:async c=>{i||(o.init(await e()),i=!0);const l=s+a;let u=r.requestSliceRange(n,0,l);if(A(u)&&(u=await u),!u||u.length===0)throw new Error("Invalid ciphertext.");const d=u.length;if(d%16!==0)throw new Error("Invalid ciphertext.");const f=d===l?d-a:d,h=W(u,f),p=new Uint8Array(f);for(let m=0;m<f;m+=16)o.in.set(h.subarray(m,m+16)),o.decrypt(),p.set(o.out,m);if(f<d)c.enqueue(p),n+=f;else{const m=p[f-1];if(m===0||m>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const y=p.subarray(0,f-m);c.enqueue(y),c.close(),t()}},cancel:()=>{t()}})};class Ln extends ht{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.pss
1hBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(i=>i.getDecoderConfig().then(n=>n?.codec??null)));return Ya({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(i=>i.info?.type==="video"),hasAudio:this.tracks.some(i=>i.info?.type==="audio"),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,t=!1,i=!1;for(;;){let n=this.reader.requestSliceRange(e,st,_t);if(A(n)&&(n=await n),!n)break;const s=e,a=gt(n);if(!a)break;if(a.name==="ftyp"||a.name==="styp"){const o=ne(n,4);this.isQuickTime=o==="qt  "}else if(a.name==="moov"){let o=this.reader.requestSlice(n.filePos,a.contentSize);if(A(o)&&(o=await o),!o)break;this.moovSlice=o,this.readContiguousBoxes(this.moovSlice);for(const c of this.tracks){const l=c.editListPreviousSegmentDurations/this.movieTimescale;c.editListOffset-=Math.round(l*c.timescale)}t=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>s+a.totalSize,i=!0;break}else if(a.name==="moof"){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');await this.copyMetadataFromInitInput(this.input._initInput),t=!1,i=!0;break}e=s+a.totalSize}if(!i&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){g(this.reader.fileSize!==null);let n=this.reader.requestSlice(this.reader.fileSize-4,4);A(n)&&(n=await n),g(n);const s=M(n),a=this.reader.fileSize-s;if(a>=0&&a<=this.reader.fileSize-_t){let o=this.reader.requestSliceRange(a,st,_t);if(A(o)&&(o=await o),o){const c=gt(o);if(c&&c.name==="mfra"){let l=this.reader.requestSlice(o.filePos,c.contentSize);A(l)&&(l=await l),l&&this.readContiguousBoxes(l)}}}}})()}async copyMetadataFromInitInput(e){const t=await e._getDemuxer();if(t.constructor!==Ln)throw new Error("Init input must match the input's format.");await t.readMetadata(),this.movieTimescale=t.movieTimescale,this.movieDurationInTimescale=t.movieDurationInTimescale,this.metadataTags=t.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=t.fragmentTrackDefaults,this.psshBoxes=t.psshBoxes;for(const i of t.tracks){const n={id:i.id,demuxer:this,trackBacking:null,disposition:i.disposition,timescale:i.timescale,durationInMediaTimescale:i.durationInMediaTimescale,durationInMovieTimescale:i.durationInMovieTimescale,rotation:i.rotation,internalCodecId:i.internalCodecId,name:i.name,languageCode:i.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:i.editListPreviousSegmentDurations,editListOffset:i.editListOffset,encryptionInfo:i.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:i.info};if(i.trackBacking){if(g(n.info),n.info.type==="video"&&n.info.width!==-1){const s=n;n.trackBacking=new ms(s),this.tracks.push(n)}else if(n.info.type==="audio"&&n.info.numberOfChannels!==-1){const s=n;n.trackBacking=new ps(s),this.tracks.push(n)}}}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;const t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;g(this.moovSlice);const i=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(i),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&be.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){g(e.info?.type==="audio");const s=ut(e.info.codec),a=[],o=[];for(let c=0;c<t.sampleToChunk.length;c++){const l=t.sampleToChunk[c],u=t.sampleToChunk[c+1],d=(u?u.startChunkIndex:t.chunkOffsets.length)-l.startChunkIndex;for(let f=0;f<d;f++){const h=l.startSampleIndex+f*l.samplesPerChunk,p=h+l.samplesPerChunk,m=X(t.sampleTimingEntries,h,C=>C.startIndex),y=t.sampleTimingEntries[m],w=X(t.sampleTimingEntries,p,C=>C.startIndex),k=t.sampleTimingEntries[w],b=y.startDecodeTimestamp+(h-y.startIndex)*y.delta,T=k.startDecodeTimestamp+(p-k.startIndex)*k.delta-b,P=re(a);P&&P.delta===T?P.count++:a.push({startIndex:l.startChunkIndex+f,startDecodeTimestamp:b,count:1,delta:T});const I=l.samplesPerChunk*s.sampleSize*e.info.numberOfChannels;o.push(I)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}t.sampleTimingEntries=a,t.sampleSizes=o}
1if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(const s of t.sampleTimingEntries)for(let a=0;a<s.count;a++)t.presentationTimestamps.push({presentationTimestamp:s.startDecodeTimestamp+a*s.delta,sampleIndex:s.startIndex+a});for(const s of t.sampleCompositionTimeOffsets)for(let a=0;a<s.count;a++){const o=s.startIndex+a,c=t.presentationTimestamps[o];c&&(c.presentationTimestamp+=s.offset)}t.presentationTimestamps.sort((s,a)=>s.presentationTimestamp-a.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let s=0;s<t.presentationTimestamps.length;s++)t.presentationTimestampIndexMap[t.presentationTimestamps[s].sampleIndex]=s}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,st,_t);A(t)&&(t=await t),g(t);const i=gt(t);g(i?.name==="moof");let n=this.reader.requestSlice(e,i.totalSize);A(n)&&(n=await n),g(n),this.traverseBox(n);const s=this.lastReadFragment;g(s&&s.moofOffset===e);for(const[,a]of s.trackData){const o=a.track,{fragmentPositionCache:c}=o;if(!a.startTimestampIsFinal){const u=o.fragmentLookupTable.find(d=>
1d.moofOffset===s.moofOffset);if(u)Ni(a,u.timestamp);else{const d=X(c,s.moofOffset-1,f=>f.moofOffset);if(d!==-1){const f=c[d];Ni(a,f.endTimestamp)}}a.startTimestampIsFinal=!0}const l=X(c,a.startTimestamp,u=>u.startTimestamp);if((l===-1||c[l].moofOffset!==s.moofOffset)&&c.splice(l+1,0,{moofOffset:s.moofOffset,startTimestamp:a.startTimestamp,endTimestamp:a.endTimestamp}),a.encryptionAuxInfo&&o.encryptionInfo){const u=await no(this.reader,o.encryptionInfo,a.encryptionAuxInfo);for(let d=0;d<Math.min(a.samples.length,u.length);d++){const f=u[d];a.samples[d].encryption=f}}}return s}readContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-st&&this.traverseBox(e););}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-st;){const i=e.filePos,n=gt(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=i+n.totalSize}}traverseBox(e){const t=e.filePos,i=gt(e);if(!i)return!1;const n=e.filePos,s=t+i.totalSize;switch(i.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"mvhd":{const a=U(e);e.skip(3),a===1?(e.skip(16),this.movieTimescale=M(e),this.movieDurationInTimescale=Ce(e)):(e.skip(8),this.movieTimescale=M(e),this.movieDurationInTimescale=M(e))}break;case"trak":{const a={id:-1,demuxer:this,trackBacking:null,disposition:{...ft,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:ye,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};if(this.currentTrack=a,this.readContiguousBoxes(e.slice(n,i.contentSize)),a.id!==-1&&a.timescale!==-1&&a.info!==null){if(a.info.type==="video"&&a.info.width!==-1){const o=a;a.trackBacking=new ms(o),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){const o=a;a.trackBacking=new ps(o),this.tracks.push(a)}}this.currentTrack=null}break;case"tkhd":{const a=this.currentTrack;if(!a)break;const o=U(e),l=!!(Ze(e)&1);if(a.disposition.default=l,o===0)e.skip(8),a.id=M(e),e.skip(4),a.durationInMovieTimescale=M(e);else if(o===1)e.skip(16),a.id=M(e),e.skip(4),a.durationInMovieTimescale=Ce(e);else throw new Error(`Incorrect track header version ${o}.`);e.skip(16);const u=[St(e),St(e),Oi(e),St(e),St(e),Oi(e),St(e),St(e),Oi(e)],d=Cr(on(kl(u),90));g(d===0||d===90||d===180||d===270),a.rotation=d}break;case"elst":{const a=this.currentTrack;if(!a)break;const o=U(e);e.skip(3);let c=!1,l=0;const u=M(e);for(let d=0;d<u;d++){const f=o===1?Ce(e):M(e),h=o===1?yd(e):At(e),p=St(e);if(f!==0){if(c){H._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(h===-1){l+=f;continue}if(p!==1){H._warn("Unsupported edit list entry: media rate must be 1.");break}a.editListPreviousSegmentDurations=l,a.editListOffset=h,c=!0}}}break;case"mdhd":{const a=this.currentTrack;if(!a)break;const o=U(e);e.skip(3),o===0?(e.skip(8),a.timescale=M(e),a.durationInMediaTimescale=M(e)):o===1&&(e.skip(16),a.timescale=M(e),a.durationInMediaTimescale=Ce(e));let c=ae(e);if(c>0){a.languageCode="";for(let l=0;l<3;l++)a.languageCode=String.fromCharCode(96+(c&31))+a.languageCode,c>>=5;_r(a.languageCode)||(a.languageCode=ye)}}break;case"hdlr":{const a=this.currentTrack;if(!a)break;e.skip(8);const o=ne(e,4);o==="vide"?a.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...wa},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:o==="soun"&&(a.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(n,i.contentSize))}break;case"stsd":{const a=this.currentTrack;if(!a||a.info===null||a.sampleTable)break;const o=U(e);e.skip(3);const c=M(e);for(let l=0;l<c;l++){const u=e.filePos,d=gt(e);if(!d)break;a.internalCodecId=d.name;const f=d.name.toLowerCase();if(a.info.type==="video"){e.skip(24),a.info.width=ae(e),a.info.height=ae(e),a.info.squarePixelWidth=a.info.width,a.info.squarePixelHeight=a.info.height,e.skip(50),a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos));const h=f==="encv"?a.frmaCodecString:f;a.frmaCodecString=null,h==="avc1"||h==="avc3"?(a.info.codec="avc",a.info.avcType=h==="avc1"?1:3):h==="hvc1"||h==="hev1"?a.info.codec="hevc":h==="vp08"?a.info.codec="vp8":h==="vp09"?a.info.codec="vp9":h==="av01"?a.info.codec="av1":Ft.includes(f)?(a.info.codec="prores",a.info.proresFormat=f):h===null?H._warn("Unknown encrypted video codec due to missing frma box."):H._warn(`Unsupported video codec (sample entry type '${d.name}').`)}else{e.skip(8);const h=ae(e);e.skip(6);let p=ae(e),m=ae(e);e.skip(4);let y=M(e)/65536,w=null;o===0&&h>0&&(h===1?(e.skip(4),m=8*M(e),e.skip(8)):h===2&&(e.skip(4),y=No(e),p=M(e),e.skip(4),m=M(e),w=M(e),e.skip(8))),a.info.numberOfChannels=p,a.info.sampleRate=y,a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos));const k=f==="enca"?a.frmaCodecString:f;if(a.frmaCodecString=null,k!=="mp4a")if(k==="opus")a.info.codec="opus",a.info.sampleRate=Ti;else if(k==="flac")a.info.codec="flac";else if(k==="ulaw")a.info.codec="ulaw";else if(k==="alaw")a.info.codec="alaw";else if(k==="ac-3")a.info.codec="ac3";else if(k==="ec-3")a.info.codec="eac3";else if(ni.includes(k))a.info.codec="dts",a.info.dtsFormat=k;else if(k==="twos")m===8?a.info.codec="pcm-s8":m===16?a.info.codec=a.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(H._warn(`Unsupported sample size ${m}
1 for codec 'twos'.`),a.info.codec=null);else if(k==="sowt")m===8?a.info.codec="pcm-s8":m===16?a.info.codec="pcm-s16":(H._warn(`Unsupported sample size ${m} for codec 'sowt'.`),a.info.codec=null);else if(k==="raw ")a.info.codec="pcm-u8";else if(k==="in24")a.info.codec=a.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(k==="in32")a.info.codec=a.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(k==="fl32")a.info.codec=a.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(k==="fl64")a.info.codec=a.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(k==="ipcm"){const b=a.info.pcmSampleSize;a.info.pcmLittleEndian?b===16?a.info.codec="pcm-s16":b===24?a.info.codec="pcm-s24":b===32?a.info.codec="pcm-s32":(H._warn(`Invalid ipcm sample size ${b}.`),a.info.codec=null):b===16?a.info.codec="pcm-s16be":b===24?a.info.codec="pcm-s24be":b===32?a.info.codec="pcm-s32be":(H._warn(`Invalid ipcm sample size ${b}.`),a.info.codec=null)}else if(k==="fpcm"){const b=a.info.pcmSampleSize;a.info.pcmLittleEndian?b===32?a.info.codec="pcm-f32":b===64?a.info.codec="pcm-f64":(H._warn(`Invalid fpcm sample size ${b}.`),a.info.codec=null):b===32?a.info.codec="pcm-f32be":b===64?a.info.codec="pcm-f64be":(H._warn(`Invalid fpcm sample size ${b}.`),a.info.codec=null)}else if(k==="lpcm"&&w!==null){const b=m+7>>3,S=!!(w&1),T=!!(w&2),P=w&4?-1:0;m>0&&m<=64&&(S?m===32&&(a.info.codec=T?"pcm-f32be":"pcm-f32"):P&1<<b-1?b===1?a.info.codec="pcm-s8":b===2?a.info.codec=T?"pcm-s16be":"pcm-s16":b===3?a.info.codec=T?"pcm-s24be":"pcm-s24":b===4&&(a.info.codec=T?"pcm-s32be":"pcm-s32"):b===1&&(a.info.codec="pcm-u8")),a.info.codec===null&&H._warn("Unsupported PCM format.")}else k===null?H._warn("Unknown encrypted audio codec due to missing frma box."):H._warn(`Unsupported audio codec (sample entry type '${d.name}').`)}e.filePos=u+d.totalSize}}break;case"frma":{const a=this.currentTrack;if(!a)break;const c=ne(e,4).toLowerCase();a.frmaCodecString=c}break;case"schm":{const a=this.currentTrack;if(!a)break;e.skip(4);const o=ne(e,4);o==="cenc"||o==="cens"||o==="cbcs"?a.encryptionInfo={scheme:o,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:H._warn(`Unsupported encryption scheme '${o}'.`)}break;case"tenc":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;const o=U(e);e.skip(3),e.skip(1);const c=U(e);if(o>0?(a.encryptionInfo.defaultCryptByteBlock=c>>4,a.encryptionInfo.defaultSkipByteBlock=c&15):(a.encryptionInfo.defaultCryptByteBlock=0,a.encryptionInfo.defaultSkipByteBlock=0),a.encryptionInfo.defaultIsProtected=U(e)!==0,a.encryptionInfo.defaultPerSampleIvSize=U(e),a.encryptionInfo.defaultKid=Ir(W(e,16)),a.encryptionInfo.defaultIsProtected&&a.encryptionInfo.defaultPerSampleIvSize===0){const l=U(e),u=new Uint8Array(16);u.set(W(e,l),0),a.encryptionInfo.defaultConstantIv=u}}break;case"avcC":{const a=this.currentTrack;if(!a||(g(a.info),i.contentSize===0))break;a.info.codecDescription=W(e,i.contentSize)}break;case"hvcC":{const a=this.currentTrack;if(!a||(g(a.info),i.contentSize===0))break;a.info.codecDescription=W(e,i.contentSize)}break;case"vpcC":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="video"),e.skip(4);const o=U(e),c=U(e),l=U(e),u=l>>4,d=l>>1&7,f=l&1,h=U(e),p=U(e),m=U(e);a.info.vp9CodecInfo={profile:o,level:c,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:h,transferCharacteristics:p,matrixCoefficients:m}}break;case"av1C":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="video"),e.skip(1);const o=U(e),c=o>>5,l=o&31,u=U(e),d=u>>7,f=u>>6&1,h=u>>5&1,p=u>>4&1,m=u>>3&1,y=u>>2&1,w=u&3,k=c===2&&f?h?12:10:f?10:8;e.skip(1);const b=W(e,i.contentSize-4),S=zn(b);a.info.av1CodecInfo={profile:c,level:l,tier:d,bitDepth:k,monochrome:p,chromaSubsamplingX:m,chromaSubsamplingY:y,chromaSamplePosition:w,videoFullRangeFlag:S?.videoFullRangeFlag??0,colourPrimaries:S?.colourPrimaries??2,transferCharacteristics:S?.transferCharacteristics??2,matrixCoefficients:S?.matrixCoefficients??2}}break;case"colr":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="video");const o=ne(e,4);
1if(o!=="nclx"&&o!=="nclc")break;const c=ae(e),l=ae(e),u=ae(e);let d;o==="nclx"&&(d=!!(U(e)&128)),a.info.colorSpace={primaries:rt[c],transfer:it[l],matrix:nt[u],fullRange:d}}break;case"pasp":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="video");const o=M(e),c=M(e);o>0&&c>0&&(o>c?a.info.squarePixelWidth=Math.round(a.info.width*o/c):a.info.squarePixelHeight=Math.round(a.info.height*c/o))}break;case"wave":this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"esds":{const a=this.currentTrack;if(!a||a.info?.type!=="audio")break;e.skip(4);const o=U(e);g(o===3),Di(e),e.skip(2);const c=U(e),l=(c&128)!==0,u=(c&64)!==0,d=(c&32)!==0;if(l&&e.skip(2),u){const y=U(e);e.skip(y)}d&&e.skip(2);const f=U(e);g(f===4);const h=Di(e),p=e.filePos,m=U(e);if(m===64||m===103?(a.info.codec="aac",a.info.aacCodecInfo={isMpeg2:m===103,objectType:null}):m===105||m===107?a.info.codec="mp3":m===221?a.info.codec="vorbis":m===169?a.info.codec="dts":H._warn(`Unsupported audio codec (objectTypeIndication ${m}) - discarding track.`),e.skip(12),h>e.filePos-p){const y=U(e);g(y===5);const w=Di(e);if(a.info.codecDescription=W(e,w),a.info.codec==="aac"){const k=Fn(a.info.codecDescription);k.outputNumberOfChannels!==null&&(a.info.numberOfChannels=k.outputNumberOfChannels),k.outputSampleRate!==null&&(a.info.sampleRate=k.outputSampleRate)}}}break;case"enda":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="audio"),a.info.pcmLittleEndian=!!(ae(e)&255)}break;case"pcmC":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="audio"),e.skip(4);const o=U(e);a.info.pcmLittleEndian=!!(o&1),a.info.pcmSampleSize=U(e)}break;case"dOps":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="audio"),e.skip(1);const o=U(e),c=ae(e),l=M(e),u=xn(e),d=U(e);let f;d!==0?f=W(e,2+o):f=new Uint8Array(0);const h=new Uint8Array(19+f.byteLength),p=new DataView(h.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,o),p.setUint16(10,c,!0),p.setUint32(12,l,!0),p.setInt16(16,u,!0),p.setUint8(18,d),h.set(f,19),a.info.codecDescription=h,a.info.numberOfChannels=o}break;case"dfLa":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="audio"),e.skip(4);const o=127,c=128,l=e.filePos;for(;e.filePos<s;){const p=U(e),m=Ze(e);if((p&o)===Zt.STREAMINFO){e.skip(10);const w=M(e),k=w>>>12,b=(w>>9&7)+1;a.info.sampleRate=k,a.info.numberOfChannels=b,e.skip(20)}else e.skip(m);if(p&c)break}const u=e.filePos;e.filePos=l;const d=W(e,u-l),f=new Uint8Array(4+d.byteLength);new DataView(f.buffer).setUint32(0,1716281667,!1),f.set(d,4),a.info.codecDescription=f}break;case"dac3":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="audio");const o=W(e,3),c=new G(o),l=c.readBits(2);c.skipBits(8);const u=c.readBits(3),d=c.readBits(1);l<3&&(a.info.sampleRate=mi[l]),a.info.numberOfChannels=On[u]+d}break;case"dec3":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="audio");const o=W(e,i.contentSize),c=zc(o);if(!c){H._warn("Invalid dec3 box contents, ignoring.");break}const l=Ua(c);l!==null&&(a.info.sampleRate=l),a.info.numberOfChannels=Wa(c)}break;case"ddts":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="audio");const o=W(e,Math.min(i.contentSize,Dn)),c=Kc(o);if(!c){H._warn("Invalid ddts box contents, ignoring.");break}a.info.sampleRate=c.sampleRate,c.numberOfChannels!==null&&(a.info.numberOfChannels=c.numberOfChannels)}break;case"stts":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=M(e);let c=0,l=0;for(let u=0;u<o;u++){const d=M(e),f=M(e);a.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:d,delta:f}),c+=d,l+=d*f}}break;case"ctts":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=M(e);let c=0;for(let l=0;l<o;l++){const u=M(e),d=At(e);a.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:u,offset:d}),c+=u}}break;case"stsz":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=M(e),c=M(e);if(o===0)for(let l=0;l<c;l++){const u=M(e);a.sampleTable.sampleSizes.push(u)}else a.sampleTable.sampleSizes.push(o)}break;case"stz2":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),e.skip(3);
1const o=U(e),c=M(e),l=W(e,Math.ceil(c*o/8)),u=new G(l);for(let d=0;d<c;d++){const f=u.readBits(o);a.sampleTable.sampleSizes.push(f)}}break;case"stss":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),a.sampleTable.keySampleIndices=[];const o=M(e);for(let c=0;c<o;c++){const l=M(e)-1;a.sampleTable.keySampleIndices.push(l)}a.sampleTable.keySampleIndices[0]!==0&&a.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=M(e);for(let l=0;l<o;l++){const u=M(e)-1,d=M(e),f=M(e);a.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:u,samplesPerChunk:d,sampleDescriptionIndex:f})}let c=0;for(let l=0;l<a.sampleTable.sampleToChunk.length;l++)if(a.sampleTable.sampleToChunk[l].startSampleIndex=c,l<a.sampleTable.sampleToChunk.length-1){const d=a.sampleTable.sampleToChunk[l+1].startChunkIndex-a.sampleTable.sampleToChunk[l].startChunkIndex;c+=d*a.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=M(e);for(let c=0;c<o;c++){const l=M(e);a.sampleTable.chunkOffsets.push(l)}}break;case"co64":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=M(e);for(let c=0;c<o;c++){const l=Ce(e);a.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"mehd":{const a=U(e);e.skip(3);const o=a===1?Ce(e):M(e);this.movieDurationInTimescale=o}break;case"trex":{e.skip(4);const a=M(e),o=M(e),c=M(e),l=M(e),u=M(e);this.fragmentTrackDefaults.push({trackId:a,defaultSampleDescriptionIndex:o,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:u})}break;case"tfra":{const a=U(e);e.skip(3);const o=M(e),c=this.tracks.find(k=>k.id===o);if(!c)break;const l=M(e),u=(l&48)>>4,d=(l&12)>>2,f=l&3,h=[U,ae,Ze,M],p=h[u],m=h[d],y=h[f],w=M(e);for(let k=0;k<w;k++){const b=a===1?Ce(e):M(e),S=a===1?Ce(e):M(e);p(e),m(e),y(e),c.fragmentLookupTable.push({timestamp:b,moofOffset:S})}c.fragmentLookupTable.sort((k,b)=>k.timestamp-b.timestamp);for(let k=0;k<c.fragmentLookupTable.length-1;k++){const b=c.fragmentLookupTable[k],S=c.fragmentLookupTable[k+1];b.timestamp===S.timestamp&&(c.fragmentLookupTable.splice(k+1,1),k--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:i.totalSize,implicitBaseDataOffset:t,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(n,i.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(g(this.currentFragment),this.readContiguousBoxes(e.slice(n,i.contentSize)),this.currentTrack){const a=this.currentFragment.trackData.get(this.currentTrack.id);e:if(a){if(a.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break e}a.presentationTimestamps=a.samples.map((u,d)=>({presentationTimestamp:u.presentationTimestamp,sampleIndex:d})).sort((u,d)=>u.presentationTimestamp-d.presentationTimestamp);for(let u=0;u<a.presentationTimestamps.length;u++){const d=a.presentationTimestamps[u],f=a.samples[d.sampleIndex];if(a.firstKeyFrameTimestamp===null&&f.isKeyFrame&&(a.firstKeyFrameTimestamp=f.presentationTimestamp),u<a.presentationTimestamps.length-1){const p=a.presentationTimestamps[u+1].presentationTimestamp-d.presentationTimestamp;f.duration=p}}const o=a.samples[a.presentationTimestamps[0].sampleIndex],c=a.samples[re(a.presentationTimestamps).sampleIndex];a.startTimestamp=o.presentationTimestamp,a.endTimestamp=c.presentationTimestamp+c.duration;const{currentFragmentState:l}=this.currentTrack;g(l),l.startTimestamp!==null&&(Ni(a,l.startTimestamp),a.startTimestampIsFinal=!0),l.encryptionAuxInfo&&!a.samples[0].encryption&&(a.encryptionAuxInfo=l.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;const a=Za(W(e,i.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(a):this.currentTrack||this.psshBoxes.push(a)}break;case"tfhd":{g(this.currentFragment),e.skip(1);const a=Ze(e),o=!!(a&1),c=!!(a&2),l=!!(a&8),u=!!(a&16),d=!!(a&32),f=!!(a&65536),h=!!(a&131072),p=M(e),m=this.tracks.find(w=>w.id===p);if(!m)break;const y=this.fragmentTrackDefaults.find(w=>w.trackId===p);this.currentTrack=m,m.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,s
1ampleDescriptionIndex:y?.defaultSampleDescriptionIndex??null,defaultSampleDuration:y?.defaultSampleDuration??null,defaultSampleSize:y?.defaultSampleSize??null,defaultSampleFlags:y?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},o?m.currentFragmentState.baseDataOffset=Ce(e):h&&(m.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(m.currentFragmentState.sampleDescriptionIndex=M(e)),l&&(m.currentFragmentState.defaultSampleDuration=M(e)),u&&(m.currentFragmentState.defaultSampleSize=M(e)),d&&(m.currentFragmentState.defaultSampleFlags=M(e)),f&&(m.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const a=this.currentTrack;if(!a)break;g(a.currentFragmentState);const o=U(e);e.skip(3);const c=o===0?M(e):Ce(e);a.currentFragmentState.startTimestamp=c}break;case"trun":{const a=this.currentTrack;if(!a)break;g(this.currentFragment),g(a.currentFragmentState);const o=U(e),c=Ze(e),l=!!(c&1),u=!!(c&4),d=!!(c&256),f=!!(c&512),h=!!(c&1024),p=!!(c&2048),m=M(e);let y=null;l&&(y=At(e));let w=null;u&&(w=M(e));let k;this.currentFragment.trackData.has(a.id)?(k=this.currentFragment.trackData.get(a.id),y!==null&&(k.currentOffset=a.currentFragmentState.baseDataOffset+y)):(k={track:a,currentTimestamp:0,currentOffset:a.currentFragmentState.baseDataOffset+(y??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(a.id,k));for(let b=0;b<m;b++){let S;d?S=M(e):(g(a.currentFragmentState.defaultSampleDuration!==null),S=a.currentFragmentState.defaultSampleDuration);let T;f?T=M(e):(g(a.currentFragmentState.defaultSampleSize!==null),T=a.currentFragmentState.defaultSampleSize);let P;h?P=M(e):(g(a.currentFragmentState.defaultSampleFlags!==null),P=a.currentFragmentState.defaultSampleFlags),b===0&&w!==null&&(P=w);let I=0;p&&(o===0?I=M(e):I=At(e));const C=!(P&65536);k.samples.push({presentationTimestamp:k.currentTimestamp+I,duration:S,byteOffset:k.currentOffset,byteSize:T,isKeyFrame:C,encryption:null}),k.currentOffset+=T,k.currentTimestamp+=S}this.currentFragment.implicitBaseDataOffset=k.currentOffset}break;case"saiz":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;if(e.skip(1),Ze(e)&1){const f=ne(e,4),h=M(e);if(f!==a.encryptionInfo.scheme||h!==0)break}const c=U(e),l=M(e);let u=null;c===0&&l>0&&(u=W(e,l));const d=ys(a);d.defaultSampleInfoSize=c,d.sampleSizes=u,d.sampleCount=l}break;case"saio":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;const o=U(e);if(Ze(e)&1){const f=ne(e,4),h=M(e);if(f!==a.encryptionInfo.scheme||h!==0)break}const l=M(e);if(l===0)break;l>1&&H._warn("Multiple saio entries are not supported; using the first offset only.");let u=o===0?M(e):Number(Ce(e));this.currentFragment&&(u+=this.currentFragment.moofOffset);const d=ys(a);d.offset=u}break;case"senc":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;g(this.currentFragment);const o=this.currentFragment.trackData.get(a.id);if(!o)break;e.skip(1);const l=!!(Ze(e)&2),u=M(e),d=a.encryptionInfo.defaultPerSampleIvSize;g(d!==null);for(let f=0;f<Math.min(u,o.samples.length);f++){const h=new Uint8Array(16);d>0?h.set(W(e,d),0):h.set(a.encryptionInfo.defaultConstantIv,0);let p=null;if(l){const y=ae(e);p=[];for(let w=0;w<y;w++){const k=ae(e),b=M(e);p.push({clearLen:k,protectedLen:b})}}const m=o.samples[f];m.encryption={iv:h,subsamples:p}}}break;case"udta":{const a=this.iterateContiguousBoxes(e.slice(n,i.contentSize));for(const{boxInfo:o,slice:c}of a){if(o.name!=="meta"&&!this.currentTrack){const l=c.filePos;this.metadataTags.raw??={},o.name[0]==="©"?this.metadataTags.raw[o.name]??=We(c):this.metadataTags.raw[o.name]??=W(c,o.contentSize),c.filePos=l}switch(o.name){case"meta":c.skip(-o.headerSize),this.traverseBox(c);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=xe.decode(W(c,o.contentSize)):this.metadataTags.title??=We(c);break;case"©des":this.currentTrack||(this.metadataTags.description??=We(c));break;case"©ART":this.currentTrack||(this.metadataTags.artist??=We(c));break;case"©alb":this.currentTrack||(this.metadataTags.album??=We(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=We(c));break;case"©gen":this.currentTrack||(this.metadataTags.genre??=We(c));break;case"©day":if(!this.currentTrack){const l=new Date(We(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"©cmt":this.currentTrack||(this.metadataTags.comment??=We(c));break;case"©lyr":this.currentTrack||(this.metadataTags.lyrics??=We(c));break}}}break;case"meta":{if(this.currentTrack)break;const o=M(e)!==0;this.currentMetadataKeys=new Map,o?this.readContiguousBoxes(e.slice(n,i.contentSize)):this.readContiguousBoxes(e.slice(n+4,
1i.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const a=M(e);for(let o=0;o<a;o++){const c=M(e);e.skip(4);const l=xe.decode(W(e,c-8));this.currentMetadataKeys.set(o+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const a=this.iterateContiguousBoxes(e.slice(n,i.contentSize));for(const{boxInfo:o,slice:c}of a){let l=o.name;const u=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(u)&&(l=this.currentMetadataKeys.get(u));const d=hl(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=d,l){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":typeof d=="string"&&(this.metadataTags.title??=d);break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof d=="string"&&(this.metadataTags.description??=d);break;case"©ART":case"com.apple.quicktime.artist":case"artist":typeof d=="string"&&(this.metadataTags.artist??=d);break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":typeof d=="string"&&(this.metadataTags.album??=d);break;case"aART":case"album_artist":typeof d=="string"&&(this.metadataTags.albumArtist??=d);break;case"©cmt":case"com.apple.quicktime.comment":case"comment":typeof d=="string"&&(this.metadataTags.comment??=d);break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof d=="string"&&(this.metadataTags.genre??=d);break;case"©lyr":case"lyrics":typeof d=="string"&&(this.metadataTags.lyrics??=d);break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof d=="string"){const f=new Date(d);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"covr":case"com.apple.quicktime.artwork":d instanceof Yt?(this.metadataTags.images??=[],this.metadataTags.images.push({data:d.data,kind:"coverFront",mimeType:d.mimeType})):d instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:d,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof d=="string"){const f=d.split("/"),h=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(h)&&h>0&&(this.metadataTags.trackNumber??=h),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(d instanceof Uint8Array&&d.length>=6){const f=K(d),h=f.getUint16(2,!1),p=f.getUint16(4,!1);h>0&&(this.metadataTags.trackNumber??=h),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(d instanceof Uint8Array&&d.length>=6){const f=K(d),h=f.getUint16(2,!1),p=f.getUint16(4,!1);h>0&&(this.metadataTags.discNumber??=h),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=s,!0}}class io{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const n of e.tracks)if(n.trackBacking.getType()===t&&i++,n===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(g(e.trackBacking),((await e.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+e.durationInMediaTimescale/e.timescale)}
1async getLiveRefreshInterval(){return null}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,i=>i.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Er(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=pn(n,i),a=await this.fetchPacketForSampleIndex(s,t);return!gs(n)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const l=X(c.presentationTimestamps,i,f=>f.presentationTimestamp),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&i<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},i,i,t)}async getNextPacket(e,t){const i=this.packetToSampleIndex.get(e);if(i!==void 0)return this.fetchPacketForSampleIndex(i+1,t);const n=this.packetToFragmentLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,s=>{if(s===n.fragment){const a=s.trackData.get(this.internalTrack.id);if(n.sampleIndex+1<a.samples.length)return{sampleIndex:n.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const i=this.mapTimestampIntoTimescale(e),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=gl(n,i),a=await this.fetchPacketForSampleIndex(s,t);return!gs(n)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const l=_n(c.presentationTimestamps,f=>c.samples[f.sampleIndex].isKeyFrame&&f.presentationTimestamp<=i),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&i<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},i,i,t)}async getNextKeyPacket(e,t){const i=this.packetToSampleIndex.get(e);if(i!==void 0){const s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=wl(s,i);return this.fetchPacketForSampleIndex(a,t)}const n=this.packetToFragmentLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,s=>{if(s===n.fragment){const o=s.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>n.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{const a=s.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){const o=a.samples.findIndex(c=>c.isKeyFrame);return g(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=yl(i,e);if(!n)return null;let s;if(t.metadataOnly)s=ve;else{let l=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);if(A(l)&&(l=await l),!l)return null;if(s=W(l,n.sampleSize),this.internalTrack.encryptionInfo){let u=null;if(this.internalTrack.encryptionAuxInfo){const d=await no(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<d.length&&(u=d[e])}u??=ws(this.internalTrack.encryptionInfo),u&&(s=await ks(this.internalTrack,u,s,null))}}const a=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=n.duration/this.internalTrack.timescale,c=new Z(s,n.isKeyFrame?"key":"delta",a,o,e,n.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,i){if(t===-1)return null;const s=e.trackData.get(this.internalTrack.id).samples[t];g(s);let a;if(i.metadataOnly)a=ve;else{let u=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(A(u)&&(u=await u),!u)return null;if(a=W(u,s.byteSize),this.internalTrack.encryptionInfo){const d=s.encryption??ws(this.internalTrack.encryptionInfo);d&&(a=await ks(this.internalTrack,d,a,e))}}const o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,l=ne
1w Z(a,s.isKeyFrame?"key":"delta",o,c,e.moofOffset+t,s.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l}async performFragmentedLookup(e,t,i,n,s){const a=this.internalTrack.demuxer;let o=null,c=null,l=-1;if(e){const{sampleIndex:y,correctSampleFound:w}=t(e);if(w)return this.fetchPacketInFragment(e,y,s);y!==-1&&(c=e,l=y)}const u=X(this.internalTrack.fragmentLookupTable,i,y=>y.timestamp),d=u!==-1?this.internalTrack.fragmentLookupTable[u]:null,f=X(this.internalTrack.fragmentPositionCache,i,y=>y.startTimestamp),h=f!==-1?this.internalTrack.fragmentPositionCache[f]:null,p=Math.max(d?.moofOffset??0,h?.moofOffset??0)||null;let m;for(e?p===null||e.moofOffset>=p?(m=e.moofOffset+e.moofSize,o=e):m=p:m=p??0;;){if(o){const b=o.trackData.get(this.internalTrack.id);if(b&&b.startTimestamp>n)break}let y=a.reader.requestSliceRange(m,st,_t);if(A(y)&&(y=await y),!y)break;const w=m,k=gt(y);if(!k)break;if(k.name==="moof"){o=await a.readFragment(w);const{sampleIndex:b,correctSampleFound:S}=t(o);if(S)return this.fetchPacketInFragment(o,b,s);b!==-1&&(c=o,l=b)}m=w+k.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){const y=this.internalTrack.fragmentLookupTable[u-1];g(!y||y.timestamp<d.timestamp);const w=y?.timestamp??-1/0;return this.performFragmentedLookup(null,t,w,n,s)}return c?this.fetchPacketInFragment(c,l,s):null}}class ms extends io{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.rotation}async getColorSpace(){const e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}
1async canBeTransparent(){return this.internalTrack.info.codec==="prores"&&(this.internalTrack.info.proresFormat==="ap4h"||this.internalTrack.info.proresFormat==="ap4x")}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription){const t=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=t&&yi(t.data)}else if(this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription){const t=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=t&&ki(t.data)}else if(this.internalTrack.info.codec==="vp9"&&(!this.internalTrack.info.vp9CodecInfo||!_c(this.internalTrack.info.vp9CodecInfo))){const t=await this.getFirstPacket({}),i=t&&Fa(t.data);i&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??i,videoFullRangeFlag:i.videoFullRangeFlag,colourPrimaries:i.colourPrimaries,transferCharacteristics:i.transferCharacteristics,matrixCoefficients:i.matrixCoefficients})}else if(this.internalTrack.info.codec==="av1"&&(!this.internalTrack.info.av1CodecInfo||!vc(this.internalTrack.info.av1CodecInfo))){const t=await this.getFirstPacket({}),i=t&&zn(t.data);i&&(this.internalTrack.info.av1CodecInfo=i)}else if(this.internalTrack.info.codec==="prores"&&!this.internalTrack.info.proresCodecInfo){const t=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=t&&Ma(t.data)}if(!En(this.internalTrack.info.colorSpace)){const t=qa(this.internalTrack.info);this.internalTrack.info.colorSpace.primaries??=t.primaries,this.internalTrack.info.colorSpace.transfer??=t.transfer,this.internalTrack.info.colorSpace.matrix??=t.matrix,this.internalTrack.info.colorSpace.fullRange??=t.fullRange}const e={codec:Un(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};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}}class ps extends io{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}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.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="dts"&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&La(e.data)}return{codec:Wn(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}}const pn=(r,e)=>{if(r.presentationTimestamps){const t=X(r.presentationTimestamps,e,i=>i.presentationTimestamp);return t===-1?-1:r.presentationTimestamps[t].sampleIndex}else{const t=X(r.sampleTimingEntries,e,n=>n.startDecodeTimestamp);if(t===-1)return-1;const i=r.sampleTimingEntries[t];return i.startIndex+Math.min(Math.floor((e-i.startDecodeTimestamp)/i.delta),i.count-1)}},gl=(r,e)=>{if(!r.keySampleIndices)return pn(r,e);if(r.presentationTimestamps){const t=X(r.presentationTimestamps,e,i=>i.presentationTimestamp);if(t===-1)return-1;for(let i=t;i>=0;i--){const n=r.presentationTimestamps[i].sampleIndex;if(Mr(r.keySampleIndices,n,a=>a)!==-1)return n}return-1}else{const t=pn(r,e),i=X(r.keySampleIndices,t,n=>n);return r.keySampleIndices[i]??-1}},yl=(r,e)=>{const t=X(r.sampleTimingEntries,e,w=>w.startIndex),i=r.sampleTimingEntries[t];if(!i||i.startIndex+i.count<=e)return null;let s=i.startDecodeTimestamp+(e-i.startIndex)*i.delta;const a=X(r.sampleCompositionTimeOffsets,e,w=>
1w.startIndex),o=r.sampleCompositionTimeOffsets[a];o&&e-o.startIndex<o.count&&(s+=o.offset);const c=r.sampleSizes[Math.min(e,r.sampleSizes.length-1)],l=X(r.sampleToChunk,e,w=>w.startSampleIndex),u=r.sampleToChunk[l];g(u);const d=u.startChunkIndex+Math.floor((e-u.startSampleIndex)/u.samplesPerChunk),f=r.chunkOffsets[d],h=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk;let p=0,m=f;if(r.sampleSizes.length===1)m+=c*(e-h),p+=c*u.samplesPerChunk;else for(let w=h;w<h+u.samplesPerChunk;w++){const k=r.sampleSizes[w];w<e&&(m+=k),p+=k}let y=i.delta;if(r.presentationTimestamps){const w=r.presentationTimestampIndexMap[e];g(w!==void 0),w<r.presentationTimestamps.length-1&&(y=r.presentationTimestamps[w+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:y,sampleOffset:m,sampleSize:c,chunkOffset:f,chunkSize:p,isKeyFrame:r.keySampleIndices?Mr(r.keySampleIndices,e,w=>w)!==-1:!0}},wl=(r,e)=>{if(!r.keySampleIndices)return e+1;const t=X(r.keySampleIndices,e,i=>i);return r.keySampleIndices[t+1]??-1},Ni=(r,e)=>{r.startTimestamp+=e,r.endTimestamp+=e;for(const t of r.samples)t.presentationTimestamp+=e;for(const t of r.presentationTimestamps)t.presentationTimestamp+=e},kl=r=>{const[e,t]=r,i=Math.atan2(t,e);return Number.isFinite(i)?i*(180/Math.PI):0},gs=r=>r.sampleSizes.length===0,ys=r=>r.currentFragmentState?r.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:r.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},no=async(r,e,t)=>{if(t.resolved)return t.resolved;if(t.offset===null||t.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let i=0;if(t.defaultSampleInfoSize>
10)i=t.defaultSampleInfoSize*t.sampleCount;else{g(t.sampleSizes);for(let o=0;o<t.sampleCount;o++)i+=t.sampleSizes[o]}let n=r.requestSlice(t.offset,i);if(A(n)&&(n=await n),!n)throw new Error("Failed to read auxiliary encryption info.");const s=e.defaultPerSampleIvSize;g(s!==null);const a=[];for(let o=0;o<t.sampleCount;o++){const c=t.defaultSampleInfoSize>0?t.defaultSampleInfoSize:t.sampleSizes[o],l=new Uint8Array(16);s>0?l.set(W(n,s),0):l.set(e.defaultConstantIv,0);let u=null;if(c>s){const d=ae(n);u=[];for(let f=0;f<d;f++){const h=ae(n),p=M(n);u.push({clearLen:h,protectedLen:p})}}a.push({iv:l,subsamples:u})}return t.resolved=a,a},ws=r=>r.defaultConstantIv?{iv:r.defaultConstantIv,subsamples:null}:null,ks=async(r,e,t,i)=>{g(r.encryptionInfo);const n=r.encryptionInfo;g(n.defaultKid!==null);const s=n.defaultKid;let a;const o=r.demuxer.decryptionKeyCache.get(s);if(o)a=await o;else{if(!r.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const c=(async()=>{let l=r.demuxer.psshBoxes;if(i){l=[...l,...i.psshBoxes].filter(d=>d.keyIds===null||d.keyIds.includes(s));for(let d=0;d<l.length-1;d++)for(let f=d+1;f<l.length;f++)Ja(l[d],l[f])&&(l.splice(f,1),f--)}const u=await r.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:s,psshBoxes:l});if(!(typeof u=="string"&&u.length===32&&tc.test(u)||u instanceof Uint8Array&&u.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return u instanceof Uint8Array?u:rc(u)})();r.demuxer.decryptionKeyCache.set(s,c),a=await c}return n.scheme==="cenc"||n.scheme==="cens"?bl(a,n,e,t):Tl(a,n,e,t)},bl=async(r,e,t,i)=>{const n=new Uint8Array(16);n.set(t.iv,0);const s=await crypto.subtle.importKey("raw",r,{name:"AES-CTR"},!1,["decrypt"]),a=async p=>{const m=await crypto.subtle.decrypt({name:"AES-CTR",counter:n,length:64},s,p);return new Uint8Array(m)};if(!t.subsamples)return a(i);g(e.defaultCryptByteBlock!==null&&e.defaultSkipByteBlock!==null);const o=so(t.subsamples,e.defaultCryptByteBlock,e.defaultSkipByteBlock);let c=0;for(const p of o)for(const m of p.perSubsample)c+=m.length;const l=new Uint8Array(c);let u=0;for(const p of o)for(const m of p.perSubsample)l.set(i.subarray(m.offset,m.offset+m.length),u),u+=m.length;const d=await a(l),f=new Uint8Array(i);let h=0;for(const p of o)for(const m of p.perSubsample)f.set(d.subarray(h,h+m.length),m.offset),h+=m.length;return f},Tl=(r,e,t,i)=>{const n=new ro;n.init({key:r,iv:t.iv});const s=e.defaultCryptByteBlock,a=e.defaultSkipByteBlock;if(g(s!==null&&a!==null),!t.subsamples){const u=new Uint8Array(i),d=Math.floor(i.length/16);for(let f=0;f<d;f++){const h=f*16;n.in.set(i.subarray(h,h+16)),n.decrypt(),u.set(n.out,h)}return u}if(s===0&&a===0)throw new Error("cbcs with subsamples requires pattern encryption.");const o=new Uint8Array(i),c=so(t.subsamples,s,a),l=new DataView(t.iv.buffer,t.iv.byteOffset,16);for(const u of c){n.iv[0]=l.getUint32(0,!1),n.iv[1]=l.getUint32(4,!1),n.iv[2]=l.getUint32(8,!1),n.iv[3]=l.getUint32(12,!1);for(const d of u.perSubsample){const f=d.length/16;for(let h=0;h<f;h++){const p=d.offset+h*16;n.in.set(i.subarray(p,p+16)),n.decrypt(),o.set(n.out,p)}}}return o},so=(r,e,t)=>{const i=[],n=e!==0||t!==0;let s=0;for(const a of r){s+=a.clearLen;const o=[];if(!n)a.protectedLen>0&&o.push({offset:s,length:a.protectedLen}),s+=a.protectedLen;else{let c=a.protectedLen,l=s;for(;c>0&&!(c<16*e);){const u=16*e;o.push({offset:l,length:u}),l+=u,c-=u;const d=Math.min(16*t,c);l+=d,c-=d}s+=a.protectedLen}i.push({perSubsample:o})}return i};var B;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Duration=17545]="Duration",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.MuxingApp=19840]="MuxingApp",r[r.WritingApp=22337]="WritingApp",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.TrackNumber=215]="TrackNumber",r[r.TrackUID=29637]="TrackUID",r[r.TrackType=131]="TrackType",r[r.FlagEnabled=185]="FlagEnabled",r[r.FlagDefault=136]="FlagDefault",r[r.FlagForced=21930]="FlagForced",r[r.FlagOriginal=2
11934]="FlagOriginal",r[r.FlagHearingImpaired=21931]="FlagHearingImpaired",r[r.FlagVisualImpaired=21932]="FlagVisualImpaired",r[r.FlagCommentary=21935]="FlagCommentary",r[r.FlagLacing=156]="FlagLacing",r[r.Name=21358]="Name",r[r.Language=2274716]="Language",r[r.LanguageBCP47=2274717]="LanguageBCP47",r[r.CodecID=134]="CodecID",r[r.CodecPrivate=25506]="CodecPrivate",r[r.CodecDelay=22186]="CodecDelay",r[r.SeekPreRoll=22203]="SeekPreRoll",r[r.DefaultDuration=2352003]="DefaultDuration",r[r.Video=224]="Video",r[r.PixelWidth=176]="PixelWidth",r[r.PixelHeight=186]="PixelHeight",r[r.DisplayWidth=21680]="DisplayWidth",r[r.DisplayHeight=21690]="DisplayHeight",r[r.DisplayUnit=21682]="DisplayUnit",r[r.AlphaMode=21440]="AlphaMode",r[r.Audio=225]="Audio",r[r.SamplingFrequency=181]="SamplingFrequency",r[r.Channels=159]="Channels",r[r.BitDepth=25188]="BitDepth",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.Block=161]="Block",r[r.BlockAdditions=30113]="BlockAdditions",r[r.BlockMore=166]="BlockMore",r[r.BlockAdditional=165]="BlockAdditional",r[r.BlockAddID=238]="BlockAddID",r[r.BlockDuration=155]="BlockDuration",r[r.ReferenceBlock=251]="ReferenceBlock",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.Colour=21936]="Colour",r[r.MatrixCoefficients=21937]="MatrixCoefficients",r[r.TransferCharacteristics=21946]="TransferCharacteristics",r[r.Primaries=21947]="Primaries",r[r.Range=21945]="Range",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPoseRoll=30325]="ProjectionPoseRoll",r[r.Attachments=423732329]="Attachments",r[r.AttachedFile=24999]="AttachedFile",r[r.FileDescription=18046]="FileDescription",r[r.FileName=18030]="FileName",r[r.FileMediaType=18016]="FileMediaType",r[r.FileData=18012]="FileData",r[r.FileUID=18094]="FileUID",r[r.Chapters=272869232]="Chapters",r[r.Tags=307544935]="Tags",r[r.Tag=29555]="Tag",r[r.Targets=25536]="Targets",r[r.TargetTypeValue=26826]="TargetTypeValue",r[r.TargetType=25546]="TargetType",r[r.TagTrackUID=25541]="TagTrackUID",r[r.TagEditionUID=25545]="TagEditionUID",r[r.TagChapterUID=25540]="TagChapterUID",r[r.TagAttachmentUID=25542]="TagAttachmentUID",r[r.SimpleTag=26568]="SimpleTag",r[r.TagName=17827]="TagName",r[r.TagLanguage=17530]="TagLanguage",r[r.TagString=17543]="TagString",r[r.TagBinary=17541]="TagBinary",r[r.ContentEncodings=28032]="ContentEncodings",r[r.ContentEncoding=25152]="ContentEncoding",r[r.ContentEncodingOrder=20529]="ContentEncodingOrder",r[r.ContentEncodingScope=20530]="ContentEncodingScope",r[r.ContentCompression=20532]="ContentCompression",r[r.ContentCompAlgo=16980]="ContentCompAlgo",r[r.ContentCompSettings=16981]="ContentCompSettings",r[r.ContentEncryption=20533]="ContentEncryption"})(B||(B={}));const Sl=[B.EBML,B.Segment],Fr=[B.SeekHead,B.Info,B.Cluster,B.Tracks,B.Cues,B.Attachments,B.Chapters,B.Tags],Yr=[...Sl,...Fr],gn=8,Be=2,at=2*gn,ao=r=>{if(r.remainingLength<1)return null;const e=U(r);if(r.skip(-1),e===0)return null;let t=1,i=128;for(;(e&i)===0;)t++,i>>=1;return r.remainingLength<t?null:t},kr=r=>{if(r.remainingLength<1)return null;const e=U(r);if(e===0)return null;let t=1,i=128;for(;(e&i)===0;)t++,i>>=1;if(r.remainingLength<t-1)return null;let n=e&i-1;for(let s=1;s<t;s++)n*=256,n+=U(r);return n},j=(r,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let i=0;i<e;i++)t*=256,t+=U(r);return t},xl=(r,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let i=0;i<e;i++)t<<=8n,t+=BigInt(U(r));return t},Hn=r=>{const e=ao(r);return e===null||r.remainingLength<e?null:j(r,e)},oo=r=>{if(r.remainingLength<1)return null;if(U(r)===255)return;r.skip(-1);const t=kr(r);if(t===null)return null;if(t!==72057594037927940)return t},et=r=>{g(r.remainingLength>=Be);const e=Hn(r);if(e===null)return null;const t=oo(r);return t===null?null:{id:e,size:t}},$t=(r,e)=>{const t=W(r,e);let i=0;for(;i<e&&t[i]!==0;)i+=1;return String.fromCharCode(...t.subarray(0,i))},cr=(r,e)=>{const t=W(r,e);let i=0;for(;i<e&&t[i]!==0;)i+=1;return xe.decode(t.subarray(0,i))},Ui=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?kd(r):No(r)},yn=async(r,e,t,i)=>{const n=new Set(t);let s=e;for(;i===null||s<i;){let a=r.requestSliceRange(s,Be,at);if(A(a)&&(a=await a),!a)break;const o=et(a);if(!o)break;if(n.has(o.id))return{pos:s,found:!0};pt(o.size),s=a.filePos+o.size}return{pos:i!==null&&i>s?i:s,found:!1}},co=async(r,e,t,i)=>{const s=new Set(t);let a=e;for(;a<i;){let o=r.requestSliceRange(a,0,Math.min(65536,i-a));if(A(o)&&(o=await o),!o||o.length<gn)break;for(let c=0;c<o.length-gn;c++){o.filePos=a;const l=Hn(o);if(l!==null&&s.has(l))return a;a++}}return null},Se={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",prores:"V_PRORES",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3",dts:"A_DTS"};function pt(r){if(r===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}const Pl=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isWebM?"webm":"x-matroska");if(r.codecStrings.length>
10){const i=[...new Set(r.codecStrings.filter(Boolean))];t+=`; codecs="${i.join(", ")}"`}return t};var Je;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(Je||(Je={}));var ai;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(ai||(ai={}));var Sr;(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})(Sr||(Sr={}));const Wi=[{id:B.SeekHead,flag:"seekHeadSeen"},{id:B.Info,flag:"infoSeen"},{id:B.Tracks,flag:"tracksSeen"},{id:B.Cues,flag:"cuesSeen"}],lo=10*2**20;class Cl extends ht{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 getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.trackBacking))}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(i=>i.getDecoderConfig().then(n=>n?.codec??null)));return Pl({isWebM:this.isWebM,hasVideo:this.segments.some(i=>i.tracks.some(n=>n.info?.type==="video")),hasAudio:this.segments.some(i=>i.tracks.some(n=>n.info?.type==="audio")),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(const 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,Be,at);if(A(t)&&(t=await t),!t)break;const i=et(t);if(!i)break;const n=i.id;let s=i.size;const a=t.filePos;if(n===B.EBML){pt(s);let o=this.reader.requestSlice(a,s);if(A(o)&&(o=await o),!o)break;this.readContiguousElements(o)}else if(n===B.Segment){if(await this.readSegment(a,s),s===void 0||this.reader.fileSize===null)break}else if(n===B.Cluster){if(this.reader.fileSize===null)break;s===void 0&&(s=(await yn(this.reader,a,Yr,this.reader.fileSize)).pos-a);const o=re(this.segments);o&&(o.elementEndPos=a+s)}pt(s),e=a+s}})()}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:t===void 0?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let i=e;for(;this.currentSegment.elementEndPos===null||i<this.currentSegment.elementEndPos;){let o=this.reader.requestSliceRange(i,Be,at);if(A(o)&&(o=await o),!o)break;const c=i,l=et(o);if(!l||!Fr.includes(l.id)&&l.id!==B.Void){const p=await co(this.reader,c,Fr,Math.min(this.currentSegment.elementEndPos??1/0,c+lo));if(p){i=p;continue}else break}const{id:u,size:d}=l,f=o.filePos,h=Wi.findIndex(p=>p.id===u);if(h!==-1){const p=Wi[h].flag;this.currentSegment[p]=!0,pt(d);let m=this.reader.requestSlice(f,d);A(m)&&(m=await m),m&&this.readContiguousElements(m)}else if(u===B.Tags||u===B.Attachments){u===B.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,pt(d);let p=this.reader.requestSlice(f,d);A(p)&&(p=await p),p&&this.readContiguousElements(p)}else if(u===B.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===void 0)break;i=f+d}if(this.currentSegment.seekEntries.sort((o,c)=>o.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(const o of this.currentSegment.seekEntries){const c=Wi.find(p=>p.id===o.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+o.segmentPosition,Be,at);if(A(l)&&(l=await l),!l)continue;const u=et(l);if(!u)continue;const{id:d,size:f}=u;if(d!==c.id)continue;pt(f),this.currentSegment[c.flag]=!0;let h=this.reader.requestSlice(l.filePos,f);A(h)&&(h=await h),h&&this.readContiguousElements(h)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(const o of this.currentSegment.tracks)o.defaultDurationNs!==null&&(o.defaultDuration=this.currentSegment.timestampFactor*o.defaultDurationNs/1e9);const n=new Map(this.currentSegment.tracks.map(o=>[o.id,o]));for(const o of this.currentSegment.cuePoints){const c=n.get(o.trackId);c&&c.cuePoints.push(o)}for(const o of this.currentSegment.tracks){o.cuePoints.sort((c,l)=>c.time-l.time);for(let c=0;c<o.cuePoints.length-1;c++){const l=o.cuePoints[c],u=o.cuePoints[c+1];l.time===u.time&&(o.cuePoints.splice(c+1,1),c--)}}let s=null,a=-1/0;for(const o of this.currentSegment.tracks)o.cuePoints.length>a&&(a=o.cuePoints.length,s=o);for(const o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let i=this.reader.requestSliceRange(e,Be,at);A(i)&&(i=await i),g(i);const n=e,s=et(i);g(s);const a=s.id;g(a===B.Cluster);let o=s.size;const c=i.filePos;o===void 0&&(o=(await yn(this.reader,c,Yr,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,o);A(l)&&(l=await l);const u={segment:t,elementStartPos:n,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){const d=this.readContiguousElements(l,Yr);u.elementEndPos=d}for(const[,d]of u.trackData){const f=d.track;g(d.blocks.length>0);let h=!1;for(let w=0;w<d.blocks.length;w++){const k=d.blocks[w];k.timestamp+=u.timestamp,h||=k.lacing!==Je.None}d.presentationTimestamps=d.blocks.map((w,k)=>({timestamp:w.timestamp,blockIndex:k})).sort((w,k)=>w.timestamp-k.timestamp);for(let w=0;w<d.presentationTimestamps.length;w++){const k=d.presentationTimestamps[w],b=d.blocks[k.blockIndex];if(d.firstKeyFrameTimestamp===null&&b.isKeyFrame&&(d.firstKeyFrameTimestamp=b.timestamp),w<d.presentationTimestamps.length-1){const S=d.presentationTimestamps[w+1];b.duration=S.timestamp-b.timestamp}else b.duration===0&&f.defaultDuration!=null&&b.lacing===Je.None&&(b.duration=f.defaultDuration)}h&&(this.expandLacedBlocks(d.blocks,f),d.presentationTimestamps=d.blocks.map((w,k)=>({timestamp:w.timestamp,blockIndex:k})).sort((w,k)=>w.timestamp-k.timestamp));const p=d.blocks[d.presentationTimestamps[0].blockIndex],m=d.blocks[re(d.presentationTimestamps).blockIndex];d.startTimestamp=p.timestamp,d.endTimestamp=m.timestamp+m.duration;const y=X(f.clusterPositionCache,d.startTimestamp,w=>w.startTimestamp);(y===-1||f.clusterPositionCache[y].elementStartPos!==n)&&f.clusterPositionCache.splice(y+1,0,{elementStartPos:u.elementStartPos,startTimestamp:d.startTimestamp})}return t.lastReadCluster=u,u}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){const n=e.segment.tracks.find(s=>s.id===t);if(!n)return null;i={track:n,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}
1expandLacedBlocks(e,t){for(let i=0;i<e.length;i++){const n=e[i];if(n.lacing===Je.None)continue;n.decoded||(n.data=this.decodeBlockData(t,n.data),n.decoded=!0);const s=Ee.tempFromBytes(n.data),a=[],o=U(s)+1;switch(n.lacing){case Je.Xiph:{let l=0;for(let u=0;u<o-1;u++){let d=0;for(;s.bufferPos<s.length;){const f=U(s);if(d+=f,f<255){a.push(d),l+=d;break}}}a.push(s.length-(s.bufferPos+l))}break;case Je.FixedSize:{const l=s.length-1,u=Math.floor(l/o);for(let d=0;d<o;d++)a.push(u)}break;case Je.Ebml:{const l=kr(s);g(l!==null);let u=l;a.push(u);let d=u;for(let f=1;f<o-1;f++){const h=s.bufferPos,p=kr(s);g(p!==null);const m=p,w=(1<<(s.bufferPos-h)*7-1)-1,k=m-w;u+=k,a.push(u),d+=u}a.push(s.length-(s.bufferPos+d))}break;default:g(!1)}g(a.length===o),e.splice(i,1);const c=n.duration||o*(t.defaultDuration??0);for(let l=0;l<o;l++){const u=a[l],d=W(s,u),f=n.timestamp+c*l/o,h=c/o;e.splice(i+l,0,{timestamp:f,duration:h,isKeyFrame:n.isKeyFrame,data:d,lacing:Je.None,decoded:!0,postProcessed:!1,mainAdditional:n.mainAdditional})}i+=o,i--}}async loadSegmentMetadata(e){for(const t of e.seekEntries){if(!(t.id===B.Tags&&!e.tagsSeen)){if(!(t.id===B.Attachments&&!e.attachmentsSeen))continue}let i=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,Be,at);if(A(i)&&(i=await i),!i)continue;const n=et(i);if(!n||n.id!==t.id)continue;const{size:s}=n;pt(s),g(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(i.filePos,s);A(a)&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,t.id===B.Tags?e.tagsSeen=!0:t.id===B.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=Be;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){const i=et(e);if(!i||t&&t.includes(i.id))return!1;const{id:n,size:s}=i,a=e.filePos;switch(pt(s),n){case B.DocType:this.isWebM=$t(e,s)==="webm";break;case B.Seek:{if(!this.currentSegment)break;const o={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(o),this.readContiguousElements(e.slice(a,s)),(o.id===-1||o.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case B.SeekID:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.id=j(e,s)}break;case B.SeekPosition:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=j(e,s)}break;case B.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=j(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case B.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Ui(e,s)}break;case B.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...ft,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(o=>o.data?.type!=="decompress"||o.scope!==ai.Block||o.data.algorithm!==Sr.HeaderStripping)&&(H._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){const o=this.currentTrack.codecId.indexOf("/"),c=o===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,o);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){const u=this.currentTrack.info.displayWidth*this.currentTrack.info.height,d=this.currentTrack.info.displayHeight*this.currentTrack.info.width;u>0&&d>0&&(u>d?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*u/d):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*d/u))}if(this.currentTrack.codecId===Se.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPr
1ivate;else if(this.currentTrack.codecId===Se.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(c===Se.vp8)this.currentTrack.info.codec="vp8";else if(c===Se.vp9)this.currentTrack.info.codec="vp9";else if(c===Se.av1)this.currentTrack.info.codec="av1";else if(c===Se.prores){const u=this.currentTrack.codecPrivate?xe.decode(this.currentTrack.codecPrivate):"";Ft.includes(u)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=u)}const l=this.currentTrack;this.currentTrack.trackBacking=new Il(l),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){c===Se.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Se.mp3?this.currentTrack.info.codec="mp3":c===Se.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Ti):c===Se.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Se.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Se.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Se.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Se.dts?(this.currentTrack.info.codec="dts",this.currentTrack.codecId==="A_DTS/EXPRESS"?this.currentTrack.info.dtsFormat="dtse":this.currentTrack.codecId==="A_DTS/LOSSLESS"&&(this.currentTrack.info.dtsFormat="dtsl")):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));const l=this.currentTrack;this.currentTrack.trackBacking=new El(l),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case B.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=j(e,s)}break;case B.TrackType:{if(!this.currentTrack)break;const o=j(e,s);o===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:{...wa},alphaMode:!1,proresFormat:null}:o===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case B.FlagEnabled:{if(!this.currentTrack)break;j(e,s)||(this.currentTrack=null)}break;case B.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!j(e,s)}break;case B.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!j(e,s)}break;case B.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!j(e,s)}break;case B.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!j(e,s)}break;case B.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!j(e,s)}break;case B.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!j(e,s)}break;case B.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=$t(e,s)}break;
1case B.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=W(e,s)}break;case B.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=j(e,s)}break;case B.Name:{if(!this.currentTrack)break;this.currentTrack.name=cr(e,s)}break;case B.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=$t(e,s),_r(this.currentTrack.languageCode)||(this.currentTrack.languageCode=ye)}break;case B.LanguageBCP47:{if(!this.currentTrack)break;const c=$t(e,s).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=ye,this.currentTrack.hasLanguageBcp47=!0}break;case B.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case B.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=j(e,s)}break;case B.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=j(e,s)}break;case B.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=j(e,s)}break;case B.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=j(e,s)}break;case B.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=j(e,s)}break;case B.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=j(e,s)===1}break;case B.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case B.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video")break;const o=j(e,s),c=nt[o];this.currentTrack.info.colorSpace.matrix=c}break;case B.Range:{if(this.currentTrack?.info?.type!=="video")break;const o=j(e,s);this.currentTrack.info.colorSpace.fullRange=o===1||o===2?o===2:void 0}break;case B.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video")break;const o=j(e,s),c=it[o];this.currentTrack.info.colorSpace.transfer=c}break;case B.Primaries:{if(this.currentTrack?.info?.type!=="video")break;const o=j(e,s),c=rt[o];this.currentTrack.info.colorSpace.primaries=c}break;case B.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case B.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;const c=-Ui(e,s);try{this.currentTrack.info.rotation=Cr(c)}catch{}}break;case B.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(a,s))}break;case B.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=Ui(e,s)}break;case B.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=j(e,s)}break;case B.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=j(e,s)}break;case B.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,s)),this.currentCueTime=null}break;case B.CueTime:this.currentCueTime=j(e,s);break;case B.CueTrackPositions:{if(this.currentCueTime===null)break;g(this.currentSegment);const o={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(o),this.readContiguousElements(e.slice(a,s)),(o.trackId===-1||o.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case B.CueTrack:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=j(e,s)}break;case B.CueClusterPosition:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;g(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+j(e,s)}break;case B.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=j(e,s)}break;case B.SimpleBlock:{if(!this.currentCluster)break;const o=kr(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const l=xn(e),u=U(e),d=u>>1&3;let f=!!(u&128);c.track.info?.type==="audio"&&c.track.info.codec&&(f=!0);const h=W(e,s-(e.filePos-a)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:f,data:h,lacing:d,decoded:!p,postProcessed:!1,mainAdditional:null})}break;case B.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,s)),this.currentBlock=null}break;case B.Block:{if(!this.currentCluster)break;const o=kr(e);
1if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const l=xn(e),d=U(e)>>1&3,f=W(e,s-(e.filePos-a)),h=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:f,lacing:d,decoded:!h,postProcessed:!1,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case B.BlockAdditions:this.readContiguousElements(e.slice(a,s));break;case B.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case B.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=W(e,s)}break;case B.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=j(e,s)}break;case B.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=j(e,s)}break;case B.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case B.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,s));break;case B.Targets:this.readContiguousElements(e.slice(a,s));break;case B.TargetTypeValue:j(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case B.TagTrackUID:case B.TagEditionUID:case B.TagChapterUID:case B.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case B.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,s))}break;case B.TagName:this.currentSimpleTagName=cr(e,s);break;case B.TagString:{if(!this.currentSimpleTagName)break;const o=cr(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case B.TagBinary:{if(!this.currentSimpleTagName)break;const o=W(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case B.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,s));const o=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(o.raw??={},o.raw[this.currentAttachedFile.fileUid.toString()]=new Pa(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){const c=this.currentAttachedFile.fileName;let l="unknown";if(c){const u=c.toLowerCase();u.startsWith("cover.")?l="coverFront":u.startsWith("back.")&&(l="coverBack")}o.images??=[],o.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:l,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case B.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=xl(e,s)}break;case B.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=cr(e,s)}break;
1case B.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=$t(e,s)}break;case B.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=W(e,s)}break;case B.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=cr(e,s)}break;case B.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,s)),this.currentTrack.decodingInstructions.sort((o,c)=>c.order-o.order)}break;case B.ContentEncoding:this.currentDecodingInstruction={order:0,scope:ai.Block,data:null},this.readContiguousElements(e.slice(a,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case B.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=j(e,s)}break;case B.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=j(e,s)}break;case B.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Sr.Zlib,settings:null},this.readContiguousElements(e.slice(a,s))}break;case B.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=j(e,s)}break;case B.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=W(e,s)}break;case B.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+s,!0}decodeBlockData(e,t){g(e.decodingInstructions.length>0);let i=t;for(const n of e.decodingInstructions)switch(g(n.data),n.data.type){case"decompress":switch(n.data.algorithm){case Sr.HeaderStripping:if(n.data.settings&&n.data.settings.length>0){const s=n.data.settings,a=new Uint8Array(s.length+i.length);a.set(s,0),a.set(i,s.length),i=a}break}break}return i}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;const i=this.currentSegment.metadataTags;if(i.raw??={},i.raw[e]??=t,typeof t=="string")switch(e.toLowerCase()){case"title":i.title??=t;break;case"description":i.description??=t;break;case"artist":i.artist??=t;break;case"album":i.album??=t;break;case"album_artist":i.albumArtist??=t;break;case"genre":i.genre??=t;break;case"comment":i.comment??=t;break;case"lyrics":i.lyrics??=t;break;case"date":{const n=new Date(t);Number.isNaN(n.getTime())||(i.date??=n)}break;case"track_number":case"part_number":{const n=t.split("/"),s=Number.parseInt(n[0],10),a=n[1]&&Number.parseInt(n[1],10);Number.isInteger(s)&&s>0&&(i.trackNumber??=s),a&&Number.isInteger(a)&&a>0&&(i.tracksTotal??=a)}break;case"disc_number":case"disc":{const n=t.split("/"),s=Number.parseInt(n[0],10),a=n[1]&&Number.parseInt(n[1],10);Number.isInteger(s)&&s>0&&(i.discNumber??=s),a&&Number.isInteger(a)&&a>0&&(i.discsTotal??=a)}break}}}class uo{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const n of e.segments)for(const s of n.tracks)if(s.trackBacking.getType()===t&&i++,s===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack.segment;if(e.duration<=0)return null;let t=e.duration/e.timestampFactor;const i=await this.getFirstPacket({metadataOnly:!0});return t+=i?.timestamp??0,t}
1async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,t=>t.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Er(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,n=>{const s=n.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};const a=X(s.presentationTimestamps,i,l=>l.timestamp),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},i,i,t)}async getNextPacket(e,t){const i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,n=>{if(n===i.cluster){const s=n.trackData.get(this.internalTrack.id);if(i.blockIndex+1<s.blocks.length)return{blockIndex:i.blockIndex+1,correctBlockFound:!0}}else if(n.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,n=>{const s=n.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};const a=_n(s.presentationTimestamps,l=>s.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=i),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},i,i,t)}async getNextKeyPacket(e,t){const i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,n=>{if(n===i.cluster){const a=n.trackData.get(this.internalTrack.id).blocks.findIndex((o,c)=>o.isKeyFrame&&c>i.blockIndex);if(a!==-1)return{blockIndex:a,correctBlockFound:!0}}else{const s=n.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){const a=s.blocks.findIndex(o=>o.isKeyFrame);return g(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,i){if(t===-1)return null;const s=e.trackData.get(this.internalTrack.id).blocks[t];if(g(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0),!s.postProcessed){if(this.internalTrack.info?.codec==="prores"&&!(s.data.length>=8&&s.data[4]===105&&s.data[5]===99&&s.data[6]===112&&s.data[7]===102)){const f=new Uint8Array(s.data.length+8);K(f).setUint32(0,f.length,!1),f[4]=105,f[5]=99,f[6]=112,f[7]=102,f.set(s.data,8),s.data=f}s.postProcessed=!0}const a=i.metadataOnly?ve:s.data,o=s.timestamp/this.internalTrack.segment.timestampFactor,c=s.duration/this.internalTrack.segment.timestampFactor,l={};s.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=i.metadataOnly?ve:s.mainAdditional,l.alphaByteLength=s.mainAdditional.byteLength);const u=new Z(a,s.isKeyFrame?"key":"delta",o,c,e.dataStartPos+t,s.data.byteLength,l);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}async performClusterLookup(e,t,i,n,s){const{demuxer:a,segment:o}=this.internalTrack;let c=null,l=null,u=-1;if(e){const{blockIndex:w,correctBlockFound:k}=t(e);if(k)return this.fetchPacketInCluster(e,w,s);w!==-1&&(l=e,u=w)}const d=X(this.internalTrack.cuePoints,i,w=>w.time),f=d!==-1?this.internalTrack.cuePoints[d]:null,h=X(this.internalTrack.clusterPositionCache,i,w=>w.startTimestamp),p=h!==-1?this.internalTrack.clusterPositionCache[h]:null,m=Math.max(f?.clusterPosition??0,p?.elementStartPos??0)||null;let y;for(e?m===null||e.elementStartPos>=m?(y=e.elementEndPos,c=e):y=m:y=m??o.clusterSeekStartPos;o.elementEndPos===null||y<=o.elementEndPos-Be;){if(c){const C=c.trackData.get(this.internalTrack.id);if(C&&C.startTimestamp>n)break}let w=a.reader.requestSliceRange(y,Be,at);if(A(w)&&(w=await w),!w)break;const k=y,b=et(w);if(!b||!Fr.includes(b.id)&&b.id!==B.Void){const C=await co(a.reader,k,Fr,Math.min(o.elementEndPos??1/0,k+lo));if(C){y=C;continue}else break}const S=b.id;let T=b.size;const P=w.filePos;if(S===B.Cluster){c=await a.readCluster(k,o),T=c.elementEndPos-P;const{blockIndex:C,correctBlockFound:x}=t(c);if(x)return this.fetchPacketInCluster(c,C,s);C!==-1&&(l=c,u=C)}T===void 0&&(g(S!==B.Cluster),T=(await yn(a.reader,P,Yr,o.elementEndPos)).pos-P);const I=P+T;if(o.elementEndPos===null){let C=a.reader.requestSliceRange(I,Be,at);if(A(C)&&(C=await C),!C)break;if(Hn(C)===B.Segment){o.elementEndPos=I;break}}y=I}if(f&&(!l||l.elementStartPos<f.clusterPosition)){const w=this.internalTrack.cuePoints[d-1];g(!w||w.time<f.time);const k=w?.time??-1/0;return this.performClusterLookup(null,t,k,n,s)}return l?this.fetchPacketInCluster(l,u,s):null}}class Il extends uo{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){const e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}
vendor: 1,279 bytes, line 1
1async canBeTransparent(){return this.internalTrack.info.alphaMode||this.internalTrack.info.codec==="prores"&&(this.internalTrack.info.proresFormat==="ap4h"||this.internalTrack.info.proresFormat==="ap4x")}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="prores"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));const i={width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?yi(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?ki(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Fa(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?zn(e.data):null,proresCodecInfo:this.internalTrack.info.codec==="prores"&&e?Ma(e.data):null,proresFormat:this.internalTrack.info.proresFormat};
1if(!En(this.internalTrack.info.colorSpace)){const s=qa(i);this.internalTrack.info.colorSpace.primaries??=s.primaries,this.internalTrack.info.colorSpace.transfer??=s.transfer,this.internalTrack.info.colorSpace.matrix??=s.matrix,this.internalTrack.info.colorSpace.fullRange??=s.fullRange}const n={codec:Un(i),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})():null}}class El extends uo{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}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.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="dts"&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&La(e.data)}return{codec:Wn({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}}const wn=async(r,e,t,i=null)=>{let s=e;for(;t===null||s<t;){const a=t!==null?Math.min(65536,t-s):65536;let o=r.requestSliceRange(s,Rt,a);if(A(o)&&(o=await o),!o||o.length<Rt)break;for(;o.remainingLength>=Rt;){const c=o.filePos,l=M(o),u=r.fileSize!==null?r.fileSize-s:null,d=Vn(l,u);if(d.header&&(!i||d.header.sampleRate===i.sampleRate&&d.header.mpegVersionId===i.mpegVersionId&&d.header.layer===i.layer&&Br(d.header.channel)===Br(i.channel)))return{header:d.header,startPos:s};o.filePos=c+d.bytesAdvanced,s=o.filePos}}return null};class _l extends ht{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new or,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new vl(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,Me);if(A(o)&&(o=await o),!o){this.lastSampleLoaded=!0;return}const c=dt(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}const e=await wn(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=Qa(t.mpegVersionId,t.channel);let n=this.reader.requestSlice(e.startPos+i,4);if(A(n)&&(n=await n),n){const o=M(n);if(o===Ga||o===Xa){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let l=this.reader.requestSlice(e.startPos+i+4,12);if(A(l)&&(l=await l),l){const u=W(l,12),d=K(u),f=d.getUint32(0,!1);this.xingData={frameCount:f&si.FrameCount?d.getUint32(4,!1):null,fileSize:f&si.FileSize?d.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);const s=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,i=!1;for(;;){let n=this.reader.requestSlice(t,Me);if(A(n)&&(n=await n),!n)break;const s=dt(n);if(!s)break;i=!0;let a=this.reader.requestSlice(n.filePos,s.size);if(A(a)&&(a=await a),!a)break;Ci(a,s,this.metadataTags),t=n.filePos+s.size}if(!i&&this.reader.fileSize!==null&&this.reader.fileSize>=Jr){let n=this.reader.requestSlice(this.reader.fileSize-Jr,Jr);A(n)&&(n=await n),g(n),ne(n,3)==="TAG"&&bd(n,this.metadataTags)}return this.metadataTags}finally{e()}}}class vl{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.demuxer;if(g(e.firstFrameHeader!==null),g(e.firstFrameHeaderPos!==null),e.xingData){if(e.xingData.frameCount!==null)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(e.reader.fileSize!==null){const t=fl(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),i=(e.reader.fileSize-e.firstFrameHeaderPos)/t;return Math.round(i)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}return null}
1async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return ye}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return g(this.demuxer.firstFrameHeader),Br(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...ft}}async getDecoderConfig(){return g(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:Br(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let n;if(t.metadataOnly)n=ve;else{let s=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(A(s)&&(s=await s),!s)return null;n=W(s,i.dataSize)}return new Z(n,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const n=Mr(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(n===-1)throw new Error("Packet was not created from this track.");const s=n+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const n=X(this.demuxer.loadedSamples,e,s=>s.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(n,t);if(n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const fo=1399285583,Al=79764919,ho=new Uint32Array(256);for(let r=0;r<256;r++){let e=r<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^Al:e<<1;ho[r]=e>>>0&4294967295}const Bl=r=>{const e=K(r),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let i=0;for(let n=0;n<r.length;n++){const s=r[n];i=(i<<8^ho[i>>>24^s])>>>0}return e.setUint32(22,t,!0),i},Fl=(r,e,t)=>{let i=0,n=null;if(r.length>0)if(e.codec==="vorbis"){g(e.vorbisInfo);const s=e.vorbisInfo.modeBlockflags.length,o=(1<<cc(s-1))-1<<1,c=(r[0]&o)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t;const u=e.vorbisInfo.modeBlockflags[c];if(n=e.vorbisInfo.blocksizes[u],u===1){const d=(o|1)+1,f=r[0]&d?1:0;l=e.vorbisInfo.blocksizes[f]}i=l!==null?l+n>>2:0}else e.codec==="opus"&&(i=Bc(r).durationInSamples);return{durationInSamples:i,vorbisBlockSize:n}},Rl=r=>{let e="audio/ogg";if(r.codecStrings){const t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};const vt=27,er=282,Ml=er+65025,xr=r=>{const e=r.filePos;if(Gt(r)!==fo)return null;r.skip(1);const i=U(r),n=wd(r),s=Gt(r),a=Gt(r),o=Gt(r),c=U(r),l=new Uint8Array(c);for(let h=0;h<c;h++)l[h]=U(r);const u=27+c,d=l.reduce((h,p)=>h+p,0),f=u+d;return{headerStartPos:e,totalSize:f,dataStartPos:e+u,dataSize:d,headerType:i,granulePosition:n,serialNumber:s,sequenceNumber:a,checksum:o,lacingValues:l}},zl=(r,e)=>{for(;r.filePos<e-3;){const t=Gt(r),i=t&255,n=t>>>8&255,s=t>>>16&255,a=t>>>24&255,o=79;if(!(i!==o&&n!==o&&s!==o&&a!==o)){if(r.skip(-4),t===fo)return!0;r.skip(1)}}return!1};class Ol extends ht{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,vt,er);if(A(t)&&(t=await t),!t)break;const i=xr(t);if(!i||!!!(i.headerType&2))break;this.bitstreams.push({serialNumber:i.serialNumber,bosPage:i,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=i.headerStartPos+i.totalSize}for(const t of this.bitstreams){const i=await this.readPacket(t.bosPage,0);i&&(i.data.byteLength>=7&&i.data[0]===1&&i.data[1]===118&&i.data[2]===111&&i.data[3]===114&&i.data[4]===98&&i.data[5]===105&&i.data[6]===115?await this.readVorbisMetadata(i,t):i.data.byteLength>=8&&i.data[0]===79&&i.data[1]===112&&i.data[2]===117&&i.data[3]===115&&i.data[4]===72&&i.data[5]===101&&i.data[6]===97&&i.data[7]===100&&await this.readOpusMetadata(i,t),t.codecInfo.codec!==null&&this.trackBackings.push(new Dl(t,this)))}})()}async readVorbisMetadata(e,t){let i=await this.findNextPacketStart(e);if(!i)return;const n=await this.readPacket(i.startPage,i.startSegmentIndex);if(!n||(i=await this.findNextPacketStart(n),!i))return;const s=await this.readPacket(i.startPage,i.startSegmentIndex);if(!s||n.data[0]!==3||s.data[0]!==5)return;const a=[],o=d=>{for(;a.push(Math.min(255,d)),!(d<255);)d-=255};o(e.data.length),o(n.data.length);const c=new Uint8Array(1+a.length+e.data.length+n.data.length+s.data.length);c[0]=2,c.set(a,1),c.set(e.data,1+a.length),c.set(n.data,1+a.length+e.data.length),c.set(s.data,1+a.length+e.data.length+n.data.length),t.codecInfo.codec="vorbis",t.description=c,t.lastMetadataPacket=s;const l=K(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);const u=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(u&15),1<<(u>>4)],modeBlockflags:Fc(s.data).modeBlockflags},fn(n.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const i=await this.findNextPacketStart(e);if(!i)return;const n=await this.readPacket(i.startPage,i.startSegmentIndex);if(!n)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=n;const s=za(e.data);t.numberOfChannels=s.outputChannelCount,t.sampleRate=Ti,t.codecInfo.opusInfo={preSkip:s.preSkip},fn(n.data.subarray(8),this.metadataTags)}async readPacket(e,t){g(t<e.lacingValues.length);let i=0;for(let d=0;d<t;d++)i+=e.lacingValues[d];let n=e,s=i,a=t;const o=[];e:for(;;){let d=this.reader.requestSlice(n.dataStartPos,n.dataSize);
1A(d)&&(d=await d),g(d);const f=W(d,n.dataSize);for(;;){if(a===n.lacingValues.length){o.push(f.subarray(i,s));break}const p=n.lacingValues[a];if(s+=p,p<255){o.push(f.subarray(i,s));break e}a++}let h=n.headerStartPos+n.totalSize;for(;;){let p=this.reader.requestSliceRange(h,vt,er);if(A(p)&&(p=await p),!p)return null;const m=xr(p);if(!m)return null;if(n=m,n.serialNumber===e.serialNumber)break;h=n.headerStartPos+n.totalSize}i=0,s=0,a=0}const c=o.reduce((d,f)=>d+f.length,0);if(c===0)return null;const l=new Uint8Array(c);let u=0;for(let d=0;d<o.length;d++){const f=o[d];l.set(f,u),u+=f.length}return{data:l,endPage:n,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let i=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let n=this.reader.requestSliceRange(i,vt,er);if(A(n)&&(n=await n),!n)return null;const s=xr(n);if(!s)return null;if(s.serialNumber===e.endPage.serialNumber)return{startPage:s,startSegmentIndex:0};i=s.headerStartPos+s.totalSize}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.trackBackings.map(t=>t.getDecoderConfig().then(i=>i?.codec??null)));return Rl({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class Dl{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new or,this.internalSampleRate=e.codecInfo.codec==="opus"?Ti:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(t=>t.bitstream===this.bitstream);return g(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}
1async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return g(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 ye}getDisposition(){return{...ft,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(g(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:n,vorbisBlockSize:s}=Fl(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new Z(i.metadataOnly?ve:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,n/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:n,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:s}),a}async getFirstPacket(e){g(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;this.bitstream.codecInfo.codec==="opus"&&(g(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);const n=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(n,{timestampInSamples:i,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");const n=await this.demuxer.findNextPacketStart(i.packet);if(!n)return null;const s=i.timestampInSamples+i.durationInSamples,a=await this.demuxer.readPacket(n.startPage,n.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:s,vorbisLastBlocksize:i.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);const i=Er(e*this.internalSampleRate);if(i===0)return this.getFirstPacket(t);if(i<0)return null;g(this.bitstream.lastMetadataPacket);const n=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!n)return null;let s=n.startPage,a=this.demuxer.reader.fileSize;const o=[s];e:for(;s.headerStartPos+s.totalSize<a;){const k=s.headerStartPos,b=Math.floor((k+a)/2);let S=b;for(;;){const T=Math.min(S+Ml,a-vt);let P=this.demuxer.reader.requestSlice(S,T-S);if(A(P)&&(P=await P),g(P),!zl(P,T)){a=b+vt;continue e}let C=this.demuxer.reader.requestSliceRange(P.filePos,vt,er);A(C)&&(C=await C),g(C);const x=xr(C);g(x);let E=!1;if(x.serialNumber===this.bitstream.serialNumber)E=!0;else{let v=this.demuxer.reader.requestSlice(x.headerStartPos,x.totalSize);A(v)&&(v=await v),g(v);const R=W(v,x.totalSize);E=Bl(R)===x.checksum}if(!E){S=x.headerStartPos+4;continue}if(E&&x.serialNumber!==this.bitstream.serialNumber){S=x.headerStartPos+x.totalSize;continue}if(x.granulePosition===-1){S=x.headerStartPos+x.totalSize;continue}this.granulePositionToTimestampInSamples(x.granulePosition)>i?a=x.headerStartPos:(s=x,o.push(x));continue e}}let c=n.startPage;for(const k of o){if(k.granulePosition===s.granulePosition)break;(!c||k.headerStartPos>c.headerStartPos)&&(c=k)}let l=c;const u=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===s.granulePosition);){const k=l.headerStartPos+l.totalSize;let b=this.demuxer.reader.requestSliceRange(k,vt,er);A(b)&&(b=await b),g(b);const S=xr(b);g(S),l=S,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}g(l.granulePosition!==-1);let d=null,f,h,p=l,m=0;if(l.headerStartPos===n.startPage.headerStartPos)f=this.granulePositionToTimestampInSamples(0),h=!0,d=0;else{f=0,h=!1;for(let S=l.lacingValues.length-1;S>=0;S--)if(l.lacingValues[S]<255){d=S+1;break}if(d===null)throw new Error("Invalid page with granule position: no packets end on this page.");m=d-1;const k={data:ve,endPage:p,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(k)){const S=Ts(u,l,d);g(S);const T=bs(u,S.page,S.segmentIndex);T&&(l=T.page,d=T.segmentIndex)}else for(;;){const S=Ts(u,l,d);if(!S)break;const T=bs(u,S.page,S.segmentIndex);if(!T)break;if(l=T.page,d=T.segmentIndex,S.page.headerStartPos!==p.headerStartPos){p=S.page,m=S.segmentIndex;break}}}let y=null,w=null;for(;l!==null;){g(d!==null);const k=await this.demuxer.readPacket(l,d);if(!k)break;if(!(l.headerStartPos===n.startPage.headerStartPos&&d<n.startSegmentIndex)){let T=this.createEncodedPacketFromOggPacket(k,{timestampInSamples:f,vorbisLastBlocksize:w?.vorbisBlockSize??null},t);g(T);let P=this.encodedPacketToMetadata.get(T);if(g(P),!h&&k.endPage.headerStartPos===p.headerStartPos&&k.endSegmentIndex===m?(f=this.granulePositionToTimestampInSamples(l.granulePosition),h=!0,T=this.createEncodedPacketFromOggPacket(k,{timestampInSamples:f-P.durationInSamples,vorbisLastBlocksize:w?.vorbisBlockSize??null},t),g(T),P=this.encodedPacketToMetadata.get(T),g(P)):f+=P.durationInSamples,y=T,w=P,h&&(Math.max(f,0)>i||Math.max(P.timestampInSamples,0)===i))break}const S=await this.demuxer.findNextPacketStart(k);if(!S)break;l=S.startPage,d=S.startSegmentIndex}return y}async getPacketSequential(e,t){const i=await this.sequentialScanMutex.acquire();try{const n=Er(e*this.internalSampleRate);e=n/this.internalSampleRate;const s=X(this.sequentialScanCache,n,c=>c.timestampInSamples);let a;if(s!==-1){const c=this.sequentialScanCache[s];a=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let o=0;for(;a&&a.timestamp<e;){const c=await this.getNextPacket(a,t);if(!c||c.timestamp>e)break;if(a=c,o++,o===100){o=0;const l=this.encodedPacketToMetadata.get(a);g(l),this.sequentialScanCache.length>0&&g(re(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return a}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const bs=(r,e,t)=>{let i=e,n=t;e:for(;;){for(n--,n;n>=0;n--)if(i.lacingValues[n]<255){n++;break e}if(g(n===-1),!(i.headerType&1)){n=0;break}const a=ka(r,o=>o.headerStartPos<i.headerStartPos);if(!a)return null;i=a,n=i.lacingValues.length}if(g(n!==-1),n===i.lacingValues.length){const s=r[r.indexOf(i)+1];g(s),i=s,n=0}return{page:i,segmentIndex:n}},Ts=(r,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};const i=ka(r,n=>n.headerStartPos<e.headerStartPos);return i?{page:i,segmentIndex:i.lacingValues.length-1}:null};var we;(function(r){r[r.PCM=1]="PCM",r[r.IEEE_FLOAT=3]="IEEE_FLOAT",r[r.ALAW=6]="ALAW",r[r.MULAW=7]="MULAW",r[r.EXTENSIBLE=65534]="EXTENSIBLE"})(we||(we={}));class Nl extends ht{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);A(e)&&(e=await e),g(e);const t=ne(e,4),i=t!=="RIFX",n=t==="RF64",s=bt(e,i);let a=n?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(ne(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,u=e.filePos;for(;a===null||u<a;){let f=this.reader.requestSlice(u,8);if(A(f)&&(f=await f),!f)break;const h=ne(f,4),p=bt(f,i),m=f.filePos;if(n&&c===0&&h!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(h==="fmt ")await this.parseFmtChunk(m,p,i);else if(h==="data"){if(l??=p,this.dataStart=f.filePos,this.dataSize=Math.min(l,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(h==="ds64"){let y=this.reader.requestSlice(m,p);if(A(y)&&(y=await y),!y)break;const w=sa(y,i);l=sa(y,i),a=Math.min(w+8,this.reader.fileSize??1/0)}else h==="LIST"?await this.parseListChunk(m,p,i):(h==="ID3 "||h==="id3 ")&&await this.parseId3Chunk(m,p);u=m+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');const d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.trackBackings.push(new Ul(this))})()}async parseFmtChunk(e,t,i){let n=this.reader.requestSlice(e,t);if(A(n)&&(n=await n),!n)return;let s=pr(n,i);const a=pr(n,i),o=bt(n,i);n.skip(4);const c=pr(n,i);let l;if(t===14?l=8:l=pr(n,i),t>=18&&s!==357){const u=pr(n,i),d=t-18;if(Math.min(d,u)>=22&&s===we.EXTENSIBLE){n.skip(6);const h=W(n,16);s=h[0]|h[1]<<8}}if((s===we.MULAW||s===we.ALAW)&&(l=8),s!==we.PCM&&s!==we.IEEE_FLOAT&&s!==we.ALAW&&s!==we.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${s}). Only integer/float PCM, A-law, and μ-law are supported.`);if(s===we.PCM&&![8,16,24,32].includes(l))throw new Error(`Unsupported WAVE PCM bit depth (${l}). Only 8, 16, 24, and 32 bits are supported.`);if(s===we.IEEE_FLOAT&&![32,64].includes(l))throw new Error(`Unsupported WAVE float bit depth (${l}). Only 32 and 64 bits are supported.`);this.audioInfo={format:s,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}
1}async parseListChunk(e,t,i){let n=this.reader.requestSlice(e,t);if(A(n)&&(n=await n),!n)return;const s=ne(n,4);if(s!=="INFO"&&s!=="INF0")return;let a=n.filePos;for(;a<=e+t-8;){n.filePos=a;const o=ne(n,4),c=bt(n,i),l=W(n,c);let u=0;for(let f=0;f<l.length&&l[f]!==0;f++)u++;const d=String.fromCharCode(...l.subarray(0,u));switch(this.metadataTags.raw??={},this.metadataTags.raw[o]=d,o){case"INAM":case"TITL":this.metadataTags.title??=d;break;case"TIT3":this.metadataTags.description??=d;break;case"IART":this.metadataTags.artist??=d;break;case"IPRD":this.metadataTags.album??=d;break;case"IPRT":case"ITRK":case"TRCK":{const f=d.split("/"),h=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(h)&&h>0&&(this.metadataTags.trackNumber??=h),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{const f=new Date(d);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"YEAR":{const f=Number.parseInt(d,10);Number.isInteger(f)&&f>0&&(this.metadataTags.date??=new Date(f,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=d;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=d;break}a+=8+c+(c&1)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(A(i)&&(i=await i),!i)return;const n=dt(i);if(n){const s=t-Me;if(n.size=Math.min(n.size,s),n.size>0){const a=i.slice(e+Me,n.size);Ci(a,n,this.metadataTags)}}}getCodec(){if(g(this.audioInfo),this.audioInfo.format===we.MULAW)return"ulaw";if(this.audioInfo.format===we.ALAW)return"alaw";if(this.audioInfo.format===we.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}if(this.audioInfo.format===we.IEEE_FLOAT){if(this.audioInfo.sampleSizeInBytes===4)return"pcm-f32";if(this.audioInfo.sampleSizeInBytes===8)return"pcm-f64"}g(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const Ut=2048;class Ul{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(g(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return g(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}
1async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return ye}getDisposition(){return{...ft}}async getPacketAtIndex(e,t){g(e>=0),g(this.demuxer.audioInfo);const i=e*Ut*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const n=Math.min(Ut*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-i);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,n);if(A(c)&&(c=await c),!c)return null}let s;if(t.metadataOnly)s=ve;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,n);A(c)&&(c=await c),g(c),s=W(c,n)}const a=e*Ut/this.demuxer.audioInfo.sampleRate,o=n/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new Z(s,"key",a,o,e,n)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){g(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Ut,(this.demuxer.dataSize-1)/(Ut*this.demuxer.audioInfo.blockSizeInBytes)));if(i<0)return null;const n=await this.getPacketAtIndex(i,t);if(n)return n;if(i===0)return null;g(this.demuxer.reader.fileSize===null);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;s;){const a=await this.getNextPacket(s,t);if(!a)break;s=a}return s}getNextPacket(e,t){g(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Ut);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const oi=7,Mt=9,Dt=r=>{const e=r.filePos,t=W(r,9),i=new G(t);if(i.readBits(12)!==4095||(i.skipBits(1),i.readBits(2)!==0))return null;const a=i.readBits(1),o=i.readBits(2)+1,c=i.readBits(4);if(c===15)return null;i.skipBits(1);const l=i.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const u=i.readBits(13);i.skipBits(11);const d=i.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let f=null;return a===1?r.filePos-=2:f=i.readBits(16),{objectType:o,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:u,numberOfAacFrames:d,crcCheck:f,startPos:e}};const ci=1024;class Wl extends ht{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new or,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();g(this.firstFrameHeader),this.trackBackings=[new Vl(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,Me);if(A(a)&&(a=await a),!a){this.lastSampleLoaded=!0;return}const o=dt(a);if(!o)break;this.lastLoadedPos=a.filePos+o.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,oi,Mt);if(A(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}const t=Dt(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);const i=Ot[t.samplingFrequencyIndex];g(i!==void 0);const n=ci/i,s={timestamp:this.nextTimestampInSamples/i,duration:n,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=ci,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0;for(;;){let i=this.reader.requestSlice(t,Me);if(A(i)&&(i=await i),!i)break;const n=dt(i);if(!n)break;let s=this.reader.requestSlice(i.filePos,n.size);if(A(s)&&(s=await s),!s)break;Ci(s,n,this.metadataTags),t=i.filePos+n.size}return this.metadataTags}finally{e()}}}class Vl{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}
1getTimeResolution(){return this.getSampleRate()/ci}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return ye}getCodec(){return"aac"}getInternalCodecId(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){g(this.demuxer.firstFrameHeader);const e=Dr[this.demuxer.firstFrameHeader.channelConfiguration];return g(e!==void 0),e}getSampleRate(){g(this.demuxer.firstFrameHeader);const e=Ot[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return g(e!==void 0),e}getDisposition(){return{...ft}}async getDecoderConfig(){return g(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(e===-1)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let n;if(t.metadataOnly)n=ve;else{let s=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(A(s)&&(s=await s),!s)return null;n=W(s,i.dataSize)}return new Z(n,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const n=Mr(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(n===-1)throw new Error("Packet was not created from this track.");const s=n+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const n=X(this.demuxer.loadedSamples,e,s=>s.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(n,t);if(n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Ll=r=>r===0?null:r===1?192:r>=2&&r<=5?144*2**r:r===6?"uncommon-u8":r===7?"uncommon-u16":r>=8&&r<=15?2**r:null,Hl=(r,e)=>{switch(r){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},ql=r=>{let e=0;const t=new G(W(r,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);const i=[],n=e-1,s=new G(W(r,n)),a=8-e-1;for(let c=0;c<a;c++)i.unshift(t.readBits(1));for(let c=0;c<n;c++)for(let l=0;l<8;l++){const u=s.readBits(1);l<2||i.unshift(u)}return i.reduce((c,l,u)=>c|l<<u,0)},jl=(r,e)=>{if(e==="uncommon-u16")return ae(r)+1;if(e==="uncommon-u8")return U(r)+1;if(typeof e=="number")return e;Fe(e),g(!1)},$l=(r,e)=>e==="uncommon-u16"?ae(r):e==="uncommon-u16-10"?ae(r)*10:e==="uncommon-u8"?U(r):typeof e=="number"?e:null,Kl=r=>{let t=0;for(const i of r){t^=i;for(let n=0;n<8;n++)(t&128)!==0?t=t<<1^7:t<<=1,t&=255}return t};class Gl extends ht{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new or,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),g(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSlice(e,Me);if(A(t)&&(t=await t),!t){this.lastSampleLoaded=!0;return}const i=dt(t);if(!i)break;let n=this.reader.requestSlice(t.filePos,i.size);A(n)&&(n=await n),g(n),Ci(n,i,this.metadataTags),e=t.filePos+i.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);
1if(A(t)&&(t=await t),e+=4,t===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);g(t);const i=U(t),n=Ze(t),s=(i&128)!==0;switch(i&127){case Zt.STREAMINFO:{let o=this.reader.requestSlice(e,n);if(A(o)&&(o=await o),g(o),o===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);const c=W(o,34),l=new G(c),u=l.readBits(16),d=l.readBits(16),f=l.readBits(24),h=l.readBits(24),p=l.readBits(20),m=l.readBits(3)+1;l.readBits(5);const y=l.readBits(36);l.skipBits(128);const w=new Uint8Array(42);w.set(new Uint8Array([102,76,97,67]),0),w.set(new Uint8Array([128,0,0,34]),4),w.set(c,8),this.audioInfo={numberOfChannels:m,sampleRate:p,totalSamples:y,minimumBlockSize:u,maximumBlockSize:d,minimumFrameSize:f,maximumFrameSize:h,description:w},this.trackBacking=new Xl(this);break}case Zt.VORBIS_COMMENT:{let o=this.reader.requestSlice(e,n);A(o)&&(o=await o),g(o),fn(W(o,n),this.metadataTags);break}case Zt.PICTURE:{let o=this.reader.requestSlice(e,n);A(o)&&(o=await o),g(o);const c=M(o),l=M(o),u=xe.decode(W(o,l)),d=M(o),f=xe.decode(W(o,d));o.skip(16);const h=M(o),p=W(o,h);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:u,kind:c===3?"coverFront":c===4?"coverBack":"unknown",description:f});break}}if(e+=n,s){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){g(this.audioInfo);const i=6,n=16,s=10,a=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+n+2,o=this.audioInfo.minimumFrameSize||s,l=(this.audioInfo.maximumFrameSize||a)+n,u=await this.reader.requestSliceRange(e,n,l);if(!u)return null;const d=this.readFlacFrameHeader({slice:u,isFirstPacket:t});if(!d)return null;for(u.filePos=e+o;;){if(u.filePos>u.end-i)return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:u.end-e,isLastFrame:!0};if(U(u)===255){const h=u.filePos,p=U(u),m=this.blockingBit===1?249:248;if(p!==m){u.filePos=h;continue}u.skip(-2);const y=u.filePos-e,w=this.readFlacFrameHeader({slice:u,isFirstPacket:!1});if(!w){u.filePos=h;continue}if(this.blockingBit===0){if(w.num-d.num!==1){u.filePos=h;continue}}else if(w.num-d.num!==d.blockSize){u.filePos=h;continue}return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:y,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const i=e.filePos,n=W(e,4),s=new G(n);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){g(t);const y=s.readBits(1);this.blockingBit=y}else if(this.blockingBit===1){if(g(!t),s.readBits(1)!==1)return null}else if(this.blockingBit===0){if(g(!t),s.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");const o=Ll(s.readBits(4));if(!o)return null;g(this.audioInfo);const c=Hl(s.readBits(4),this.audioInfo.sampleRate);if(!c||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;const u=ql(e),d=jl(e,o),f=$l(e,c);if(f===null||f!==this.audioInfo.sampleRate)return null;const h=e.filePos-i,p=U(e);e.skip(-h),e.skip(-1);const m=Kl(W(e,h));return p!==m?null:{num:u,blockSize:d,sampleRate:f}}async advanceReader(){await this.readMetadata(),g(this.lastLoadedPos!==null),g(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}const i=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(s),t.isLastFrame){this.lastSampleLoaded=!0;return}}}class Xl{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return ye}getTimeResolution(){return g(this.demuxer.audioInfo),this.demuxer.audio
1Info.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...ft}}async getDecoderConfig(){return g(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(g(this.demuxer.audioInfo),e<0)return null;const i=await this.demuxer.readingMutex.acquire();try{for(;;){const n=X(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(n===-1){await this.demuxer.advanceReader();continue}const s=this.demuxer.loadedSamples[n],a=s.blockOffset/this.demuxer.audioInfo.sampleRate,o=s.blockSize/this.demuxer.audioInfo.sampleRate;if(a+o<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(n,t)}}finally{i()}}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const n=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&n>=this.demuxer.loadedSamples.length)return null;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const i=this.demuxer.loadedSamples[e];if(!i)return null;let n;if(t.metadataOnly)n=ve;else{let o=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(A(o)&&(o=await o),!o)return null;n=W(o,i.byteSize)}g(this.demuxer.audioInfo);const s=i.blockOffset/this.demuxer.audioInfo.sampleRate,a=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Z(n,"key",s,a,e,i.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}const $e=9e4,Ie=188,Ql=r=>{let e="video/MP2T";const t=[...new Set(r.filter(Boolean))];return t.length>0&&(e+=`; codecs="${t.join(", ")}"`),e};const mo="PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.",Ss=5,Yl=1212435798,Zl=1212436562,Jl=1146376960,eu=new Set([133,134,162]),xs=new Set;class tu extends ht{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{const e=Ie+16+1;let t=this.reader.requestSlice(0,e);A(t)&&(t=await t),g(t);const i=W(t,e);if(i[0]===71&&i[Ie]===71)this.packetOffset=0,this.packetStride=Ie;else if(i[0]===71&&i[Ie+16]===71)this.packetOffset=0,this.packetStride=Ie+16;else if(i[4]===71&&i[4+Ie+4]===71)this.packetOffset=4,this.packetStride=Ie+4;else throw new Error("Unreachable.");const n=256;this.minReferencePointByteDistance=n*this.packetStride;let s=this.packetOffset,a=null,o=!1,c=!1;for(;;){const l=await this.readPacketHeader(s);if(!l)break;if(l.payloadUnitStartIndicator===0){s+=this.packetStride;continue}if(c&&!this.elementaryStreams.some(m=>m.pid===l.pid)){s+=this.packetStride;continue}const u=await this.readSection(s,!0,!c);if(!u)break;const d=3,f=32;let h=!1;if(!c&&u.pid!==0&&!(u.payload[0]===0&&u.payload[1]===0&&u.payload[2]===1)){const y=new G(u.payload),w=y.readAlignedByte();y.skipBits(8*w),h=y.readBits(8)===2}if(u.pid===0&&!o){const m=new G(u.payload),y=m.readAlignedByte();m.skipBits(8*y),m.skipBits(14);const w=m.readBits(10);for(m.skipBits(40);8*(w+d)-m.pos>f;){const k=m.readBits(16);m.skipBits(3);const b=m.readBits(13);if(k!==0){if(a!==null)throw new Error("Only files with a single program are supported.");a=b}}if(a===null)throw new Error("Program Association Table must link to a Program Map Table.");o=!0}else if((u.pid===a||h)&&!c){const m=new G(u.payload),y=m.readAlignedByte();m.skipBits(8*y),m.skipBits(12);const w=m.readBits(12);m.skipBits(43),m.readBits(13),m.skipBits(6);const k=m.readBits(10),b=m.pos+8*k;let S=!1;for(;m.pos<b;){const T=m.readBits(8),P=m.readBits(8),I=m.pos+8*P;if(T===Ss&&P>=4){const C=m.readBits(32);S||=C===Yl||C===Zl}m.pos=I}for(m.pos=b;8*(w+d)-m.pos>f;){const T=m.readBits(8);m.skipBits(3);const P=m.readBits(13);m.skipBits(6);const I=m.readBits(10),C=m.pos+8*I;let x=!1,E=!1,_=!1;for(;m.pos<C;){const O=m.readBits(8),N=m.readBits(8),D=m.pos+8*N;if(O===106)x=!0;else if(O===122||O===204)E=!0;else if(O===123)_=!0;else if(O===Ss&&N>=4){const $=m.readBits(32);_||=($&4294967040)===Jl}m.pos=D}let v=null;const R=S&&eu.has(T)?130:T;switch(R){case 27:case 36:v={type:"video",codec:T===27?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:case 130:case 138:{let O;R===3||R===4?O="mp3":R===15?O="aac":R===129?O="ac3":R===135?O="eac3":O="dts",v={type:"audio",codec:O,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:E?v={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:x?v={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:_&&(v={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:xs.has(T)||(H._warn(`Note: MPEG-TS streams with stream_type 0x${T.toString(16)} are not currently supported.`),xs.add(T))}v&&this.elementaryStreams.push({demuxer:this,pid:P,streamType:T,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:v,referencePesPackets:[]})}c=!0}else{const m=this.elementaryStreams.find(y=>y.pid===u.pid);e:if(m&&!m.initialized){const y=Kt(u,!0);if(!y)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${m.pid}`);if(m.firstSection=u,m.canBeTrustedWithKeyPackets=u.randomAccessIndicator===1,this.input._initInput){const b=(await this.input._initInput._getDemuxer()).elementaryStreams.find(S=>S.pid===u.pid&&S.info.codec===m.info.codec);
1if(b){m.info=b.info,m.initialized=!0;break e}}const w=new br(m,y);if(m.info.type==="video"){for(;;){const k=w;if(k.suppliedPacket=null,await w.markNextPacket(),m.info.codec==="avc"){if(!w.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(m.info.avcCodecInfo=yi(w.suppliedPacket.data),!m.info.avcCodecInfo)continue;const b=m.info.avcCodecInfo.sequenceParameterSets[0];g(b);const S=wi(b);m.info.width=S.displayWidth,m.info.height=S.displayHeight;const T=S.pixelAspectRatio.num,P=S.pixelAspectRatio.den;T>0&&P>0&&(T>P?(m.info.squarePixelWidth=Math.round(m.info.width*T/P),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*P/T))),m.info.colorSpace={primaries:rt[S.colourPrimaries],transfer:it[S.transferCharacteristics],matrix:nt[S.matrixCoefficients],fullRange:!!S.fullRangeFlag},m.info.reorderSize=S.maxDecFrameBuffering;break}else if(m.info.codec==="hevc"){if(!w.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(m.info.hevcCodecInfo=ki(w.suppliedPacket.data),!m.info.hevcCodecInfo)continue;const S=m.info.hevcCodecInfo.arrays.find(P=>P.nalUnitType===ce.SPS_NUT).nalUnits[0];g(S);const T=Mn(S);m.info.width=T.displayWidth,m.info.height=T.displayHeight,T.pixelAspectRatio.num>T.pixelAspectRatio.den?(m.info.squarePixelWidth=Math.round(m.info.width*T.pixelAspectRatio.num/T.pixelAspectRatio.den),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*T.pixelAspectRatio.den/T.pixelAspectRatio.num)),m.info.colorSpace={primaries:rt[T.colourPrimaries],transfer:it[T.transferCharacteristics],matrix:nt[T.matrixCoefficients],fullRange:!!T.fullRangeFlag},m.info.reorderSize=T.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}m.info.decoderConfig={codec:Un({width:m.info.width,height:m.info.height,codec:m.info.codec,codecDescription:null,colorSpace:m.info.colorSpace,avcType:1,avcCodecInfo:m.info.avcCodecInfo,hevcCodecInfo:m.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:m.info.width,codedHeight:m.info.height,colorSpace:m.info.colorSpace},(m.info.width!==m.info.squarePixelWidth||m.info.height!==m.info.squarePixelHeight)&&(m.info.decoderConfig.displayAspectWidth=m.info.squarePixelWidth,m.info.decoderConfig.displayAspectHeight=m.info.squarePixelHeight),m.initialized=!0}else{if(await w.markNextPacket(),!w.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${m.pid}`);if(m.info.codec==="aac"){const k=Ee.tempFromBytes(w.suppliedPacket.data),b=Dt(k);if(!b)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");m.info.aacCodecInfo={isMpeg2:!1,objectType:b.objectType},m.info.numberOfChannels=Dr[b.channelConfiguration],m.info.sampleRate=Ot[b.samplingFrequencyIndex]}else if(m.info.codec==="mp3"){const k=M(Ee.tempFromBytes(w.suppliedPacket.data)),b=Vn(k,w.suppliedPacket.data.byteLength);if(!b.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");m.info.numberOfChannels=Br(b.header.channel),m.info.sampleRate=b.header.sampleRate}else if(m.info.codec==="ac3"){const k=Oa(w.suppliedPacket.data);if(!k)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(k.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=On[k.acmod]+k.lfeon,m.info.sampleRate=mi[k.fscod]}else if(m.info.codec==="eac3"){const k=Na(w.suppliedPacket.data);if(!k)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const b=Ua(k);if(b===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=Wa(k),m.info.sampleRate=b}else if(m.info.codec==="dts"){const k=Nn(w.suppliedPacket.data);if(!k)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");m.info.numberOfChannels=k.numberOfChannels,m.info.sampleRate=k.sampleRate,k.core&&(m.info.dtsFormat=k.hasExtensions?"dtsh":"dtsc")}else throw new Error("Unhandled.");m.info.decoderConfig={codec:Wn({codec:m.info.codec,codecDescription:null,aacCodecInfo:m.info.aacCodecInfo,dtsFormat:m.info.dtsFormat}),numberOfChannels:m.info.numberOfChannels,sampleRate:m.info.sampleRate},m.initialized=!0}}}if(c&&this.elementaryStreams.every(m=>m.initialized))break;s+=this.packetStride}if(!c)throw o?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(const l of this.elementaryStreams)l.initialized&&(l.info.type==="video"?this.trackBackingEntries.push(new ru(l)):this.trackBackingEntries.push(new iu(l)))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.trackBackingEntries.map(t=>t.getDecoderConfig().then(i=>i?.codec??null)));return Ql(e)}async readSection(e,t,i=!1){let n=e,s=e;const a=[];let o=0,c=null,l=!0,u=0;for(;;){const f=await this.readPacket(s);if(s+=this.packetStride,!f)break;
1if(c){if(f.pid!==c.pid){if(i)break;continue}if(f.payloadUnitStartIndicator===1)break}else{if(f.payloadUnitStartIndicator===0)break;c=f}const h=!!(f.adaptationFieldControl&2),p=!!(f.adaptationFieldControl&1);let m=0;if(h&&(m=1+f.body[0],f===c&&m>1&&(u=f.body[1]>>6&1)),p&&(m===0?(a.push(f.body),o+=f.body.byteLength):(a.push(f.body.subarray(m)),o+=f.body.byteLength-m)),n=s,!t&&o>=64){l=!1;break}if(Mr(this.sectionEndPositions,n,w=>w)!==-1){l=!1;break}}if(l){const f=X(this.sectionEndPositions,n,h=>h);this.sectionEndPositions.splice(f+1,0,n)}if(!c)return null;let d;if(a.length===1)d=a[0];else{const f=a.reduce((p,m)=>p+m.length,0);d=new Uint8Array(f);let h=0;for(const p of a)d.set(p,h),h+=p.length}return{startPos:e,endPos:t?n:null,pid:c.pid,payload:d,randomAccessIndicator:u}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(A(t)&&(t=await t),!t)return null;if(U(t)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const n=ae(t),s=n>>14&1,a=n&8191,c=U(t)>>4&3;return{payloadUnitStartIndicator:s,pid:a,adaptationFieldControl:c}}async readPacket(e){let t=this.reader.requestSlice(e,Ie);if(A(t)&&(t=await t),!t)return null;const i=W(t,Ie);if(i[0]!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const s=(i[1]<<8)+i[2],a=s>>14&1,o=s&8191,l=i[3]>>4&3;return{payloadUnitStartIndicator:a,pid:o,adaptationFieldControl:l,body:i.subarray(4)}}}const Ct=(r,e)=>{if(r.payload.byteLength<3)return null;const t=new G(r.payload);if(t.readBits(24)!==1)return null;const n=t.readBits(8);if(t.skipBits(16),n===188||n===190||n===191||n===240||n===241||n===255||n===242||n===248)return null;t.skipBits(8);const s=t.readBits(2);t.skipBits(14);let a=null;if(s===2||s===3)a=0,t.skipBits(4),a+=t.readBits(3)*(1<<30),t.skipBits(1),a+=t.readBits(15)*32768,t.skipBits(1),a+=t.readBits(15);else if(e)throw new Error(mo);return{sectionStartPos:r.startPos,sectionEndPos:r.endPos,pts:a,randomAccessIndicator:r.randomAccessIndicator}},Kt=(r,e)=>{g(r.endPos!==null);const t=Ct(r,e);if(!t)return null;const i=new G(r.payload);i.skipBits(32);const n=i.readBits(16),s=6;i.skipBits(16);const a=i.readBits(8),o=i.pos+8*a;i.pos=o;const c=o/8;g(Number.isInteger(c));const l=r.payload.subarray(c,n>0?s+n:r.payload.byteLength);return{...t,data:l}};class Si{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){const e=this.elementaryStream.demuxer,t=this.elementaryStream.info.type;let i=0;for(const n of e.trackBackingEntries)if(n.getType()===t&&i++,g(n instanceof Si),n.elementaryStream===this.elementaryStream)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return ye}getDisposition(){return{...ft,primary:!1}}getTimeResolution(){return $e}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}
1async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,i){let n;return this.allPacketsAreKeyPackets()?n="key":n=e.randomAccessIndicator===1?"key":"delta",new Z(i.metadataOnly?ve:e.data,n,e.pts/$e,Math.max(t/$e,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;g(t);const i=Kt(t,!0);g(i);const n=new br(this.elementaryStream,i),s=new Vi(this,n),a=await s.readNext();if(!a)return null;const o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,s),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,t){let i=this.packetBuffers.get(e);if(i){const u=await i.readNext();if(!u)return null;this.packetBuffers.delete(e);const d=this.createEncodedPacket(u.packet,u.duration,t);return this.packetBuffers.set(d,i),this.packetSectionStarts.set(d,u.packet.sectionStartPos),d}const n=this.packetSectionStarts.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");const a=await this.elementaryStream.demuxer.readSection(n,!0);g(a);const o=Kt(a,!0);g(o);const c=new br(this.elementaryStream,o);i=new Vi(this,c);const l=e.sequenceNumber;for(;;){const u=await i.readNext();if(!u)return null;if(u.packet.sequenceNumber>l){const d=this.createEncodedPacket(u.packet,u.duration,t);return this.packetBuffers.set(d,i),this.packetSectionStarts.set(d,u.packet.sectionStartPos),d}}}async getNextKeyPacket(e,t){let i=e;for(;;){if(i=await this.getNextPacket(i,t),!i)return null;if(i.type==="key")return i}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,i){const n=Er(e*$e),s=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=s,c=this.elementaryStream.pid,l=async(S,T,P)=>{let I=S;for(;I<T;){const C=await s.readPacketHeader(I);if(!C)return null;if(C.pid===c&&C.payloadUnitStartIndicator===1){const x=await s.readSection(I,P);if(!x)return null;const E=Ct(x,!1);if(E&&E.pts!==null)return{pesPacketHeader:E,section:x}}I+=s.packetStride}return null},u=this.elementaryStream.firstSection;g(u);const d=Ct(u,!0);if(g(d),n<d.pts)return null;let f;const h=this.elementaryStream.referencePesPackets,p=X(h,n,S=>S.pts),m=p!==-1?h[p]:null;if(m&&n-m.pts<$e/2)f=m.sectionStartPos;else{let S=0;if(a.fileSize!==null){const T=Math.ceil(a.fileSize/o);if(T>1){let P=0,I=T-1;for(S=P;P<=I;){const C=Math.floor((P+I)/2),x=_i(C*o,s.packetStride)+d.sectionStartPos,E=x+o,_=await l(x,E,!1);if(!_){I=C-1;continue}_.pesPacketHeader.pts<=n?(S=C,P=C+1):I=C-1}}}f=_i(S*o,s.packetStride)+d.sectionStartPos}let w=(await l(f,a.fileSize??1/0,!1))?.pesPacketHeader??null;w||(w=d);const k=this.getReorderSize(),b=async(S,T)=>{const P=await s.readSection(S,!0);g(P);const I=Kt(P,!0);g(I);const C=new br(this.elementaryStream,I),x=new Vi(this,C);for(;!((re(x.presentationOrderPackets)?.pts??-1/0)>=n||!await x.readNextPacket()););const E=_n(x.presentationOrderPackets,T);if(E===-1)return null;const _=x.presentationOrderPackets[E],v=E===0?0:_.pts-x.presentationOrderPackets[E-1].pts;for(;x.decodeOrderPackets[0]!==_;)x.decodeOrderPackets.shift();x.lastDuration=v;const R=await x.readNext();g(R);const O=this.createEncodedPacket(R.packet,R.duration,i);return this.packetBuffers.set(O,x),this.packetSectionStarts.set(O,R.packet.sectionStartPos),O};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let S=w.sectionStartPos+s.packetStride;for(;;){const T=await s.readPacketHeader(S);if(!T)break e;if(T.pid===c&&T.payloadUnitStartIndicator===1){const P=await s.readSection(S,!1);if(P){const I=Ct(P,!1);if(I&&I.pts!==null){if(I.pts>n)break e;w=I,kn(this.elementaryStream,w);break}}}S+=s.packetStride}}e:for(let S=0;S<k+1;S++){let T=w.sectionStartPos-s.packetStride;for(;T>=s.packetOffset;){const P=await s.readPacketHeader(T);if(!P)break e;if(P.pid===c&&P.payloadUnitStartIndicator===1){const I=await s.readSection(T,!1);if(I){const C=Ct(I,!1);if(C&&C.pts!==null){w=C;break}}}T-=s.packetStride}}return b(w.sectionStartPos,S=>S.pts<=n)}else{let S=f,T=null;const P=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let I=null;const C=S<=d.sectionStartPos;let x,E=null;if(C)x=d,E=u;else{const R=await l(S,a.fileSize??1/0,P);x=R?.pesPacketHeader??null,E=R?.section??null}let _=!1,v=0;e:for(;x&&!(T!==null&&x.sectionStartPos>=T);){if(x.pts<=n){let O;if(this.elementaryStream.canBeTrustedWithKeyPackets)O=x.randomAccessIndicator===1;else{g(E);const N=Kt(E,!0);g(N);const D=new br(this.elementaryStream,N);await D.markNextPacket(),O=D.suppliedPacket?.randomAccessIndicator===1}O&&(I=x)}if(x.pts>n&&(_=!0),_&&(v++,v>k))break;let R=x.sectionStartPos+s.packetStride;for(;;){const O=await s.readPacketHeader(R);if(!O)break e;if(O.pid===c&&O.payloadUnitStartIndicator===1){const N=await s.readSection(R,P);if(N){const D=Ct(N,!1);if(D&&D.pts!==null){x=D,E=N,kn(this.elementaryStream,x);break}}}R+=s.packetStride}}if(I){let R=I;if(v===0)e:for(let N=0;N<k;N++){let D=R.sectionStartPos-s.packetStride;for(;D>=s.packetOffset;
1){const $=await s.readPacketHeader(D);if(!$)break e;if($.pid===c&&$.payloadUnitStartIndicator===1){const J=await s.readSection(D,P);if(J){const ue=Ct(J,!1);if(ue&&ue.pts!==null){R=ue;break}}}D-=s.packetStride}}const O=await b(R.sectionStartPos,N=>N.pts<=n&&N.randomAccessIndicator===1);return g(O),O}if(C)return null;T=S,S=Math.max(_i(S-d.sectionStartPos-o,s.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}}class ru extends Si{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return g(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class iu extends Si{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return g(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const kn=(r,e)=>{const t=r.referencePesPackets,i=X(t,e.sectionStartPos,n=>n.sectionStartPos);if(i>=0){const n=t[i];if(e.pts<=n.pts)return!1;const s=r.demuxer.minReferencePointByteDistance;if(e.sectionStartPos-n.sectionStartPos<s)return!1;if(i<t.length-1){const a=t[i+1];if(a.pts<e.pts||a.sectionStartPos-e.sectionStartPos<s)return!1}}return t.splice(i+1,0,e),!0};class br{constructor(e,t){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=t}ensureBuffered(e){const t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return g(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos<t;){let i;if(this.pesPackets.length===0)i=this.startingPesPacket;else{let n=re(this.pesPackets).sectionEndPos;for(g(n!==null);;){const s=await this.demuxer.readPacketHeader(n);if(!s)return;if(s.pid===this.pid){const a=await this.demuxer.readSection(n,!0);if(!a)return;const o=Kt(a,!1);if(o){i=o;break}}n+=this.demuxer.packetStride}}this.pesPackets.push(i),this.endPos+=i.data.byteLength}}readBytes(e){const t=this.getCurrentPesPacket(),i=this.currentPos-this.currentPesPacketPos,n=i+e;if(this.currentPos+=e,n<=t.data.byteLength)return t.data.subarray(i,n);const s=new Uint8Array(e);s.set(t.data.subarray(i));let a=t.data.byteLength-i;for(;;){this.advanceCurrentPacket();const o=this.getCurrentPesPacket(),c=e-a;if(c<=o.data.byteLength){s.set(o.data.subarray(0,c),a);break}s.set(o.data,a),a+=o.data.byteLength}return s}readU8(){let e=this.getCurrentPesPacket();const t=this.currentPos-this.currentPesPacketPos;return this.currentPos++,t<e.data.byteLength?e.data[t]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;const t=this.getCurrentPesPacket();this.currentPesPacketPos-=t.data.byteLength}else for(;;){const t=this.getCurrentPesPacket(),i=this.currentPesPacketPos+t.data.byteLength;if(e<i)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){g(!this.suppliedPacket);const e=this.elementaryStream;if(e.info.type==="video"){const t=e.info.codec,i=1024;if(t!=="avc"&&t!=="hevc")throw new Error("Unhandled.");const n=t==="avc"?1:2;let s=null,a=!1,o=0;for(;;){let c=this.ensureBuffered(i);if(A(c)&&(c=await c),c===0)break;const l=this.currentPos,u=this.readBytes(c),d=u.byteLength;let f=0;for(;f<d;){const h=u.indexOf(0,f);
1if(h===-1||h>=d)break;f=h;const p=l+f;if(f+3>=d){this.seekTo(p);break}const m=u[f+1],y=u[f+2],w=u[f+3];let k=0;if(m===0&&y===0&&w===1?k=4:m===0&&y===1&&(k=3),k===0){f++;continue}const b=p;s??=b;const S=f+k,T=S+n,P=6;if(T+(t==="avc"?P:1)>d){this.seekTo(p);break}const C=u[S];let x,E,_;if(t==="avc")x=pi(C),E=x===fe.NON_IDR_SLICE||x===fe.SLICE_DPA||x===fe.IDR,_=x===fe.SEI||x===fe.SPS||x===fe.PPS||x===fe.AUD;else{if(x=tr(C),((C&1)<<5|u[S+1]>>3)>0){f+=k;continue}E=x<=ce.RASL_R||x>=ce.BLA_W_LP&&x<=21,_=x>=ce.VPS_NUT&&x<=37||x===ce.PREFIX_SEI_NUT||x>=41&&x<=44||x>=48&&x<=55}let v=!1;if(E){let R;if(t==="avc"){const O=u.subarray(T,T+P),N=z(new G(O));R=!a||N<=o,o=N}else R=u[T]>>7===1;R&&(a?v=!0:a=!0)}else _&&a&&(v=!0);if(v){const R=b-s;return this.seekTo(s),this.supplyPacket(R,0)}f+=k}if(c<i)break}if(s!==null&&this.endPos>s){const c=this.endPos-s;return this.seekTo(s),this.supplyPacket(c,0)}}else{const t=e.info.codec,i=128;for(;;){let n=this.ensureBuffered(i);A(n)&&(n=await n);const s=this.currentPos;for(;this.currentPos-s<n;){const a=this.readU8();if(t==="aac"){if(a!==255)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(Mt);if(A(c)&&(c=await c),c<Mt)return;const l=this.readBytes(Mt),u=Dt(Ee.tempFromBytes(l));if(u){this.seekTo(o);let d=this.ensureBuffered(u.frameLength);return A(d)&&(d=await d),this.supplyPacket(d,Math.round(ci*$e/e.info.sampleRate))}else this.seekTo(o+1)}else if(t==="mp3"){if(a!==255)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(Rt);if(A(c)&&(c=await c),c<Rt)return;const l=this.readBytes(Rt),u=K(l).getUint32(0),d=Vn(u,null);if(d.header){this.seekTo(o);let f=this.ensureBuffered(d.header.totalSize);A(f)&&(f=await f);const h=d.header.audioSamplesInFrame*$e/e.info.sampleRate;return this.supplyPacket(f,Math.round(h))}else this.seekTo(o+1)}else if(t==="ac3"){if(a!==11)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(5);if(A(c)&&(c=await c),c<5)return;const l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}const u=l[4]>>6,d=l[4]&63;if(u===3||d>37){this.seekTo(o+1);continue}const f=Rc[3*d+u];g(f!==void 0),this.seekTo(o),c=this.ensureBuffered(f),A(c)&&(c=await c);const h=Math.round(Mc*$e/e.info.sampleRate);return this.supplyPacket(c,h)}else if(t==="eac3"){if(a!==11)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(5);if(A(c)&&(c=await c),c<5)return;const l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}const d=(((l[2]&7)<<8|l[3])+1)*2,h=l[4]>>6===3?3:l[4]>>4&3,p=Da[h];this.seekTo(o),c=this.ensureBuffered(d),A(c)&&(c=await c);const m=p*256,y=Math.round(m*$e/e.info.sampleRate);return this.supplyPacket(c,y)}else if(t==="dts"){if(a!==127&&a!==100)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(Xr);if(A(c)&&(c=await c),c<Xr)return;const l=this.readBytes(Xr),u=Ha(l);let d=u?null:Qr(l);if(!u&&!d){this.seekTo(o+1);continue}if(d&&!d.asset){this.seekTo(o);const m=Math.min(d.frameSize,Dc);let y=this.ensureBuffered(m);A(y)&&(y=await y),d=Qr(this.readBytes(y))??d}let f=u?u.frameSize:d.frameSize;if(u){let m=Math.ceil(u.frameSize/4)*4;for(;;){this.seekTo(o);const y=m+hn;let w=this.ensureBuffered(y);if(A(w)&&(w=await w),w<y)break;this.seekTo(o+m);const k=Qr(this.readBytes(hn));if(!k)break;m+=k.frameSize,f=m}}const h=u?.sampleCount??d.asset?.sampleCount;if(h===void 0){this.seekTo(o+1);continue}this.seekTo(o),c=this.ensureBuffered(f),A(c)&&(c=await c);const p=Math.round(h*$e/e.info.sampleRate);return this.supplyPacket(c,p)}else throw new Error("Unhandled.")}if(n<i)break}}}supplyPacket(e,t){const i=this.getCurrentPesPacket();let n;if(this.lastSuppliedPesPacket===i)g(this.nextPts!==null),n=this.nextPts;else{if(i.pts===null)throw new Error(mo);n=i.pts,kn(this.elementaryStream,i)}this.lastSuppliedPesPacket=i,this.nextPts=n+t;const s=i.sectionStartPos,a=s+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e);let c=i.randomAccessIndicator;if(c===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")c=1;else if(this.elementaryStream.info.decoderConfig){const l=bi(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)==="key";c=Number(l)}}this.suppliedPacket={pts:n,data:o,sequenceNumber:a,sectionStartPos:s,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}}class Vi{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),g(this.reorderSize>=0)}
1async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);g(t!==-1);let i;for(t===this.presentationOrderPackets.length-1?i=this.lastDuration:(i=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=i),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const n=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(n))break;this.presentationOrderPackets.shift()}return{packet:e,duration:i}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket?e=this.context.suppliedPacket:(await this.context.markNextPacket(),e=this.context.suppliedPacket),this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){const e=this.decodeOrderPackets[0];for(g(e);;){const t=this.presentationOrderPackets.indexOf(e);if(t!==-1&&t<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let t=0;for(let n=1;n<this.reorderBuffer.length;n++)this.reorderBuffer[n].pts<this.reorderBuffer[t].pts&&(t=n);const i=this.reorderBuffer[t];this.presentationOrderPackets.push(i),this.reorderBuffer.splice(t,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const po="application/vnd.apple.mpegurl",Ps="#EXT-X-STREAM-INF:",Cs="#EXT-X-I-FRAME-STREAM-INF:",Is="#EXT-X-MEDIA:",bn="#EXTINF:",Es="#EXT-X-MAP:",_s="#EXT-X-KEY:",vs="#EXT-X-MEDIA-SEQUENCE:",As="#EXT-X-BYTERANGE:",Bs="#EXT-X-PROGRAM-DATE-TIME:",nu="#EXT-X-DISCONTINUITY",Fs="#EXT-X-TARGETDURATION:",su="#EXT-X-ENDLIST",Rs="#EXT-X-PLAYLIST-TYPE:",au="#EXT-X-I-FRAMES-ONLY",go=r=>r.length===0||r.startsWith("#")&&!r.startsWith("#EXT");class Pr{constructor(e){this._attributes={};let t="",i="",n=!1,s=!1;for(let a=0;a<e.length;a++){const o=e[a];o==='"'?s=!s:o==="="&&!n&&!s?n=!0:o===","&&!s?(t&&(this._attributes[t.trim().toLowerCase()]=i),t="",i="",n=!1):n?i+=o:t+=o}t&&(this._attributes[t.trim().toLowerCase()]=i)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){const t=this.get(e);if(t===null)return null;const i=Number(t);return Number.isFinite(i)?i:null}merge(e){Object.assign(this._attributes,e._attributes)}}class ou{constructor(e,t,i){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=new WeakMap,this.firstTimestampCache=new WeakMap,this.input=e,this.path=t,this.trackDeclarations=i}
1async getDurationFromMetadata(e){const t=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return t?t.timestamp+t.duration:null}async getUnixTimeForTimestamp(e){let t=await this.getSegmentAt(e,{});if(t??=await this.getFirstSegment({}),!t||t.unixEpochTimestamp===null)return null;const i=e-t.timestamp;return t.unixEpochTimestamp+i}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if(t.type==="video"){const i=wr(e,n=>n.getType()==="video")+1;e.push(new Ms(this,t,i))}else if(t.type==="audio"){const i=wr(e,n=>n.getType()==="audio")+1;e.push(new zs(this,t,i))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];const i=await this.getInputForSegment(this.firstSegment).getTracks();for(const n of i)if(n.type==="video"){const s=wr(e,a=>a.getType()==="video")+1;e.push(new Ms(this,{id:e.length+1,type:"video"},s))}else if(n.type==="audio"){const s=wr(e,a=>a.getType()==="audio")+1;e.push(new zs(this,{id:e.length+1,type:"audio"},s))}}return e})()}async getFirstTimestampForInput(e){const t=this.firstTimestampCache.get(e);if(t!==void 0)return t;const i=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,i),i}async getMediaOffset(e,t){const i=e.firstSegment??e;let n;if(this.firstSegmentFirstTimestamps.has(i))n=this.firstSegmentFirstTimestamps.get(i);else{const l=this.getInputForSegment(i);n=await this.getFirstTimestampForInput(l),this.firstSegmentFirstTimestamps.set(i,n)}if(i===e)return i.timestamp-n;const s=await this.getFirstTimestampForInput(t),a=e.timestamp-i.timestamp,c=s-n-a;return Math.abs(c)<=Math.min(.25,a)?i.timestamp-n:e.timestamp-s}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class yo{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");let e=this.segmentedInput.firstSegment,t=null;for(;e&&(t=(await this.segmentedInput.getInputForSegment(e).getTracks()).find(s=>s.type===this.decl.type&&s.number===this.number)??null,!t);)e=await this.segmentedInput.getNextSegment(e,{});if(!t)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=t,this.firstSegment=e})()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),g(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}
1getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,i){g(e.sequenceNumber>=0),g(this.segmentedInput.firstSegment);const n=await this.segmentedInput.getMediaOffset(t,i.input),s=t.timestamp-this.segmentedInput.firstSegment.timestamp,a=e.clone({timestamp:ei(e.timestamp+n,await i.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+e.sequenceNumber});return this.packetInfos.set(a,{segment:t,track:i,sourcePacket:e}),a}async getFirstPacket(e){await this.hydrate(),g(this.firstInputTrack),g(this.firstSegment);let t=this.firstInputTrack,i=this.firstSegment;for(;;){if(t){const a=await t._backing.getFirstPacket(e);if(a)return this.createAdjustedPacket(a,i,t)}if(i=await this.segmentedInput.getNextSegment(i,{skipLiveWait:e.skipLiveWait}),!i)break;t=(await this.segmentedInput.getInputForSegment(i).getTracks()).find(a=>a.type===this.firstInputTrack.type&&a.number===this.firstInputTrack.number)??null}return null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,i){const n=this.packetInfos.get(e);if(!n)throw new Error("Packet was not created from this track.");const s=i?await n.track._backing.getNextKeyPacket(n.sourcePacket,t):await n.track._backing.getNextPacket(n.sourcePacket,t);if(s)return this.createAdjustedPacket(s,n.segment,n.track);let a=n.segment;for(;;){const o=await this.segmentedInput.getNextSegment(a,{skipLiveWait:t.skipLiveWait});if(!o)return null;const u=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(f=>f.type===n.track.type&&f.number===n.track.number);if(!u){a=o;continue}const d=await u._backing.getFirstPacket(t);return d?this.createAdjustedPacket(d,o,u):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,i){let n=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!n)return null;for(await this.hydrate();n;){const s=this.segmentedInput.getInputForSegment(n),o=(await s.getTracks()).find(d=>d.type===this.firstInputTrack.type&&d.number===this.firstInputTrack.number);if(!o){n=await this.segmentedInput.getPreviousSegment(n,{skipLiveWait:t.skipLiveWait});continue}const c=await this.segmentedInput.getMediaOffset(n,s),l=e-c,u=i?await o._backing.getKeyPacket(l,t):await o._backing.getPacket(l,t);if(!u){n=await this.segmentedInput.getPreviousSegment(n,{skipLiveWait:t.skipLiveWait});continue}return this.createAdjustedPacket(u,n,o)}return null}}class Ms extends yo{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}
1async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}class zs extends yo{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}An();const wo=0,ko=1/0;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(r=>{r()});class Ge extends Or{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<"u"&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new ge;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,wo,ko),e=this._getFileSize(),g(e!==void 0)),e})()}async getSize(){if(this._disposed)throw new ge;
1const e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new fu(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new qn(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}}class qn{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;g(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class Ur extends Ge{constructor(e,t){if(typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){const t=this.requestHandler(e),i=n=>{if(!(n instanceof Ge||n instanceof qn))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const s=n instanceof Ge?n.ref():n;return s.source._usedForHls||=this._usedForHls,s};return A(t)?t.then(i):i(t)}}const Os=(r,e)=>r.path===e.path;class cu extends Ur{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,i,n){if(!this._root){if(!this._rootRequest){const s=this._resolveRequest({path:this.rootPath,isRoot:!0}),a=o=>{const c=o instanceof Ge?o.ref():o;return this._root=c,this._rootRequest=null,c};A(s)?this._rootRequest=s.then(a):(a(s),g(this._root))}if(this._rootRequest)return this._rootRequest.then(s=>s.source._read(e,t,i,n))}return this._root.source._read(e,t,i,n)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}const Ds=typeof FinalizationRegistry<"u"?new FinalizationRegistry(r=>{r.cancel().catch(()=>{})}):null;class ih extends Ge{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!zr(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.useStreamReader!==void 0&&typeof t.useStreamReader!="boolean")throw new TypeError("options.useStreamReader, when provided, must be a boolean.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new du({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:i=>{const n=this._readers.get(i);n&&(this._readers.delete(i),Ds?.unregister(i),n.cancel().catch(()=>{}))},prefetchProfile:uu.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,n){return this._orchestrator.read(e,t,i,n)}async _runWorker(e){g(e.strictTarget);let t=this._readers.get(e);for(t===void 0&&("stream"in this._blob&&!Tr()&&this._options.useStreamReader!==!1?(t=this._blob.slice(e.currentPos).stream().getReader(),Ds?.register(e,t,e)):t=null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){const{done:i,value:n}=await t.read();if(i)throw this._orchestrator.onWorkerFinished(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}else{const i=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+i.byteLength),this._or
1chestrator.supplyWorkerData(e,new Uint8Array(i))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}}class lu extends Ge{constructor(e,t={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!zr(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.",this._stream=e,this._maxCacheSize=t.maxCacheSize??32*2**20}_getFileSize(){return this._endIndex}_read(e,t){if(this._endIndex!==null&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=X(this._cache,e,u=>u.start),n=i!==-1?this._cache[i]:null;if(n&&n.start<=e&&t<=n.end)return{bytes:n.bytes,view:n.view,offset:n.start};let s=e;const a=new Uint8Array(t-e);if(i!==-1)for(let u=i;u<this._cache.length;u++){const d=this._cache[u];if(d.start>=t)break;const f=Math.max(e,d.start);f>s&&this._throwDueToCacheMiss();const h=Math.min(t,d.end);f<h&&(a.set(d.bytes.subarray(f-d.start,h-d.start),f-e),s=h)}if(s===t)return{bytes:a,view:K(a),offset:e};this._currentIndex>s&&this._throwDueToCacheMiss();const{promise:o,resolve:c,reject:l}=se();return this._pendingSlices.push({start:e,end:t,bytes:a,resolve:c,reject:l}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(u=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(d=>d.reject(u)),this._pendingSlices.length=0;else throw u})),o}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){const{done:e,value:t}=await this._reader.read();if(e){for(const s of this._pendingSlices)s.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}const i=this._currentIndex,n=this._currentIndex+t.byteLength;this._dispatchRead(i,n);for(let s=0;s<this._pendingSlices.length;s++){const a=this._pendingSlices[s],o=Math.max(i,a.start),c=Math.min(n,a.end);o<c&&(a.bytes.set(t.subarray(o-i,c-i),o-a.start),c===a.end&&(a.resolve({bytes:a.bytes,view:K(a.bytes),offset:a.start}),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:i,end:n,bytes:t,view:K(t),age:0});this._cache.length>0;){const s=this._cache[0];if(this._maxRequestedIndex-s.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){for(const e of this._pendingSlices)e.reject(new ge);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const uu={fileSystem:(r,e)=>(r=Math.floor((r-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:r,end:e})};class du{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,i,n){g(!this.disposed);const s=this.options.prefetchProfile(e,t,this.workers),a=Math.max(s.start,i),o=Math.min(s.end,this.fileSize??1/0,n);g(a<=e&&t<=o);let c=null;const l=X(this.cache,e,T=>T.start),u=l!==-1?this.cache[l]:null;u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,c={bytes:u.bytes,view:u.view,offset:u.start});const d=X(this.cache,a,T=>T.start),f=c?null:new Uint8Array(t-e);let h=0,p=a;const m=[];if(d!==-1){for(let T=d;T<this.cache.length;T++){const P=this.cache[T];if(P.start>=o)break;if(P.end<=a)continue;const I=Math.max(a,P.start),C=Math.min(o,P.end);if(g(I<=C),p<I&&m.push({start:p,end:I}),p=C,f){const x=Math.max(e,P.start),E=Math.min(t,P.end);if(x<E){const _=x-e;
1f.set(P.bytes.subarray(x-P.start,E-P.start),_),_===h&&(h=E-e)}}P.age=this.nextAge++}p<o&&m.push({start:p,end:o})}else m.push({start:a,end:o});if(f&&h>=f.length&&(c={bytes:f,view:K(f),offset:e}),m.length===0)return g(c),c;const{promise:y,resolve:w,reject:k}=se(),b=[];for(const T of m){const P=Math.max(e,T.start),I=Math.min(t,T.end);P===T.start&&I===T.end?b.push(T):P<I&&b.push({start:P,end:I})}const S=f&&{start:e,bytes:f,holes:b,resolve:w,reject:k};e:for(const T of m){for(const C of this.workers)if(this.checkHoleAgainstWorker(C,T,S?[S]:[])){this.checkQueuedReadsAgainstWorker(C);continue e}const P=T.end<o||this.fileSize!==null,I=this.createWorker(T.start,T.end,P);if(I)S&&(I.pendingSlices=[S]),this.runWorker(I);else{let C=X(this.queuedReads,T.start,E=>E.hole.start),x=C!==-1?this.queuedReads[C]:null;for(x&&T.start<=x.hole.end?(x.hole.end=Math.max(x.hole.end,T.end),x.strictTarget&&=P,S&&x.pendingSlices.push(S)):(C++,x={hole:{start:T.start,end:T.end},strictTarget:P,pendingSlices:S?[S]:[],age:this.nextAge++},this.queuedReads.splice(C,0,x));C+1<this.queuedReads.length;){const E=this.queuedReads[C+1];if(E.hole.start>x.hole.end)break;x.hole.end=Math.max(x.hole.end,E.hole.end),x.pendingSlices.push(...E.pendingSlices),x.strictTarget&&=E.strictTarget,x.age=Math.min(x.age,E.age),this.queuedReads.splice(C+1,1)}}}return c?y.catch(T=>{if(!this.disposed)throw T}):(g(f),c=y.then(T=>T&&{bytes:T,view:K(T),offset:e})),c}checkHoleAgainstWorker(e,t,i){if(is(t.start-131072,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let s=0;s<i.length;s++){const a=i[s];e.pendingSlices.includes(a)||e.pendingSlices.push(a)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let i=0;i<this.queuedReads.length;i++){const n=this.queuedReads[i];if(this.checkHoleAgainstWorker(e,n.hole,n.pendingSlices))this.queuedReads.splice(i,1),i--,t=!0;else if(t)break}}createWorker(e,t,i){if(this.workers.length>=this.options.maxWorkerCount){let s=null,a=null;for(let o=0;o<this.workers.length;o++){const c=this.workers[o];!c.running&&c.pendingSlices.length===0&&(!s||c.age<s.age)&&(a=o,s=c)}if(s)g(a!==null),g(s.pendingSlices.length===0),this.workers.splice(a,1),this.options.onIdleWorkerRemoved?.(s);else return null}const n={startPos:e,currentPos:e,targetPos:t,strictTarget:i,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(n),n}runWorker(e){g(!e.running),g(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(i=>i.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed)throw t}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let t=0;for(let s=1;s<this.queuedReads.length;s++)this.queuedReads[s].age<this.queuedReads[t].age&&(t=s);const i=this.queuedReads[t],n=this.createWorker(i.hole.start,i.hole.end,i.strictTarget);if(!n)return;this.queuedReads.splice(t,1),n.pendingSlices=i.pendingSlices,this.runWorker(n)}})}supplyWorkerData(e,t){g(!e.aborted);const i=e.currentPos,n=i+t.length;this.insertIntoCache({start:i,end:n,bytes:t,view:K(t),age:this.nextAge++}),e.currentPos+=t.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let s=0;s<e.pendingSlices.length;s++){const a=e.pendingSlices[s],o=Math.max(i,a.start),c=Math.min(n,a.start+a.bytes.length);o<c&&a.bytes.set(t.subarray(o-i,c-i),o-a.start);for(let l=0;l<a.holes.length;l++){const u=a.holes[l];i<=u.start&&n>u.start&&(u.start=n),u.end<=u.start&&(a.holes.splice(l,1),l--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(s,1),s--)}for(let s=0;s<this.workers.length;s++){const a=this.workers[s];e===a||a.running||is(i,n,a.currentPos,a.targetPos)&&(this.workers.splice(s,1),this.options.onIdleWorkerRemoved?.(a),s--)}}supplyFileSize(e){g(this.fileSize===null),this.fileSize=e;for(const t of this.workers){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let i=0;i<t.pendingSlices.length;i++){const n=t.pendingSlices[i];for(const s of n.holes)if(s.end>e){n.resolve(null),t.pendingSlices.splice(i,1),i--;break}}}for(let t=0;t<this.queuedReads.length;t++){const i=this.queuedReads[t];if(i.hole.start>=e){for(const n of i.pendingSlices)n.resolve(null);this.queuedReads.splice(t,1),t--}else if(i.hole.end>e){i.hole.end=e,i.strictTarget=!0;for(let n=0;n<i.pendingSlices.length;n++){const s=i.pendingSlices[n];s.start>=e&&(s.resolve(null),i.pendingSlices.splice(n,1),n--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.aborted||(e.pendingSlices.length=0)}
1onWorkerFinished(e){const t=this.workers.indexOf(e);g(t!==-1),e.running=!1,this.workers.splice(t,1),this.options.onIdleWorkerRemoved?.(e),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(const i of e.pendingSlices)i.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=X(this.cache,e.start,i=>i.start)+1;if(t>0){const i=this.cache[t-1];if(i.end>=e.end)return;if(i.end>e.start){const n=new Uint8Array(e.end-i.start);n.set(i.bytes,0),n.set(e.bytes,e.start-i.start),this.currentCacheSize+=e.end-i.end,i.bytes=n,i.view=K(n),i.end=e.end,t--,e=i}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 i=t+1;i<this.cache.length;i++){const n=this.cache[i];if(e.end<=n.start)break;if(e.end>=n.end){this.cache.splice(i,1),this.currentCacheSize-=n.bytes.length,i--;continue}const s=new Uint8Array(n.end-e.start);s.set(e.bytes,0),s.set(n.bytes,n.start-e.start),this.currentCacheSize-=e.end-n.start,e.bytes=s,e.view=K(s),e.end=n.end,this.cache.splice(i,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let i=0,n=this.cache[0];for(let s=1;s<this.cache.length;s++){const a=this.cache[s];a.age<n.age&&(i=s,n=a)}if(this.currentCacheSize-n.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(i,1),this.currentCacheSize-=n.bytes.length}}dispose(){for(const e of this.workers){for(const t of e.pendingSlices)t.reject(new ge);e.pendingSlices.length=0,e.aborted=!0,e.running||this.options.onIdleWorkerRemoved?.(e)}for(const e of this.queuedReads)for(const t of e.pendingSlices)t.reject(new ge);this.workers.length=0,this.cache.length=0,this.queuedReads.length=0,this.disposed=!0}}class fu extends Ge{constructor(e,t,i){if(super(),this._ref=null,e._disposed)throw new Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=t,this._length=i??null}_getFileSize(){const e=this._baseSource._getFileSize();return e===void 0?this._length!==null?this._length:void 0:e===null?this._length!==null?this._length:null:oe(e-this._offset,0,this._length??1/0)}_read(e,t,i,n){if(this._length!==null&&t>this._length)return null;const s=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+n),a=o=>o?(o.offset-=this._offset,o):null;return A(s)?s.then(a):a(s)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}}var Ns=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,n;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(n=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");n&&(i=function(){try{n.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:i,async:t})}else t&&r.stack.push({async:!0});return e},Us=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var i,n=0;function s(){for(;i=e.stack.pop();)try{if(!i.async&&n===1)return n=0,e.stack.push(i),Promise.resolve().then(s);if(i.dispose){var a=i.dispose.call(i.value);if(i.async)return n|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else n|=1}catch(o){t(o)}if(n===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=r,i.suppressed=e,i});const hu=/^0[xX][0-9a-fA-F]+$/,mu=/^data:.*;base64,/i;class Ws extends ou{constructor(e,t,i,n){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=n}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{const e=this.getRemainingWaitTimeMs();e>0&&await xa(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){const e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){const b={stack:[],error:void 0,hasError:!1};
1try{const S=Ns(b,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),P=await new Zr(S.source).requestEntireFile();g(P),e=Uo(P,P.length,{ignore:go}),S.source instanceof Ur&&(this.rootPath=S.source.rootPath)}catch(S){b.error=S,b.hasError=!0}finally{Us(b)}}const t=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1;let i=!1,n=0,s=null,a=null,o=null,c=0,l=null,u=null,d=null,f=null,h=null,p=null,m=!1,y=re(this.segments)??null;const w=b=>{const S=b.indexOf("@"),T=Number(S===-1?b:b.slice(0,S));if(!Number.isInteger(T)||T<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${b}'.`);let P=null;if(S!==-1&&(P=Number(b.slice(S+1)),!Number.isInteger(P)||P<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${b}'.`);return{length:T,offset:P}},k=b=>{c=b,y&&(g(y.sequenceNumber!==null),y.sequenceNumber<b&&(n=y.timestamp+y.duration,l=y.firstSegment,u=y.initSegment,h=y.lastProgramDateTimeSeconds,s=y.unixEpochTimestamp!==null?y.unixEpochTimestamp+y.duration:null,y=null))};for(let b=0;b<e.length;b++){const S=e[b];if(!i){if(S!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");i=!0;continue}if(!S.startsWith("#")){if(!y){if(a===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let T=o;if(T&&T.method==="AES-128"&&!T.iv){const x=new Uint8Array(qe),E=K(x);E.setUint32(8,Math.floor(c/2**32)),E.setUint32(12,c),T={...T,iv:x}}const I={path:yt(this.rootPath,S),offset:f?.offset??0,length:f?.length??null},C={timestamp:n,unixEpochTimestamp:s,firstSegment:l,sequenceNumber:c,location:I,duration:a,encryption:T,initSegment:u,lastProgramDateTimeSeconds:h};l??=C,n+=a,s!==null&&(s+=a),this.segments.push(C)}a=null,f===null?d=null:f=null,k(c+1)}if(S.startsWith(bn)){if(y){m=!0;continue}m||(h===null&&c>0&&p!==null&&(n=c*p),m=!0);const T=S.slice(bn.length),P=T.indexOf(","),I=P===-1?T:T.slice(0,P),C=Number(I);if(!Number.isFinite(C)||C<0)throw new Error(`Invalid #EXTINF tag duration '${I}'.`);a=C}else if(S.startsWith(Es)){const T=new Pr(S.slice(Es.length)),P=T.get("uri");if(!P)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const I=T.get("byterange");let C=null;if(I!==null&&(C=w(I)),C&&C.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!y){const E={path:yt(this.rootPath,P),offset:C?.offset??0,length:C?.length??null};if(o?.method==="AES-128"&&!o.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");u={timestamp:n,unixEpochTimestamp:s,firstSegment:null,sequenceNumber:null,location:E,duration:0,encryption:o,initSegment:null,lastProgramDateTimeSeconds:h}}a=null,f===null?d=null:f=null}else if(S.startsWith(_s)){const T=new Pr(S.slice(_s.length)),P=T.get("method");if(P==="NONE")o=null;else if(P==="AES-128"){const I=T.get("uri");if(!I)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let C=null;const x=T.get("iv");if(x){if(!hu.test(x))throw new Error(`Unsupported IV format '${x}'.`);let _=x.slice(2);_=_.padStart(qe*2,"0"),C=new Uint8Array(qe);for(let v=0;v<qe;v++){const R=-qe*2+v;C[v]=parseInt(_.slice(R,R+2),16)}}const E=T.get("keyformat")??"identity";if(E!=="identity")throw new Error("For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.");o={method:"AES-128",keyUri:yt(this.rootPath,I),iv:C,keyFormat:E}}else if(P==="SAMPLE-AES"||P==="SAMPLE-AES-CTR"){const I=T.get("uri");if(!I)throw new Error(`Invalid #EXT-X-KEY: ${P} requires a URI attribute.`);if((T.get("keyformat")??"identity")==="identity")throw new Error("For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.");let x=null;if(mu.test(I)){const E=I.indexOf(","),_=Sa(I.slice(E+1));if(_.length>=8&&_[4]===112&&_[5]===115&&_[6]===115&&_[7]===104){const v=K(_).getUint32(0);x=Za(_.subarray(8,Math.min(v,_.length)))}}o={method:P,psshBox:x}}else throw new Error(`Unsupported encryption method '${P}'. If you think this method should be supported, please raise an issue.`)}else if(S.startsWith(vs)){const T=S.slice(vs.length),P=Number(T);
1if(!Number.isInteger(P)||P<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${T}'.`);k(P)}else if(S.startsWith(As)){const T=w(S.slice(As.length));if(T.offset===null){if(d===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");T.offset=d}f=T,d=T.offset+T.length}else if(S.startsWith(Bs)){if(y)continue;const T=S.slice(Bs.length),P=Date.parse(T);if(!Number.isFinite(P))continue;const I=P/1e3;if(h===I)continue;if(h===null&&this.segments.length>0){const C=re(this.segments),x=C.timestamp+C.duration,E=I-x;for(const _ of this.segments)_.unixEpochTimestamp=_.timestamp+E,t&&(_.timestamp=_.unixEpochTimestamp)}h=I,s=I,t&&(n=I)}else if(S===nu)l=null;else if(S.startsWith(Fs)){const T=S.slice(Fs.length),P=Number(T);if(!Number.isFinite(P)||P<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${T}'.`);this.refreshInterval=P,p=P}else if(S===su){this.streamHasEnded=!0;break}else S.startsWith(Rs)&&S.slice(Rs.length).toLowerCase()==="vod"&&(this.streamHasEnded=!0)}if(!i)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){this.segments.length===0&&await this.runUpdateSegments();let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const n=X(this.segments,e,a=>a.timestamp);if(n===-1)return null;if(n<this.segments.length-1||this.streamHasEnded||i)return this.segments[n];const s=this.segments[n];if(e<s.timestamp+s.duration)return s;await this.runUpdateSegments(),t.skipLiveWait&&(i=!0)}}async getNextSegment(e,t){const i=this.segments.indexOf(e);g(i!==-1);const n=i+1;let s=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(n<this.segments.length)return this.segments[n];if(this.streamHasEnded||s)return null;await this.runUpdateSegments(),t.skipLiveWait&&(s=!0)}}async getPreviousSegment(e){const t=this.segments.indexOf(e);return g(t!==-1),this.segments[t-1]??null}getInputForSegment(e){const t=e,i=this.inputCache.find(c=>c.segment===t);if(i)return i.age=this.nextInputCacheAge++,i.input;let n=null;(t.initSegment||t.firstSegment)&&(n=this.getInputForSegment(t.initSegment??t.firstSegment));const s={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(c=>{if(!t.encryption||!(t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR")||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(c);let l=c.psshBoxes;const{psshBox:u}=t.encryption;return(u.keyIds===null||u.keyIds.includes(c.keyId))&&!l.some(d=>Ja(d,u))&&(l=[...l,u]),this.input._formatOptions.isobmff.resolveKeyId({...c,psshBoxes:l})})}},a=new Pi({source:new cu(t.location.path,async c=>{g(c.isRoot);const l={...c,isRoot:!1};let u;const d=t.location.offset>0||t.location.length!==null;if(!t.encryption||t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR"){if(u=await this.input._getSourceCached(l),d){const h=u.source.slice(t.location.offset,t.location.length??void 0).ref();u.free(),u=h}}else if(t.encryption.method==="AES-128"){const f=t.encryption;g(f.iv);let h=await this.input._getSourceCached(l);if(d){const w=h.source.slice(t.location.offset,t.location.length??void 0).ref();h.free(),h=w}const p=new Zr(h.source),m=pl(p,async()=>{const y={stack:[],error:void 0,hasError:!1};try{const w=Ns(y,await this.input._getSourceCached({path:f.keyUri,isRoot:!1},pd),!1),b=await new Zr(w.source).requestSlice(0,qe);if(!b)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:W(b,qe),iv:f.iv}}catch(w){y.error=w,y.hasError=!0}finally{Us(y)}},()=>{h.free()});u=new lu(m).ref()}else g(!1);return u}),formats:this.input._formats.filter(c=>!(c instanceof Co)),initInput:n??void 0,formatOptions:s});if(a._onFormatDetermined=c=>{if((t.encryption?.method==="SAMPLE-AES"||t.encryption?.method==="SAMPLE-AES-CTR")&&!c._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:t,input:a,age:this.nextInputCacheAge++}),this.inputCache.length>4){const c=Bn(this.inputCache,l=>l.age);g(c!==-1),this.inputCache.splice(c,1)}return a}
1async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class pu extends ht{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{g(this.input._rootSource instanceof Ur);const e=await this.input._reader.requestEntireFile();g(e);const t=Uo(e,e.length,{ignore:go}),{rootPath:i}=this.input._rootSource,n=[],s=[];for(let d=1;d<t.length;d++){const f=t[d];if(f.startsWith(Ps)){const h=d,p=t[++d];if(p===void 0)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");const m=yt(i,p),y=new Pr(f.slice(Ps.length));if(y.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");n.push({fullPath:m,attributes:y,lineNumber:h,hasOnlyKeyPackets:!1})}else if(f.startsWith(Cs)){const h=new Pr(f.slice(Cs.length)),p=h.get("uri");if(p===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(h.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");const y=yt(i,p);n.push({fullPath:y,attributes:h,lineNumber:d,hasOnlyKeyPackets:!0})}else if(f.startsWith(Is)){const h=new Pr(f.slice(Is.length));if(h.get("type")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(h.get("group-id")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let y=null;const w=h.get("uri");w!==null&&(y=yt(i,w)),s.push({fullPath:y,attributes:h,lineNumber:d})}else if(f!==au){if(f.startsWith(bn)){const h=new Ws(this,i,null,t);this.segmentedInputs=[h],this.hasMasterPlaylist=!1,this.trackBackings=await h.getTrackBackings();return}}}const a=[...new Set(s.filter(d=>d.attributes.get("type").toLowerCase()==="video").map(d=>d.attributes.get("group-id")))],o=[...new Set(s.filter(d=>d.attributes.get("type").toLowerCase()==="audio").map(d=>d.attributes.get("group-id")))],c=await Promise.all(n.map(async(d,f)=>{const h=[],p=d.attributes.get("codecs");let m;if(p)m=p.split(",").map(x=>x.trim());
1else{const E=await this.getSegmentedInputForPath(d.fullPath).getTrackBackings(),_=await Promise.all(E.map(async v=>({track:v,codec:await v.getCodec()})));m=await Promise.all(_.filter(v=>v.codec!==null).map(v=>v.track.getDecoderConfig().then(R=>R.codec)))}const y=d.attributes.get("video"),w=d.attributes.get("audio"),k=m.some(x=>_e.includes(lt(x))),b=m.some(x=>Re.includes(lt(x)));if(y!==null&&!k){if(!a.includes(y))throw new Error(`Invalid M3U8 file; variant stream references video group "${y}" which is not defined in any #EXT-X-MEDIA tags.`);const x=s.find(E=>{const _=E.attributes.get("group-id"),v=E.attributes.get("type");return _===y&&v.toLowerCase()==="video"});e:if(x){const E=x.attributes.get("uri");if(E===null)break e;const _=yt(i,E),O=(await this.getSegmentedInputForPath(_).getTrackBackings()).find(D=>D.getType()==="video");if(!O||await O.getCodec()===null)break e;const N=await O.getDecoderConfig().then(D=>D?.codec??null);g(N!==null),m.push(N)}}if(w!==null&&!b){if(!o.includes(w))throw new Error(`Invalid M3U8 file; variant stream references audio group "${w}" which is not defined in any #EXT-X-MEDIA tags.`);const x=s.find(E=>{const _=E.attributes.get("group-id"),v=E.attributes.get("type");return _===w&&v.toLowerCase()==="audio"});e:if(x){const E=x.attributes.get("uri");if(E===null)break e;
1const _=yt(i,E),O=(await this.getSegmentedInputForPath(_).getTrackBackings()).find(D=>D.getType()==="audio");if(!O||await O.getCodec()===null)break e;const N=await O.getDecoderConfig().then(D=>D?.codec??null);g(N!==null),m.push(N)}}m=[...new Set(m)];let S=null,T=null;const P=d.attributes.getAsNumber("bandwidth");g(P!==null);const I=d.attributes.getAsNumber("average-bandwidth"),C=d.attributes.get("name");for(const x of m){const E=lt(x);if(E!==null){if(_e.includes(E)){if(S!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");S=x;const _=d.attributes.get("video");if(_===null){const v=d.attributes.get("resolution");let R=null,O=null;if(v){const N=v.match(/^(\d+)x(\d+)$/);N&&(R=Number(N[1]),O=Number(N[2]))}h.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:ye,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:S,pairingMask:1n<<BigInt(f),peakBitrate:P,averageBitrate:I,name:C,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:R,height:O}})}else{if(!a.includes(_))throw new Error(`Invalid M3U8 file; variant stream references video group "${_}" which is not defined in any #EXT-X-MEDIA tags.`);for(const v of s){const R=v.attributes.get("group-id"),O=v.attributes.get("type");if(R!==_||O.toLowerCase()!=="video")continue;const N=v.attributes.get("resolution")??d.attributes.get("resolution");let D=null,$=null;if(N){const J=N.match(/^(\d+)x(\d+)$/);J&&(D=Number(J[1]),$=Number(J[2]))}h.push({id:-1,demuxer:this,backingTrack:null,default:Lr(v.attributes),autoselect:Lr(v.attributes)||Vs(v.attributes),languageCode:Ls(v.attributes.get("language")),lineNumber:v.lineNumber,fullPath:v.fullPath??d.fullPath,fullCodecString:S,pairingMask:1n<<BigInt(f),peakBitrate:null,averageBitrate:null,name:v.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:D,height:$}})}}}else if(Re.includes(E)){if(T!==null)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");T=x;const _=d.attributes.get("audio");if(_===null){const v=d.attributes.get("channels"),R=v!==null?Number(v.split("/")[0]):null;h.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:ye,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:T,pairingMask:1n<<BigInt(f),peakBitrate:P,averageBitrate:I,name:C,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:R!==null&&Number.isInteger(R)&&R>0?R:null}})}else{if(!o.includes(_))throw new Error(`Invalid M3U8 file; variant stream references audio group "${_}" which is not defined in any #EXT-X-MEDIA tags.`);for(const v of s){const R=v.attributes.get("group-id"),O=v.attributes.get("type");if(R!==_||O.toLowerCase()!=="audio")continue;const N=v.attributes.get("channels")??d.attributes.get("channels"),D=N!==null?Number(N.split("/")[0]):null;h.push({id:-1,demuxer:this,backingTrack:null,default:Lr(v.attributes),autoselect:Lr(v.attributes)||Vs(v.attributes),languageCode:Ls(v.attributes.get("language")),lineNumber:v.lineNumber,fullPath:v.fullPath??d.fullPath,fullCodecString:T,pairingMask:1n<<BigInt(f),peakBitrate:null,averageBitrate:null,name:v.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:D!==null&&Number.isInteger(D)&&D>0?D:null}})}}}}}return h})),l=[],u=d=>{const f=l.find(h=>h.fullPath===d.fullPath&&h.info.type===d.info.type);f?(f.pairingMask|=d.pairingMask,f.default||=d.default,f.autoselect||=d.autoselect,f.lineNumber=Math.min(f.lineNumber,d.lineNumber),d.peakBitrate!==null&&(f.peakBitrate=Math.max(f.peakBitrate??-1/0,d.peakBitrate)),d.averageBitrate!==null&&(f.averageBitrate=Math.max(f.averageBitrate??-1/0,d.averageBitrate)),f.languageCode===ye&&(f.languageCode=d.languageCode)):(d.id=l.length+1,l.push(d))};for(const d of c)for(const f of d)u(f);l.sort((d,f)=>d.lineNumber-f.lineNumber),this.trackBackings=[];for(const d of l)d.info.type==="video"?this.trackBackings.push(new To(d)):this.trackBackings.push(new So(d));this.internalTracks=l})()}async getTrackBackings(){return await this.readMetadata(),g(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(n=>n.path===e);if(t)return t;let i=null;return this.internalTracks&&(i=this.internalTracks.filter(s=>s.fullPath===e).map(s=>({id:s.id,type:s.info.type}))),t=new Ws(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return po}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class bo{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let t=null;const n=(await e.getTrackBackings()).filter(s=>s.getType()===this.getType());if(n.length===1)t=n[0];else if(this instanceof To){for(const s of n)if(await s.getCodec()===this.getCodec()){t=s;break}}else{g(this instanceof So);for(const s of n)if(await s.getCodec()===this.getCodec()){t=s;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t})()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...ft,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){g(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}
vendor: 1,594 bytes, line 1
1async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}}class To extends bo{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return lt(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}
1async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}}class So extends bo{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return lt(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}}const Lr=r=>{const e=r.get("default");if(e===null)return!1;const t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${e}".`)},Vs=r=>{const e=r.get("autoselect");if(e===null)return!1;const t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${e}".`)},Ls=r=>{if(r===null)return ye;const e=r.split("-")[0];return e||ye};class Qe{constructor(){this._isIsobmff=!1}}class xo extends Qe{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(A(t)&&(t=await t),!t)return null;t.skip(4);const i=ne(t,4);return i!=="ftyp"&&i!=="styp"?null:ne(t,4)}_createDemuxer(e){return new Ln(e)}}class gu extends xo{async _canReadInput(e){const t=await this._getMajorBrand(e);if(t!==null)return t!=="qt  ";let i=0;for(let n=0;n<10;n++){let s=e._reader.requestSlice(i,8);if(A(s)&&(s=await s),!s)return!1;let a=M(s),o=8;if(a===1){let l=e._reader.requestSlice(i+8,8);if(A(l)&&(l=await l),!l)return!1;a=Ce(l),o=16}if(a<o)return!1;const c=ne(s,4);if(c==="moof"||c==="sidx")return!0;if(c==="emsg"||c==="prft"||c==="free")i+=a;else return!1}return!1}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class yu extends xo{async _canReadInput(e){return await this._getMajorBrand(e)==="qt  "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class Po extends Qe{async isSupportedEBMLOfDocType(e,t){let i=e._reader.requestSlice(0,at);if(A(i)&&(i=await i),!i)return!1;const n=ao(i);if(n===null||n<1||n>8||j(i,n)!==B.EBML)return!1;const a=oo(i);if(typeof a!="number")return!1;let o=e._reader.requestSlice(i.filePos,a);if(A(o)&&(o=await o),!o)return!1;const c=i.filePos;for(;o.filePos<=c+a-Be;){const l=et(o);if(!l)break;const{id:u,size:d}=l,f=o.filePos;if(d===void 0)return!1;switch(u){case B.EBMLVersion:if(j(o,d)!==1)return!1;break;case B.EBMLReadVersion:if(j(o,d)!==1)return!1;break;case B.DocType:if($t(o,d)!==t)return!1;break;case B.DocTypeVersion:if(j(o,d)>4)return!1;break}o.filePos=f+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Cl(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class wu extends Po{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class ku extends Qe{async _canReadInput(e){let t=0;for(;;){let d=e._reader.requestSlice(t,Me);if(A(d)&&(d=await d),!d)break;const f=dt(d);if(!f)break;t=d.filePos+f.size}const i=await wn(e._reader,t,t+4096);if(!i)return!1;const n=i.header,s=Qa(n.mpegVersionId,n.channel);let a=e._reader.requestSlice(i.startPos+s,4);if(A(a)&&(a=await a),!a)return!1;const o=M(a);if(o===Ga||o===Xa)return!0;t=i.startPos+i.header.totalSize;const l=await wn(e._reader,t,t+Rt);if(!l)return!1;const u=l.header;return!(n.channel!==u.channel||n.sampleRate!==u.sampleRate)}_createDemuxer(e){return new _l(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}
1class bu extends Qe{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(A(t)&&(t=await t),!t)return!1;const i=ne(t,4);return i!=="RIFF"&&i!=="RIFX"&&i!=="RF64"?!1:(t.skip(4),ne(t,4)==="WAVE")}_createDemuxer(e){return new Nl(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Tu extends Qe{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return A(t)&&(t=await t),t?ne(t,4)==="OggS":!1}_createDemuxer(e){return new Ol(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Su extends Qe{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,Me);if(A(n)&&(n=await n),!n)break;const s=dt(n);if(!s)break;t=n.filePos+s.size}let i=e._reader.requestSlice(t,4);return A(i)&&(i=await i),i?ne(i,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Gl(e)}}class xu extends Qe{async _canReadInput(e){let t=0;for(;;){let a=e._reader.requestSlice(t,Me);if(A(a)&&(a=await a),!a)break;const o=dt(a);if(!o)break;t=a.filePos+o.size}let i=e._reader.requestSliceRange(t,oi,Mt);if(A(i)&&(i=await i),!i)return!1;const n=Dt(i);if(!n||(t+=n.frameLength,i=e._reader.requestSliceRange(t,oi,Mt),A(i)&&(i=await i),!i))return!1;const s=Dt(i);return s?n.objectType===s.objectType&&n.samplingFrequencyIndex===s.samplingFrequencyIndex&&n.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new Wl(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Pu extends Qe{async _canReadInput(e){const t=Ie+16+1;let i=e._reader.requestSlice(0,t);if(A(i)&&(i=await i),!i)return!1;const n=W(i,t);return n[0]===71&&n[Ie]===71||n[0]===71&&n[Ie+16]===71?!0:n[4]===71&&n[4+Ie+4]===71}_createDemuxer(e){return new tu(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Co extends Qe{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(A(t)&&(t=await t),!t||!(ne(t,7)==="#EXTM3U"))return!1;if(!(e._rootSource instanceof Ur))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,!0}_createDemuxer(e){return new pu(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return po}}const Cu=new gu,Iu=new yu,Eu=new Po,_u=new wu,vu=new ku,Au=new bu,Bu=new Tu,Fu=new xu,Ru=new Su,Mu=new Pu,zu=new Co,nh=[zu,Cu,Iu,Eu,_u,Au,Bu,Ru,vu,Fu,Mu],Ou=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(`${e}, when provided, must be an object.`);if(r.isobmff!==void 0){if(!r.isobmff||typeof r.isobmff!="object")throw new TypeError(`${e}.isobmff, when provided, must be an object.`);if(r.isobmff.resolveKeyId!==void 0&&typeof r.isobmff.resolveKeyId!="function")throw new TypeError(`${e}.isobmff.resolveKeyId, when provided, must be a function.`)}if(r.hls!==void 0){if(!r.hls||typeof r.hls!="object")throw new TypeError(`${e}.hls, when provided, must be an object.`);if(r.hls.offsetTimestampsByDateTime!==void 0&&typeof r.hls.offsetTimestampsByDateTime!="boolean")throw new TypeError(`${e}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};var Du=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,n;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(n=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");n&&(i=function(){try{n.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:i,async:t})}else t&&r.stack.push({async:!0});return e},Nu=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var i,n=0;function s(){for(;i=e.stack.pop();)try{if(!i.async&&n===1)return n=0,e.stack.push(i),Promise.resolve().then(s);if(i.dispose){var a=i.dispose.call(i.value);if(i.async)return n|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else n|=1}catch(o){t(o)}
1if(n===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=r,i.suppressed=e,i});An();let Hs=-1/0,qs=-1/0,Rr=null;typeof FinalizationRegistry<"u"&&(Rr=new FinalizationRegistry(r=>{const e=performance.now();r.type==="video"?(e-Hs>=1e3&&(H._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."),Hs=e),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(e-qs>=1e3&&(H._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."),qs=e),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));class xt{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Tn=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Uu=new Set(Tn);class pe{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(wt*this.timestamp)}get microsecondDuration(){return Math.trunc(wt*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.format===void 0||!Uu.has(t.format))throw new TypeError("init.format must be one of: "+Tn.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const s of t.layout){if(!s||typeof s!="object"||Array.isArray(s))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(s.offset)||s.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(s.stride)||s.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.visibleRect!==void 0&&Fi(t.visibleRect,"init.visibleRect"),t.displayWidth!==void 0&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(t.displayHeight!==void 0&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(t.displayWidth!==void 0!=(t.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=t.format,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0;const i=t.layout??Lu(t.format,t.codedWidth,t.codedHeight);let n=t.colorSpace??null;n===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?n={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:n={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:t.visibleRect?.left??0,top:t.visibleRect?.top??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},t.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=t._doNotC
vendor: 4,620 bytes, line 1
1opy?ke(e):ke(e).slice(),this._layout=i,this.colorSpace=new Li(n)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");t?.visibleRect!==void 0&&Fi(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=t?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new Li(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(t.visibleRect!==void 0&&Fi(t.visibleRect,"init.visibleRect"),typeof VideoFrame<"u")return new pe(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*wt),duration:Math.trunc((t.duration??0)*wt)||void 0,visibleRect:t.visibleRect&&{x:t.visibleRect.left,y:t.visibleRect.top,width:t.visibleRect.width,height:t.visibleRect.height}}),t);let i=0,n=0;if("naturalWidth"in e?(i=e.naturalWidth,n=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,n=e.videoHeight):"width"in e&&(i=Number(e.width),n=Number(e.height)),!i||!n)throw new TypeError("Could not determine dimensions.");const s=t.visibleRect??{left:0,top:0,width:i,height:n},a=new OffscreenCanvas(s.width,s.height),o=a.getContext("2d",{alpha:ba(),willReadFrequently:!0});if(!o)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");o.drawImage(e,-s.left,-s.top),this._data=a,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:s.width,height:s.height},this.squarePixelWidth=s.width,this.squarePixelHeight=s.height,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new Li({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof xt){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),this.format!==null&&!Tn.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace
1=e.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=t?.encodeOptions??{},this.pixelAspectRatio=vr({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Rr?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return g(this._data!==null),this._data instanceof xt?new pe(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):ur(this._data)?new pe(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(g(this._layout),new pe(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new pe(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(Rr?.unregister(this),this._data instanceof xt?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):ur(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Ks(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return ur(this._data)?this._data.allocationSize(e):Gs(this,e).allocationSize}async copyTo(e,t={}){if(!ui(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ks(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(g(this._data!==null),ur(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format))if(this._data instanceof xt){const l={stack:[],error:void 0,hasError:!1};try{const u=Du(l,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(u instanceof pe))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(u.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${u.format}' instead.`);return await u.copyTo(e,t)}catch(u){l.error=u,l.hasError=!0}finally{Nu(l)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const l=this.toVideoFrame(),u=await l.copyTo(e,t);return l.close(),u}const i=Gs(this,t);g(this.format);const n=ke(e);if(n.byteLength<i.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${i.allocationSize}, Available: ${n.byteLength}`);const s=xi(this.format);let a;if(this._data instanceof xt){let l=this._data.getDataPlanes();if(A(l)&&(l=await l),!Array.isArray(l)||l.some(u=>!(u.data instanceof Uint8Array)||!Number.isInteger(u.stride)||u.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');a=l}else if(this._data instanceof Uint8Array)g(this._layout),g(this._layout.length===s.length),a=this._layout.map((l,u)=>{const d=Math.ceil(this.codedHeight/s[u].heightDivisor);return{data:this._data.subarray(l.offset,l.offset+l.stride*d),stride:l.stride}});else{const u=this._data.getContext("2d");g(u);const d=u.getImageData(0,0,this.codedWidth,this.codedHeight);
1a=[{data:ke(d.data),stride:4*this.codedWidth}]}const o=[],c=s.length;for(let l=0;l<c;l++){const u=i.computedLayouts[l],d=a[l].stride,f=a[l].data;let h=u.sourceTop*d;h+=u.sourceLeftBytes;let p=u.destinationOffset;const m=u.sourceWidthBytes,y={offset:p,stride:u.destinationStride};for(let w=0;w<u.sourceHeight;w++){if(h+m>f.byteLength)throw new Error("Source buffer OOB read.");if(p+m>n.byteLength)throw new Error("Destination buffer OOB write.");const k=f.subarray(h,h+m);n.set(k,p),h+=d,p+=u.destinationStride}o.push(y)}if(t.format!==void 0){const l=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),u=this.format.includes("X")&&t.format.includes("A");if(l||u)for(let d=0;d<i.allocationSize;d+=4){if(l){const f=n[d],h=n[d+2];n[d]=h,n[d+2]=f}u&&(n[d+3]=255)}}return o}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(g(this._data!==null),this._data instanceof xt){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const e=this._data.getDataPlanes();if(A(e))throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const t=e.reduce((a,o)=>a+o.data.byteLength,0),i=new Uint8Array(t);let n=0;const s=[];for(const a of e)i.set(a.data,n),s.push(n),n+=a.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((a,o)=>({offset:s[o],stride:a.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return ur(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(g(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,n,s,a,o,c,l){let u=0,d=0,f=this.displayWidth,h=this.displayHeight,p=0,m=0,y=this.displayWidth,w=this.displayHeight;if(a!==void 0?(u=t,d=i,f=n,h=s,p=a,m=o,c!==void 0?(y=c,w=l):(y=f,w=h)):(p=t,m=i,n!==void 0&&(y=n,w=s)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:d,sWidth:f,sHeight:h}=this._rotateSourceRegion(u,d,f,h,this.rotation));const k=this.toCanvasImageSource();e.save();const b=p+y/2,S=m+w/2;e.translate(b,S),e.rotate(this.rotation*Math.PI/180);const T=this.rotation%180===0?1:y/w;e.scale(1/T,T),e.drawImage(k,u,d,f,h,-y/2,-w/2,y,w),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");
1if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");t.crop!==void 0&&li(t.crop,"options.");const i=e.canvas.width,n=e.canvas.height,s=t.rotation??this.rotation,[a,o]=s%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let c=t.crop;c&&(c=Sn(c,a,o));let l,u,d,f;const{sx:h,sy:p,sWidth:m,sHeight:y}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??a,t.crop?.height??o,s);if(t.fit==="fill")l=0,u=0,d=i,f=n;else{const[k,b]=t.crop?[t.crop.width,t.crop.height]:[a,o],S=t.fit==="contain"?Math.min(i/k,n/b):Math.max(i/k,n/b);d=k*S,f=b*S,l=(i-d)/2,u=(n-f)/2}e.save();const w=s%180===0?1:d/f;e.translate(i/2,n/2),e.rotate(s*Math.PI/180),e.scale(1/w,w),e.translate(-i/2,-n/2),e.drawImage(this.toCanvasImageSource(),h,p,m,y,l,u,d,f),e.restore()}_rotateSourceRegion(e,t,i,n,s){return s===90?[e,t,i,n]=[t,this.squarePixelHeight-e-i,n,i]:s===180?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-n]:s===270&&([e,t,i,n]=[this.squarePixelWidth-t-n,e,n,i]),{sx:e,sy:t,sWidth:i,sHeight:n}}_drawWithFitAndMipmapping(e,t,i){const n=e.width,s=e.height,[a,o]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=i.crop?i.crop.width:a,l=i.crop?i.crop.height:o;let u=0;2*n<c&&2*s<l&&(u=Math.floor(Math.log2(Math.min(c/n,l/s))));const d=n*2**u,f=s*2**u,{canvas:h,context:p,isNew:m}=u>0?$s(d,f):{canvas:e,context:t,isNew:i.targetIsFresh};p.imageSmoothingQuality="high",i.fillBlack?(p.fillStyle="black",p.fillRect(0,0,d,f)):m||p.clearRect(0,0,d,f),this.drawWithFit(p,{fit:i.fit,rotation:i.rotation,crop:i.crop}),p.globalCompositeOperation="copy";for(let y=u;y>1;y--){const w=n*2**y,k=s*2**y;p.drawImage(h,0,0,w,k,0,0,w/2,k/2)}p.globalCompositeOperation="source-over",u>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(h,0,0,2*n,2*s,0,0,n,s),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(g(this._data!==null),this._data instanceof xt||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}async transform(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(e.roundDimensionsTo!==void 0&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(e.crop!==void 0&&li(e.crop,"options."),e.alpha!==void 0&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const t=Cr(this.rotation+(e.rotate??0)),[i,n]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let s=e.crop;s&&(s=Sn(s,i,n));const a=s?s.width:i,o=s?s.height:n,c=a/o;let l,u;e.width!==void 0&&e.height===void 0?(l=e.width,u=l/c):e.width===void 0&&e.height!==void 0?(u=e.height,l=u*c):e.width!==void 0&&e.height!==void 0?(l=e.width,u=e.height):(l=a,u=o),l=on(l,e.roundDimensionsTo??1),u=on(u,e.roundDimensionsTo??1);const d={width:l,height:u,fit:e.fit??"fill",rotation:t,crop:s??{left:0,top:0,width:i,height:n},alpha:e.alpha??"keep"};for(const m of Wu){let y=m(this,d);if(A(y)&&(y=await y),y!==null)return y}const{canvas:f,context:h,isNew:p}=$s(d.width,d.height);return this._drawWithFitAndMipmapping(f,h,{fit:d.fit,rotation:d.rotation,crop:d.crop,targetIsFresh:p,fillBlack:d.alpha==="discard"}),new pe(f,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||typeof e!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const Wu=[],Vu=3,lr=[];let js=0;const $s=(r,e)=>{for(const n of lr)if(n.canvas.width===r&&n.canvas.height===e)return n.age=js++,{canvas:n.canvas,context:n.context,isNew:!1};let t;if(typeof OffscreenCanvas<"u")t=new OffscreenCanvas(r,e);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");t=document.createElement("canvas"),t.width=r,t.height=e}const i=t.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!i)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return lr.length>=Vu&&lr.splice(Bn(lr,n=>n.age),1),lr.push({canvas:t,context:i,age:js++}),{canvas:t,context:i,isNew:!0}};class Li{constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(nr);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);const i=Object.keys(sr);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);const n=Object.keys(ar);if(e.matrix!=null&&!n.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${n.join(", ")}.`);
vendor: 1,354 bytes, line 1
1if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const ur=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,Sn=(r,e,t)=>{const i=Math.min(r.left,e),n=Math.min(r.top,t),s=Math.min(r.width,e-i),a=Math.min(r.height,t-n);return g(s>=0),g(a>=0),{left:i,top:n,width:s,height:a}},li=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Ks=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.colorSpace!==void 0&&!["display-p3","srgb"].includes(r.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'dis
1play-p3' or 'srgb'.");if(r.format!==void 0&&typeof r.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of r.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.rect!==void 0){if(!r.rect||typeof r.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(r.rect.x!==void 0&&(!Number.isInteger(r.rect.x)||r.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(r.rect.y!==void 0&&(!Number.isInteger(r.rect.y)||r.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(r.rect.width!==void 0&&(!Number.isInteger(r.rect.width)||r.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(r.rect.height!==void 0&&(!Number.isInteger(r.rect.height)||r.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Lu=(r,e,t)=>{const i=xi(r),n=[];let s=0;for(const a of i){const o=Math.ceil(e/a.widthDivisor),c=Math.ceil(t/a.heightDivisor),l=o*a.sampleBytes,u=l*c;n.push({offset:s,stride:l}),s+=u}return n},xi=r=>{const e=(t,i,n,s,a)=>{const o=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:i,widthDivisor:n,heightDivisor:s},{sampleBytes:i,widthDivisor:n,heightDivisor:s}];return a&&o.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),o};switch(r){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Fe(r),g(!1)}},Gs=(r,e)=>{const t={left:0,top:0,width:r.codedWidth,height:r.codedHeight},i=e.rect,n=Hu(t,i,r.codedWidth,r.codedHeight,r.format),s=e.layout;let a;if(!e.format||e.format===r.format)a=r.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(e.format))a=e.format;else throw new Error("NotSupportedError: Invalid destination format.");return ju(n,a,s)},Hu=(r,e,t,i,n)=>{const s={...r};if(e!==void 0){if(e.width===0||e.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>t)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>i)throw new TypeError("visibleRect exceeds codedHeight.");s.x=e.x||0,s.y=e.y||0,s.width=e.width||0,s.height=e.height||0}if(!qu(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},qu=(r,e)=>{if(r===null)return!0;const t=xi(r);for(let i=0;i<t.length;i++){const n=t[i],s=n.widthDivisor,a=n.heightDivisor;if((e.x||0)%s!==0||(e.y||0)%a!==0)return!1}return!0},ju=(r,e,t)=>{const i=xi(e),n=i.length;if(t!==void 0&&t.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let s=0;const a=[],o=[];for(let c=0;c<n;c++){const l=i[c],u=l.sampleBytes,d=l.widthDivisor,f=l.heightDivisor,h={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(h.sourceTop=Math.ceil(Math.trunc(r.y||0)/f),h.sourceHeight=Math.ceil(Math.trunc(r.height||0)/f),h.sourceLeftBytes=Math.floor(Math.trunc(r.x||0)/d)*u,h.sourceWidthBytes=Math.floor(Math.trunc(r.width||0)/d)*u,t!==void 0){const y=t[c];if(y.stride<h.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);h.destinationOffset=y.offset,h.destinationStride=y.stride}else h.destinationOffset=s,h.destinationStride=h.sourceWidthBytes;const m=h.destinationStride*h.sourceHeight+h.destinationOffset;if(m>4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(m),s=Math.max(s,m);for(let y=0;y<c;y++){const w=a[y];if(!(o[c]<=w.destinationOffset||o[y]<=h.destinationOffset))throw new TypeError("Planes overlap.")}a.push(h)}return{allocationSize:s,computedLayouts:a}},Hr=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class dr{constructor(){this._referenceCount=0}}class he{get microsecondTimestamp(){return Math.trunc(wt*this.timestamp)}get microsecondDuration(){return Math.trunc(wt*this.duration)}constructor(e){if(this._closed=!1,fr(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else if(e instanceof dr){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!Hr.has(this.format))throw new TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw new TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw new TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw new TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw new TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Hr.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(tt(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let i;if(e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");const n=this.numberOfFrames*this.numberOfChannels*tt(this.format);if(i.byteLength<n)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}Rr?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!Hr.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const t=e.format??this.format,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const n=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(n>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const s=tt(t),a=It(t);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?n:n*this.numberOfChannels)*s}copyTo(e,t){if(!ui(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!Hr.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:i,frameCount:n,frameOffset:s}=t;let{planeIndex:a}=t,o=this.format;const c=i??this.format;if(!c)throw new Error("Destination format not determined");const l=this.numberOfFrames,u=this.numberOfChannels,d=s??0;if(d>=l)throw new RangeError("frameOffset out of range");const f=n!==void 0?n:l-d;if(f>l-d)throw new RangeError("frameCount out of range");const h=tt(c),p=It(c);if(p&&a>=u)throw new RangeError("planeIndex out of range");if(!p&&a!==0)throw new RangeError("planeIndex out of range");const y=(p?f:f*u)*h;if(e.byteLength<y)throw new RangeError("Destination buffer is too small");const w=K(e),k=Eo(c);if(fr(this._data))if(Tr()&&u>2&&c!==o){Ku(this._data,w,o,c,u,a,d,f);return}else try{this._data.copyTo(e,{planeIndex:a,frameOffset:d,frameCount:f,format:c});return}catch(C){if(c==="f32-planar")throw C;o="f32-planar"}const b=Io(o),S=tt(o),T=It(o);let P;if(this._data instanceof dr){const C=x=>{const E=this._data.getDataPlane(x);if(!(E instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const _=l*S*(T?1:u);if(E.byteLength!==_)throw new TypeError(`Data plane ${x}
1 has invalid size. Expected exactly ${_} bytes, got ${E.byteLength} bytes.`);return E};if(T)if(p)P=C(a),a=0;else{P=new Uint8Array(l*S*u);for(let x=0;x<u;x++){const E=C(x);P.set(E,x*l*S)}}else P=C(0)}else if(this._data instanceof Uint8Array)P=this._data;else if(g(o==="f32-planar"),p)P=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:a})),this._data.copyTo(P,{format:"f32-planar",planeIndex:a}),a=0;else{P=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:0})*u);for(let C=0;C<u;C++)this._data.copyTo(P.subarray(C*l*S,(C+1)*l*S),{format:"f32-planar",planeIndex:C})}const I=K(P);for(let C=0;C<f;C++)if(p){const x=C*h;let E;T?E=(a*l+(C+d))*S:E=((C+d)*u+a)*S;const _=b(I,E);k(w,x,_)}else for(let x=0;x<u;x++){const _=(C*u+x)*h;let v;T?v=(x*l+(C+d))*S:v=((C+d)*u+x)*S;const R=b(I,v);k(w,_,R)}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof dr){const e=new he(this._data);return e.setTimestamp(this.timestamp),e}else if(fr(this._data)){const e=new he(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new he({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}trim(e,t=this.numberOfFrames){if(!Number.isInteger(e)||e<0)throw new TypeError("startSample must be a non-negative integer.");if(!Number.isInteger(t)||t<0)throw new TypeError("endSample must be a non-negative integer.");if(e>this.numberOfFrames)throw new RangeError("startSample out of range.");if(t>this.numberOfFrames)throw new RangeError("endSample out of range.");if(t<e)throw new RangeError("endSample must not be less than startSample.");if(this._closed)throw new Error("AudioSample is closed.");const i=t-e,n=tt(this.format);let s;if(It(this.format)){const a=i*n;if(s=new Uint8Array(a*this.numberOfChannels),i>0)for(let o=0;o<this.numberOfChannels;o++)this.copyTo(s.subarray(o*a,(o+1)*a),{planeIndex:o,format:this.format,frameOffset:e,frameCount:i})}else s=new Uint8Array(i*this.numberOfChannels*n),i>0&&this.copyTo(s,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new he({data:s,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(Rr?.unregister(this),this._data instanceof dr?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):fr(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof dr?this._createAudioDataFromData():fr(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(It(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(new Uint8Array(t,i*e,e),{planeIndex:i,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{const e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(t,{planeIndex:i,format:"f32-planar"}
1),e.copyToChannel(t,i);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(i/n);let c=0,l=a;for(;l>0;){const u=Math.min(o,l),d=new Float32Array(n*u);for(let f=0;f<n;f++)e.copyFromChannel(d.subarray(f*u,(f+1)*u),f,c);yield new he({format:"f32-planar",sampleRate:s,numberOfFrames:u,numberOfChannels:n,timestamp:t+c/s,data:d}),c+=u,l-=u}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(i/n);let c=0,l=a;const u=[];for(;l>0;){const d=Math.min(o,l),f=new Float32Array(n*d);for(let p=0;p<n;p++)e.copyFromChannel(f.subarray(p*d,(p+1)*d),p,c);const h=new he({format:"f32-planar",sampleRate:s,numberOfFrames:d,numberOfChannels:n,timestamp:t+c/s,data:f});u.push(h),c+=d,l-=d}return u}}const tt=r=>{switch(r){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},It=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Io=r=>{switch(r){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)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},Eo=r=>{switch(r){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,oe((i+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,oe(Math.round(i*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,oe(Math.round(i*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},fr=r=>typeof AudioData<"u"&&r instanceof AudioData,$u=r=>{switch(r){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return r}},Ku=(r,e,t,i,n,s,a,o)=>{const c=Io(t),l=Eo(i),u=tt(t),d=tt(i),f=It(t);if(It(i))if(f){const p=new ArrayBuffer(o*u),m=K(p);r.copyTo(p,{planeIndex:s,frameOffset:a,frameCount:o,format:t});for(let y=0;y<o;y++){const w=y*u,k=y*d,b=c(m,w);l(e,k,b)}}else{const p=new ArrayBuffer(o*n*u),m=K(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let y=0;y<o;y++){const w=(y*n+s)*u,k=y*d,b=c(m,w);l(e,k,b)}}else if(f){const p=o*u,m=new ArrayBuffer(p),y=K(m);for(let w=0;w<n;w++){r.copyTo(m,{planeIndex:w,frameOffset:a,frameCount:o,format:t});for(let k=0;k<o;k++){const b=k*u,S=(k*n+w)*d,T=c(y,b);l(e,S,T)}}}else{const p=new ArrayBuffer(o*n*u),m=K(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let y=0;y<o;y++)for(let w=0;w<n;w++){const k=y*n+w,b=k*u,S=k*d,T=c(m,b);l(e,S,T)}}},Gu=(r,e)=>{const t=r.allocationSize({format:e,planeIndex:0}),i=new ArrayBuffer(t);return r.copyTo(i,{format:e,planeIndex:0}),new he({data:i,format:e,numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,timestamp:r.timestamp,duration:r.duration})};const Xs=new Map,Qs=new Map,Xu=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!_e.includes(r.codec))throw new TypeError(`Invalid video codec '${r.codec}'. Must be one of: ${_e.join(", ")}.`);const e=r.bitrate;if(r.quality===void 0&&e===void 0)throw new TypeError("config.quality must be provided.");if(r.quality!==void 0&&e!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(r.quality!==void 0&&!(r.quality instanceof le))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof le)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(r.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(r.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.width!==void 0&&(!Number.isInteger(r.transform.width)||r.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(r.transform.height!==void 0&&(!Number.isInteger(r.transform.height)||r.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(r.transform.fit!==void 0&&!["fill","contain","cover"].includes(r.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(r.transform.width!==void 0&&r.transform.height!==void 0&&r.transform.fit===void 0&&!["fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(r.transform.fit!==void 0&&["fill","contain","cover"].includes(r.sizeChangeBehavior)&&r.transform.fit!==r.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(r.transform.rotate!==void 0&&![0,90,180,270].includes(r.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");
vendor: 10,591 bytes, line 1
1if(r.transform.crop!==void 0&&li(r.transform.crop,"config.transform."),r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(r.transform.frameRate!==void 0&&(!Number.isFinite(r.transform.frameRate)||r.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(r.transform.force!==void 0&&typeof r.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");_o(r.codec,r)},_o=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");const t=e.bitrateMode;if(t!==void 0&&!["constant","variable"].includes(t))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&lt(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},vo=r=>{const e=r.bitrateMode,t=r.quality._toVideoRateControl(r.codec,r.width,r.height,e),i=(s,a,o)=>({codec:r.fullCodecString??Yc(r.codec,r.width,r.height,o,r.alpha==="keep"),width:r.width,height:r.height,displayWidth:r.squarePixelWidth,displayHeight:r.squarePixelHeight,bitrate:s,bitrateMode:a,alpha:r.alpha??"discard",framerate:r.framerate,latencyMode:r.latencyMode,hardwareAcceleration:r.hardwareAcceleration,scalabilityMode:r.scalabilityMode,contentHint:r.contentHint,...el(r.codec)}),n=[];return t.quantizer!==null&&n.push({config:i(void 0,"quantizer",t.bitrate),quantizer:t.quantizer}),t.bitrateMode!=="quantizer"&&n.push({config:i(t.bitrate,t.bitrateMode,t.bitrate),quantizer:null}),g(n.length>0),n},Qu=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!Re.includes(r.codec))throw new TypeError(`Invalid audio codec '${r.codec}'. Must be one of: ${Re.join(", ")}.`);const e=r.bitrate;if(r.quality===void 0&&e===void 0&&!(be.includes(r.codec)||r.codec==="flac"))throw new TypeError("config.quality must be provided for compressed audio codecs.");if(r.quality!==void 0&&e!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(r.quality!==void 0&&!(r.quality instanceof le))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof le)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.numberOfChannels!==void 0&&(!Number.isInteger(r.transform.numberOfChannels)||r.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(r.transform.sampleRate!==void 0&&(!Number.isInteger(r.transform.sampleRate)||r.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(r.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(r.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");Ao(r.codec,r)},Ao=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");const t=e.bitrateMode;if(t!==void 0&&!["constant","variable"].includes(t))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&lt(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`)},Bo=r=>{const e=r.bitrateMode;return{codec:r.fullCodecString??Jc(r.codec,r.numberOfChannels,r.sampleRate),numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,bitrate:r.quality?._toAudioBitrate(r.codec),bitrateMode:r.quality?._bitrateMode??e,...tl(r.codec)}};class le{constructor(e){if((typeof e=="number"||typeof e=="string")&&(e={quality:e}),!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("options.bitrateMode, when provided, must be 'constant' or 'variable'.");if("quality"in e){if(typeof e.quality=="string"?!(e.quality in Ys):typeof e.quality!="number"||Number.isNaN(e.quality))throw new TypeError("options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.");if(e.preferBitrate!==void 0&&typeof e.preferBitrate!="boolean")throw new TypeError("options.preferBitrate, when provided, must be a boolean.");if("bitrate"in e||"quantizer"in e)throw new TypeError("options.quality cannot be combined with options.bitrate or options.quantizer.");this._quality=typeof e.quality=="string"?Ys[e.quality]:e.quality,this._preferBitrate=e.preferBitrate??!1,this._bitrate=void 0,this._quantizer=void 0}else{if(e.bitrate!==void 0&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw new TypeError("options.bitrate, when provided, must be a positive integer.");if(e.quantizer!==void 0&&(!Number.isInteger(e.quantizer)||e.quantizer<0))throw new TypeError("options.quantizer, when provided, must be a non-negative integer.");if(e.bitrate===void 0&&e.quantizer===void 0)throw new TypeError("At least one of options.bitrate or options.quantizer must be set.");if("preferBitrate"in e)throw new TypeError("options.preferBitrate can only be combined with options.quality.");this._quality=void 0,this._preferBitrate=!1,this._bitrate=e.bitrate,this._quantizer=e.quantizer}this._bitrateMode=e.bitrateMode}_toVideoRateControl(e,t,i,n){const s=Yu[e];let a=null,o=this._bitrateMode??n??"variable";if(this._quantizer!==void 0){if(s)if(this._quantizer<s.min||this._quantizer>s.max){if(this._bitrate===void 0)throw new Error(`Quantizer ${this._quantizer} is out of range for codec '${e}'; must be between ${s.min} and ${s.max}.`)}else a=this._quantizer,this._bitrate===void 0&&(o="quantizer");else if(this._bitrate===void 0)throw new Error(`Codec '${e}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else this._bitrate===void 0&&s&&!this._preferBitrate&&(g(this._quality!==void 0),a=oe(Math.round(oc(s.worst,s.best,this._quality)),s.min,s.max));let c;if(this._bitrate!==void 0)c=this._bitrate;else{let l=this._quality;l===void 0&&(g(a!==null&&s),l=oe((a-s.worst)/(s.best-s.worst),0,1)),c=Zs(e,t,i,Hi(l))}return{quantizer:a,bitrate:c,bitrateMode:o}}_toVideoBitrate(e,t,i){return this._bitrate!==void 0?this._bitrate:(g(this._quality!==void 0),Zs(e,t,i,Hi(this._quality)))}_toAudioBitrate(e){if(be.includes(e)||e==="flac")return;if(this._bitrate!==void 0)return this._bitrate;if(this._quality===void 0)throw new Error("This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.");const t=Hi(this._quality),n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[e];if(!n)throw new Error(`Unhandled codec: ${e}`);let s=n*t;return e==="aac"?s=[96e3,128e3,16e4,192e3].reduce((o,c)=>Math.abs(c-s)<Math.abs(o-s)?c:o):e==="opus"||e==="vorbis"?s=Math.max(6e3,s):e==="mp3"&&(s=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((o,c)=>Math.abs(c-s)<Math.abs(o-s)?c:o)),Math.round(s/1e3)*1e3}}const Ys={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},Yu={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:{min:0,max:63,worst:52,best:20},av1:{min:0,max:255,worst:208,best:80}},Hi=r=>.3*Math.exp(2.5538*r),Zs=(r,e,t,i)=>{const n=e*t,s=1920*1080,a=3e6,o=Math.pow(n/s,.95),c=a*o,l={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/a},d=c*l[r]*i;return Math.ceil(d/1e3)*1e3},Fo=(r,e)=>{if(r==="avc")return{avc:{quantizer:e}};if(r==="hevc")return{hevc:{quantizer:e}};if(r==="vp9")return{vp9:{quantizer:e}};if(r==="av1")return{av1:{quantizer:e}};g(!1)},Zu=async(r,e={})=>{const{width:t=1280,height:i=720,quality:n,bitrate:s,...a}=e;if(!_e.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("height must be a positive integer.");if(n!==void 0&&!(n instanceof le))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&s!==void 0)throw new TypeError("quality and bitrate c
1annot both be provided.");if(s!==void 0&&!(s instanceof le)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer or a quality.");_o(r,a);const o=rr(n,s)??new le("medium");let c;try{c=vo({codec:r,width:t,height:i,quality:o,framerate:void 0,...a,alpha:"discard"})}catch{return!1}const l=JSON.stringify(c),u=Xs.get(l);if(u)return u;const d=(async()=>{for(const{config:h}of c)if(zo.some(p=>p.supports(r,h)))return!0;if(typeof VideoEncoder>"u"||(t%2===1||i%2===1)&&(r==="avc"||r==="hevc"))return!1;for(const{config:h,quantizer:p}of c){try{if(!(await VideoEncoder.isConfigSupported(h)).supported)continue}catch{continue}if(!ba()||await new Promise(async y=>{try{const w=new VideoEncoder({output:()=>{},error:()=>y(!1)});w.configure(h);const k=new Uint8Array(t*i*4),b=new VideoFrame(k,{format:"RGBA",codedWidth:t,codedHeight:i,timestamp:0});w.encode(b,p!==null?Fo(r,p):void 0),b.close(),await w.flush(),y(!0)}catch{y(!1)}}))return!0}return!1})();return Xs.set(l,d),d},Ju=async(r,e={})=>{const{numberOfChannels:t=2,sampleRate:i=48e3,quality:n,bitrate:s,...a}=e;if(!Re.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("sampleRate must be a positive integer.");if(n!==void 0&&!(n instanceof le))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&s!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(s!==void 0&&!(s instanceof le)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer.");Ao(r,a);const o=rr(n,s)??new le("medium"),c=Bo({codec:r,numberOfChannels:t,sampleRate:i,quality:o,...a}),l=JSON.stringify(c),u=Qs.get(l);if(u)return u;const d=(async()=>{if(Oo.some(f=>f.supports(r,c))||be.includes(r))return!0;if(typeof AudioEncoder>"u")return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return Qs.set(l,d),d},rr=(r,e)=>{if(r!==void 0)return r;if(e!==void 0)return e instanceof le?e:new le({bitrate:e})},Js=async(r=Re,e)=>{const t=await Promise.all(r.map(i=>Ju(i,e)));return r.filter((i,n)=>t[n])},ed=async(r,e)=>{for(const t of r)if(await Zu(t,e))return t;return null};const Ro=[],Mo=[],zo=[],Oo=[];const td=r=>{let i=r,n=4096,s=0,a=12,o=0;for(i<0&&(i=-i,s=128),i+=33,i>8191&&(i=8191);(i&n)!==n&&a>=5;)n>>=1,a--;return o=i>>a-4&15,~(s|a-5<<4|o)&255},rd=r=>{let t=0,i=0,n=~r;n&128&&(n&=-129,t=-1),i=((n&240)>>4)+5;const s=(1<<i|(n&15)<<i-4|1<<i-5)-33;return t===0?s:-s},id=r=>{let t=2048,i=0,n=11,s=0,a=r;for(a<0&&(a=-a,i=128),a>4095&&(a=4095);(a&t)!==t&&n>=5;)t>>=1,n--;return s=a>>(n===4?1:n-4)&15,(i|n-4<<4|s)^85},nd=r=>{let e=0,t=0,i=r^85;i&128&&(i&=-129,e=-1),t=((i&240)>>4)+4;let n=0;return t!==4?n=1<<t|(i&15)<<t-4|1<<t-5:n=i<<1|1,e===0?n:-n};const Pt=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.metadataOnly!==void 0&&typeof r.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(r.verifyKeyPackets!==void 0&&typeof r.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(r.verifyKeyPackets&&r.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(r.skipLiveWait!==void 0&&typeof r.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},zt=r=>{if(!zr(r))throw new TypeError("timestamp must be a number.")},qi=(r,e,t)=>t.verifyKeyPackets?e.then(async i=>{if(!i||i.type==="delta")return i;const n=await r.determinePacketType(i);return n&&(i.type=n),i}):e;class ir{constructor(e){if(!(e instanceof Wr))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(Pt(e),this._track.input._disposed)throw new ge;return qi(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Pt(e);const t=await this.getFirstPacket(e);return t?t.type==="key"?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(zt(e),Pt(t),this._track.input._disposed)throw new ge;return qi(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof Z))throw new TypeError("packet must be an EncodedPacket.");if(Pt(t),this._track.input._disposed)throw new ge;return qi(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(zt(e),Pt(t),this._track.input._disposed)throw new ge;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=await this._track._backing.getKeyPacket(e,t);
1return i&&(g(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getKeyPacket(i.timestamp-1/await this._track.getTimeResolution(),t):i)}async getNextKeyPacket(e,t={}){if(!(e instanceof Z))throw new TypeError("packet must be an EncodedPacket.");if(Pt(t),this._track.input._disposed)throw new ge;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=await this._track._backing.getNextKeyPacket(e,t);return i&&(g(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getNextKeyPacket(i,t):i)}packets(e,t,i={}){if(e!==void 0&&!(e instanceof Z))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!i?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof Z))throw new TypeError("endPacket must be an EncodedPacket.");if(Pt(i),this._track.input._disposed)throw new ge;const n=[];let{promise:s,resolve:a}=se(),{promise:o,resolve:c}=se(),l=!1,u=!1,d=null,f=!1;const h=[],p=()=>Math.max(2,h.length);(async()=>{let y=e??await this.getFirstPacket(i);for(;y&&!u&&!this._track.input._disposed&&!(t&&y.sequenceNumber>=t?.sequenceNumber);){if(n.length>p()){({promise:o,resolve:c}=se()),await o;continue}n.push(y),a(),{promise:s,resolve:a}=se(),y=await this.getNextPacket(y,i)}l=!0,a()})().catch(y=>{f||(d=y,f=!0,a())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new ge;if(u)return{value:void 0,done:!0};if(f)throw d;if(n.length>0){const y=n.shift(),w=performance.now();for(h.push(w);h.length>0&&w-h[0]>=1e3;)h.shift();return c(),{value:y,done:!1}}else{if(l)return{value:void 0,done:!0};await s}}},async return(){return u=!0,c(),a(),{value:void 0,done:!0}},async throw(y){throw y},[Symbol.asyncIterator](){return this}}}}class jn{constructor(e,t){this.onSample=e,this.onError=t}}class Do{mediaSamplesInRange(e=-1/0,t=1/0,i){zt(e),zt(t);const n=[];let s=!1,a=null,{promise:o,resolve:c}=se(),{promise:l,resolve:u}=se(),d=!1,f=!1,h=!1,p=null,m=null,y=!1;const w={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=await this._createDecoder(x=>{if(u(),x.timestamp>=t&&(f=!0),f){x.close();return}a&&(x.timestamp>e?(n.push(a),s=!0):a.close()),x.timestamp>=e&&(n.push(x),s=!0),a=s?null:x,n.length>0&&(c(),{promise:o,resolve:c}=se())},x=>{y||(m=x,y=!0,c())});const S=this._createPacketSink(),T=await S.getKeyPacket(e,w)??await S.getFirstKeyPacket(w);let P=T;const C=S.packets(T??void 0,void 0,w);for(await C.next();P&&!f&&!this._track.input._disposed;){const x=ea(n.length);if(n.length+p.getDecodeQueueSize()>x){({promise:l,resolve:u}=se()),await l;continue}p.decode(P);const E=await C.next();if(E.done)break;P=E.value}await C.return(),!h&&!this._track.input._disposed&&await p.flush(),!s&&a&&n.push(a),d=!0,c()})().catch(S=>{y||(m=S,y=!0,c())}).finally(()=>{p?.close()});const k=this._track,b=()=>{a?.close();for(const S of n)S.close()};return{async next(){for(;;){if(k.input._disposed)throw h=!0,f=!0,b(),new ge;if(h)return{value:void 0,done:!0};if(y)throw h=!0,f=!0,b(),m;if(n.length>0){const S=n.shift();return u(),{value:S,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return h=!0,f=!0,u(),c(),b(),{value:void 0,done:!0}},async throw(S){throw S},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){nc(e);const i=ic(e),n=[],s=[];let{promise:a,resolve:o}=se(),{promise:c,resolve:l}=se(),u=!1,d=!1,f=null,h=null,p=!1;const m=b=>{s.push(b),o(),{promise:a,resolve:o}=se()},y={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=await this._createDecoder(x=>{if(l(),d){x.close();return}let E=0;for(;n.length>0&&x.timestamp-n[0]>-1e-10;)E++,n.shift();if(E>0)for(let _=0;_<E;_++)m(_<E-1?x.clone():x);else x.close()},x=>{p||(h=x,p=!0,o())});const b=this._createPacketSink();let S=null,T=null,P=-1;const I=async()=>{g(T),g(f);let x=T;for(f.decode(x);x.sequenceNumber<P;){const E=ea(s.length);for(;s.length+f.getDecodeQueueSize()>E&&!d;)({promise:c,resolve:l}=se()),await c;if(d)break;const _=await b.getNextPacket(x,y);g(_),f.decode(_),x=_}P=-1},C=async()=>{g(f),await f.flush();for(let x=0;x<n.length;x++)m(null);n.length=0};for await(const x of i){if(zt(x),d||this._track.input._disposed)break;const E=await b.getPacket(x,y),_=E&&await b.getKeyPacket(x,y);if(!_){P!==-1&&(await I(),await C()),m(null),S=null;continue}S&&(_.sequenceNumber!==T.sequenceNumber||E.timestamp<S.timestamp)&&(await I(),await C()),n.push(E.timestamp),P=Math.max(E.sequenceNumber,P),S=E,T=_}!d&&!this._track.input._disposed&&(P!==-1&&await I(),await C()),u=!0,o()})().catch(b=>{p||(h=b,p=!0,o())}).finally(()=>{f?.close()});const w=this._track,k=()=>{for(const b of s)b?.close()};return{async next(){for(;;){if(w.input._disposed)throw d=!0,k(),new ge;if(d)return{value:void 0,done:!0};if(p)throw d=!0,k(),h;if(s.length>0){const b=s.shift();return g(b!==void 0),l(),{value:b,done:!1}}else if(!u)await a;else return{value:void 0,done:!0}}},async return(){return d=!0,l(),o(),k(),{value:void 0,done:!0}},async throw(b){throw b},[Symbol.asyncIterator](){return this}}}}const ea=r=>r===0?40:8;class sd extends jn{constructor(e,t,i,n,s,a){super(e,t),this.codec=i,this.decoderConfig=n,this.rotation=s,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer
1=new fi,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.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];const o=Ro.find(c=>c.supports(i,n));if(o)this.customDecoder=new o,this.customDecoder.codec=i,this.customDecoder.config=n,this.customDecoder.onSample=c=>{if(!(c instanceof pe))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoder.onError=c=>{t(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(c=>t(c));else{const c=u=>{if(this.alphaQueue.length>0){const d=this.alphaQueue.shift();g(d!==void 0),this.mergeAlpha(u,d)}else this.colorQueue.push(u)};if(ln()){if(i==="avc"&&this.decoderConfig.description){const u=Aa(ke(this.decoderConfig.description));if(u&&u.sequenceParameterSets.length>0){const d=wi(u.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}En(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??"bt709",matrix:this.decoderConfig.colorSpace?.matrix??"bt709",transfer:this.decoderConfig.colorSpace?.transfer??"bt709",fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}const l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:u=>{try{c(u)}catch(d){this.onError(d)}},error:u=>{u.stack=l,this.onError(u)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(g(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>
10&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(t=>this.onError(t)).finally(()=>this.customDecoderQueueSize--);else{if(g(this.decoder),Tr()||ts(this.inputTimestamps,e.timestamp,t=>t),ln()&&this.currentPacketIndex===0){if(this.codec==="avc"){const t=[];let i=!1;for(const s of _a(e.data,this.decoderConfig)){const a=pi(e.data[s.offset]);if(i||=a>=1&&a<=5,a===fe.AUD){if(i)break;t.length=0}a>=20&&a<=31||t.push(e.data.subarray(s.offset,s.offset+s.length))}const n=pc(t,this.decoderConfig);e=new Z(n,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){const t=Ic(e.data,this.decoderConfig);t&&(e=new Z(t,e.type,e.timestamp,e.duration))}}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||(this.merger=new ad),!this.alphaDecoder){const i=s=>{if(this.colorQueue.length>0){const a=this.colorQueue.shift();g(a!==void 0),this.mergeAlpha(a,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const a=this.colorQueue.shift();g(a!==void 0),this.mergeAlpha(a,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},n=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{i(s)}catch(a){this.onError(a)}},error:s=>{s.stack=n,this.onError(s)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=bi(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=t==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>
10&&!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(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const t of ti(e,this.decoderConfig)){const i=tr(e[t.offset]);if(i===ce.RASL_N||i===ce.RASL_R)return!0}return!1}sampleHandler(e){if(Tr()){if(this.sampleQueue.length>0&&e.timestamp>=re(this.sampleQueue).timestamp){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}ts(this.sampleQueue,e,t=>t.timestamp)}else{const t=this.inputTimestamps.shift();g(t!==void 0),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)}async mergeAlpha(e,t){const i=se();this.mergeAlphaPromises.push(i.promise);const n={sample:null};this.finalSamples.push(n);try{if(!t)n.sample=new pe(e);else{g(this.merger);const s=await this.merger.merge(e,t);n.sample=new pe(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){const s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){an(this.finalSamples,n),this.onError(s)}finally{an(this.mergeAlphaPromises,i.promise),i.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(g(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),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),Tr()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(g(this.decoder),this.decoder.state!=="closed"&&this.decoder.close(),this.alphaDecoder&&this.alphaDecoder.state!=="closed"&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}}let ji=null;class ad{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(this.workers.length===0){if(!ji){const o=new Blob([`(${od.toString()})()`],{type:"application/javascript"});ji=URL.createObjectURL(o)}const a=oe(navigator.hardwareConcurrency,1,4);for(let o=0;o<a;o++){const c=new Worker(ji);c.addEventListener("message",l=>{const u=l.data,d=this.pendingRequests.get(u.id);d&&(this.pendingRequests.delete(u.id),"error"in u?d.reject(new Error(u.error)):d.resolve(u.frame))}),c.addEventListener("error",l=>{const u=new Error(l.message||"Color/alpha merge worker error.");for(const d of this.pendingRequests.values())d.reject(u);this.pendingRequests.clear()}),this.workers.push(c)}}const i=this.nextRequestId++,n=se();this.pendingRequests.set(i,n);const s=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,s.postMessage({id:i,color:e,alpha:t},{transfer:[e,t]}),n.promise}close(){for(const t of this.workers)t.terminate();this.workers.length=0;const e=new Error("Color/alpha merger closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}const od=()=>{let r=null,e=null,t=Promise.resolve();self.addEventListener("message",c=>{const{id:l,color:u,alpha:d}=c.data;t=t.then(async()=>{try{const f=await i(u,d);self.postMessage({id:l,frame:f},{transfer:[f]})}catch(f){self.postMessage({id:l,error:f.message})}finally{u.close(),d.close()}})});const i=async(c,l)=>{const u=c.format,d=l.format;if(!u||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const f=u.includes("P10"),h=u.includes("P12"),p=d.includes("P10"),m=d.includes("P12");
1if(p!==f||m!==h)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${u}', alpha: '${d}').`);if(u==="RGBX"||u==="RGBA"||u==="BGRX"||u==="BGRA")return await n(c,l,u);if(u==="I420"||u==="I420P10"||u==="I420P12"||u==="I422"||u==="I422P10"||u==="I422P12"||u==="I444"||u==="I444P10"||u==="I444P12")return await s(c,l,u);if(u==="NV12")return await a(c,l);throw new Error(`CPU color/alpha merging does not support format '${u}'.`)},n=async(c,l,u)=>{const d=c.visibleRect?.width??c.codedWidth,f=c.visibleRect?.height??c.codedHeight,h=d*f,p=new Uint8Array(h*4);await c.copyTo(p);const m=await o(l,d,f,1);for(let k=0,b=3;k<h;k++,b+=4)p[b]=m[k];const w={format:u==="RGBX"||u==="RGBA"?"RGBA":"BGRA",codedWidth:d,codedHeight:f,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[p.buffer]};return new VideoFrame(p,w)},s=async(c,l,u)=>{const d=c.visibleRect?.width??c.codedWidth,f=c.visibleRect?.height??c.codedHeight,h=u.includes("P10"),p=u.includes("P12"),m=h||p?2:1;let y,w;u.startsWith("I420")?(y=Math.ceil(d/2),w=Math.ceil(f/2)):u.startsWith("I422")?(y=Math.ceil(d/2),w=f):(y=d,w=f);const k=d*f,b=y*w,S=k*m,T=b*m,P=k*m,I=S+2*T+P,C=new Uint8Array(I);await c.copyTo(C);const x=await o(l,d,f,m),E=S+2*T;C.set(x,E);const v={format:u.slice(0,4)+"A"+u.slice(4),codedWidth:d,codedHeight:f,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[C.buffer]};return new VideoFrame(C,v)},a=async(c,l)=>{const u=c.visibleRect?.width??c.codedWidth,d=c.visibleRect?.height??c.codedHeight,f=u*d,h=Math.ceil(u/2),p=Math.ceil(d/2),m=h*p,y=c.allocationSize();(!e||e.byteLength!==y)&&(e=new Uint8Array(y)),await c.copyTo(e);const w=new Uint8Array(f+2*m+f);w.set(e.subarray(0,f),0);const k=f,b=f+m,S=f;for(let I=0;I<m;I++)w[k+I]=e[S+I*2],w[b+I]=e[S+I*2+1];const T=await o(l,u,d,1);w.set(T,f+2*m);const P={format:"I420A",codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[w.buffer]};return new VideoFrame(w,P)},o=async(c,l,u,d)=>{const f=c.allocationSize();(!r||r.byteLength!==f)&&(r=new Uint8Array(f)),await c.copyTo(r);const h=c.format;if(h==="RGBA"||h==="BGRA"||h==="RGBX"||h==="BGRX"){const p=h==="RGBA"||h==="RGBX"?0:2,m=l*u;for(let y=0;y<m;y++)r[y]=r[y*4+p];return r.subarray(0,m)}else return r.subarray(0,l*u*d)}},cd=r=>{if(!r||typeof r!="object")throw new TypeError("decoderOptions must be an object.");if(r.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(r.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(r.optimizeForLatency!==void 0&&typeof r.optimizeForLatency!="boolean")throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class ta extends Do{constructor(e,t={}){if(!(e instanceof $n))throw new TypeError("videoTrack must be an InputVideoTrack.");cd(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(hi("VideoDecoder")):new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.");const i=await this._track.getCodec(),n=await this._track.getRotation();let s=await this._track.getDecoderConfig();const a=await this._track.getTimeResolution();return g(i&&s),s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new sd(e,t,i,s,n,a)}_createPacketSink(){return new ir(this._track)}async getSample(e,t={}){zt(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class ld extends jn{constructor(e,t,i,n){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new fi,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const s=o=>{let c=o.timestamp;this.expectedFirstTimestamp!==null&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp-c),c+=this.timestampOffset,(this.currentTimestamp===null||Math.abs(c-this.currentTimestamp)>=o.duration)&&(this.currentTimestamp=c);const l=this.currentTimestamp;if(this.currentTimestamp+=o.duration,o.numberOfFrames===0){o.close();return}const u=n.sampleRate;o.setTimestamp(Math.round(l*u)/u),e(o)},a=Mo.find(o=>o.supports(i,n));if(a)this.customDecoder=new a,this.customDecoder.codec=i,this.customDecoder.config=n,this.customDecoder.onSample=o=>{if(!(o instanceof he))throw new TypeError("The argument passed to onSample must be an AudioSample.");s(o)},this.customDecoder.onError=o=>{t(o)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(o=>t(o));else{const o=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:c=>{try{s(new he(c))}catch(l){this.onError(l)}},error:c=>{c.stack=o,this.onError(c)}}),this.decoder.configure(n)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(g(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(t=>this.onError(t)).finally(()=>this.customDecoderQueueSize--)):(g(this.decoder),this.expectedFirstTimestamp??=e.timestamp,this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(g(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(g(this.decoder),this.decoder.state!=="closed"&&this.decoder.close())}}class ud extends jn{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,g(be.includes(i.codec)),this.codec=i.codec;const{dataType:n,sampleSize:s,littleEndian:a}=ut(this.codec);switch(this.inputSampleSize=s,s){case 1:n==="unsigned"?this.readInputValue=(o,c)=>o.getUint8(c)-2**7:n==="signed"?this.readInputValue=(o,c)=>o.getInt8(c):n==="ulaw"?this.readInputValue=(o,c)=>rd(o.getUint8(c)):n==="alaw"?this.readInputValue=(o,c)=>nd(o.getUint8(c)):g(!1);break;case 2:n==="unsigned"?this.readInputValue=(o,c)=>o.getUint16(c,a)-2**15:n==="signed"?this.readInputValue=(o,c)=>o.getInt16(c,a):g(!1);break;case 3:n==="unsigned"?this.readInputValue=(o,c)=>di(o,c,a)-2**23:n==="signed"?this.readInputValue=(o,c)=>sc(o,c,a):g(!1);break;case 4:n==="unsigned"?this.readInputValue=(o,c)=>o.getUint32(c,a)-2**31:n==="signed"?this.readInputValue=(o,c)=>o.getInt32(c,a):n==="float"?this.readInputValue=(o,c)=>o.getFloat32(c,a):g(!1);break;case 8:n==="float"?this.readInputValue=(o,c)=>o.getFloat64(c,a):g(!1);break;default:Fe(s),g(!1)}switch(s){case 1:n==="ulaw"||n==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(o,c,l)=>o.setInt16(c,l,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(o,c,l)=>
1o.setUint8(c,l+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(o,c,l)=>o.setInt16(c,l,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(o,c,l)=>o.setInt32(c,l<<8,!0);break;case 4:this.outputSampleSize=4,n==="float"?(this.outputFormat="f32",this.writeOutputValue=(o,c,l)=>o.setFloat32(c,l,!0)):(this.outputFormat="s32",this.writeOutputValue=(o,c,l)=>o.setInt32(c,l,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(o,c,l)=>o.setFloat32(c,l,!0);break;default:Fe(s),g(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=K(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,n=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(n),a=new DataView(s);for(let u=0;u<i*this.decoderConfig.numberOfChannels;u++){const d=u*this.inputSampleSize,f=u*this.outputSampleSize,h=this.readInputValue(t,d);this.writeOutputValue(a,f,h)}const o=i/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=o)&&(this.currentTimestamp=e.timestamp);const c=this.currentTimestamp;this.currentTimestamp+=o;const l=new he({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:c});this.onSample(l)}async flush(){}close(){}}class dd extends Do{constructor(e){if(!(e instanceof Kn))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw typeof AudioDecoder>"u"?new Error(hi("AudioDecoder")):new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.");const i=await this._track.getCodec(),n=await this._track.getDecoderConfig();return g(i&&n),be.includes(n.codec)?new ud(e,t,n):new ld(e,t,i,n)}_createPacketSink(){return new ir(this._track)}async getSample(e,t={}){zt(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Wr{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof $n}isAudioTrack(){return this instanceof Kn}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return ee(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return ee(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return ee(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return ee(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return ee(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(e){const t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e}),i=(t?.timestamp??0)+(t?.duration??0);return ei(i,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){const i=new ir(this);let n=1/0,s=-1/0,a=0,o=0;for await(const c of i.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&c.timestamp>=s)break;n=Math.min(n,c.timestamp),s=Math.max(s,c.timestamp+c.duration),a++,o+=c.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(s-n)).toPrecision(16)):0,averageBitrate:a?
1Number((8*o/(s-n)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof Wr))throw new TypeError("other must be an InputTrack.");return this.input!==e.input||this===e?!1:(this._backing.getPairingMask()&e._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(Et({filter:t=>t.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(Et({filter:t=>t.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(Et({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(Et({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(Et({filter:t=>t.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=$i(e);const t=await this.input.getTracks();for(const i of t)if(this.canBePairedWith(i)&&(!e||await e(i)))return!0;return!1}hasPairableVideoTrack(e){return e&&=$i(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=$i(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const ee=(r,e,t)=>{if(A(r))throw new Error(`'${e}' is deprecated and not available synchronously for this track. Use the preferred '${t}()' instead.`);return r},$i=r=>{if(r!==void 0&&typeof r!="function")throw new TypeError("predicate, when provided, must be a function.");return r?e=>{const t=n=>{if(typeof n!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return n},i=r(e);return A(i)?i.then(t):t(i)}:void 0};class $n extends Wr{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return ee(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()==="prores"}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return ee(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return ee(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return ee(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return ee(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return ee(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=vr({num:await this.get
1SquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=vr({num:ee(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*ee(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:ee(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*ee(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}async getDisplayWidth(){const e=await this._backing.getMetadataDisplayWidth?.();return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){const e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){const n=ee(e,"displayWidth","getDisplayWidth");if(n!==null)return n}const i=ee(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return ee(i,"displayWidth","getDisplayWidth")}async getDisplayHeight(){const e=await this._backing.getMetadataDisplayHeight?.();return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){const e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){const n=ee(e,"displayHeight","getDisplayHeight");if(n!==null)return n}const i=ee(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return ee(i,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pq"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}
1async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();return g(t!==null),Ro.some(n=>n.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return H._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Z))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const t=await this.getCodec();if(t===null)return null;const i=await this.getDecoderConfig();return g(i),bi(t,i,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.targetPacketCount!==void 0&&(!zr(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");const t=await this.getTimeResolution(),i=e.targetPacketCount??256,n=new ir(this),s=[];let a=-1/0,o=0;for await(const E of n.packets(void 0,void 0,{metadataOnly:!0})){if(s.length>=i&&E.timestamp>=a)break;s.push(E.timestamp),a=Math.max(a,E.timestamp),o++}const c=new Float64Array(s.length);for(let E=0;E<s.length;E++)c[E]=Math.round(s[E]*t);c.sort();let l=1;for(let E=1;E<c.length;E++)c[E]!==c[l-1]&&(c[l++]=c[E]);if(l<2)return{underlyingFrameRate:null,bestGuessFrameRate:t,minFrameRate:t,maxFrameRate:t,averageFrameRate:t,medianFrameRate:t,frameRateIsConstant:!0,probedPacketCount:o};const u=c.subarray(0,l),d=fd(u,t),f=d??t,h=d!==null?t/d:null,p=new Map;let m=1/0,y=-1/0,w=0;for(let E=1;E<l;E++){const _=u[E]-u[E-1],v=h!==null?Math.max(1,Math.round(_/h)):_;p.set(v,(p.get(v)??0)+1),m=Math.min(m,v),y=Math.max(y,v),w+=v}const k=l-1,b=[...p.keys()].sort((E,_)=>E-_),S=k-1>>1,T=k>>1;let P=0,I=0,C=0;for(const E of b)if(C+=p.get(E),P===0&&C>S&&(P=E),C>T){I=E;break}const x=(f/P+f/I)/2;return{underlyingFrameRate:d,bestGuessFrameRate:d!==null?d:hd(x),minFrameRate:f/y,maxFrameRate:f/m,averageFrameRate:f*k/w,medianFrameRate:x,frameRateIsConstant:d!==null&&m===1&&y===1,probedPacketCount:o}}}class Kn extends Wr{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return ee(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return ee(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return ee(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();return g(t!==null),Mo.some(i=>i.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return H._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Z))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}}const ra=r=>-(r??-1/0),hr=r=>-r,mr=r=>{if(typeof r!="object"||!r)throw new TypeError("query must be an object.");if(r.filter!==void 0&&typeof r.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(r.sortBy!==void 0&&typeof r.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:r.filter?e=>{const t=n=>{if(typeof n!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return n},i=r.filter(e);return A(i)?i.then(t):t(i)}:void 0,sortBy:r.sortBy?e=>{const t=n=>
1{if(typeof n!="number"&&(!Array.isArray(n)||!n.every(s=>typeof s=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return n},i=r.sortBy(e);return A(i)?i.then(t):t(i)}:void 0}},Et=(r,e)=>({filter:r?.filter||e?.filter?t=>{const i=r?.filter?.(t)??!0,n=s=>s===!1?!1:e?.filter?.(t)??!0;return A(i)?i.then(n):n(i)}:void 0,sortBy:r?.sortBy||e?.sortBy?t=>{const i=r?.sortBy?.(t)??[],n=e?.sortBy?.(t)??[],s=(a,o)=>[...Array.isArray(a)?a:[a],...Array.isArray(o)?o:[o]];return A(i)||A(n)?Promise.all([i,n]).then(([a,o])=>s(a,o)):s(i,n)}:void 0}),Ki=async(r,e)=>{let t=r;if(e?.filter){const a=r.map(c=>e.filter(c));if(a.some(c=>A(c))){const c=await Promise.all(a);t=r.filter((l,u)=>c[u])}else t=r.filter((c,l)=>a[l])}if(!e?.sortBy)return t;const i=t.map(a=>e.sortBy(a)),s=i.some(a=>A(a))?await Promise.all(i):i;return t.map((a,o)=>({track:a,sortValue:s[o]})).sort((a,o)=>{const c=Array.isArray(a.sortValue)?a.sortValue:[a.sortValue],l=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],u=Math.max(c.length,l.length);for(let d=0;d<u;d++){const f=c[d]??0,h=l[d]??0;if(f!==h)return f-h}return 0}).map(a=>a.track)},fd=(r,e)=>{const n=1.000000001,s=1e3,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(r.length<2)return null;const o=new Float64Array(r.length-1);for(let I=1;I<r.length;I++){const C=r[I]-r[I-1];if(!(C>0))return null;o[I-1]=C}const c=o.slice();c.sort();let l=c[Math.floor(c.length*.05)];for(let I=0;I<6;I++){let C=0,x=0;for(const _ of o){const v=Math.max(1,Math.round(_/l));Math.abs(_-v*l)>=n||(C+=_,x+=v)}if(x===0)return null;const E=C/x;if(Math.abs(E-l)<=1e-12*Math.max(1,l)){l=E;break}l=E}let u=0,d=0,f=0;for(const I of o){const C=Math.max(1,Math.round(I/l));Math.abs(I-C*l)>=n||(u++,d+=I,f+=C)}if(u/o.length<.98)return null;l=d/f;const h=1/Math.min(f,s),p=Math.max(Number.EPSILON,l-h),m=l+h,y=e/m,w=e/p,k=e/l;let b=null,S=1/0;for(const I of a){if(I<y||I>w)continue;const C=Math.abs(I/k-1);C<S&&(b=I,S=C)}if(b===null){const I=ia(p,m,1e6),C=ia(y,w,1e6);if(C&&(!I||C.den<I.den||C.den===I.den&&C.num<=I.num))b=C.num/C.den;else if(I)b=e*I.den/I.num;else return null}const T=e/b;let P=0;for(const I of o){const C=Math.max(1,Math.round(I/T));Math.abs(I-C*T)<n&&P++}return P/o.length<.98?null:b},ia=(r,e,t)=>{for(let i=1;i<=t;i++){const n=Math.floor(r*i)+1;if(n/i<e)return vr({num:n,den:i})}return null},hd=r=>{const e=[23.976023976023978,29.970029970029973,59.940059940059946,119.88011988011989],t=[12,15,20,24,25,30,48,50,60,100,120,144,240],i=5e-4,n=.025;for(const o of e)if(Math.abs(o/r-1)<=i)return o;let s=r,a=1/0;for(const o of t){const c=Math.abs(o/r-1);c<=n&&c<a&&(s=o,a=c)}return s};An();const md=1,pd=2;class Pi extends Or{get disposed(){return this._disposed}constructor(e){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(t=>!(t instanceof Qe)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Ge||e.source instanceof qn))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof Ge&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof Pi))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&Ou(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof Ge?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){g(this._rootSource instanceof Ur);const t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=md){const i=this._sourceCache.find(a=>a.cacheGroup===t&&Os(a.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const n=this._sourceCachePromises.find(a=>a.cacheGroup===t&&Os(a.request,e));if(n)return n.promise.then(a=>a.sourceRef.source.ref());const s=(async()=>{const a=await this._getSourceUncached(e);if(wr(this._sourceCache,d=>d.cacheGroup===t&&d.sourceRef.source._refCount===1)>=4){const d=Bn(this._sourceCache,h=>h.cacheGroup===t&&h.sourceRef.source._refCount===1?h.age:1/0);g(d!==-1);const f=this._sourceCache[d];this._sourceCache.splice(d,1),f.sourceRef.free(),an(this._sourceRefs,f.sourceRef)}this._sourceRefs.push(a);const l=this._sourceCachePromises.findIndex(d=>d.request===e);return g(l!==-1),this._sourceCachePromises.splice(l,1),{request:e,sourceRef:a,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:s}),s.then(a=>{const o=a.sourceRef.source.ref();return this._sourceCache.push(a),o})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new Zr(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});
1for(const e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new na})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),g(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof na)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();const t=e.filter(s=>s!==null);if(t.length===0)return 0;const i=await Promise.all(t.map(s=>s._backing.getFirstPacket({metadataOnly:!0}))),n=Math.min(...i.map(s=>s?.timestamp??1/0));return n===1/0?0:n}async computeDuration(e,t){e??=await this.getTracks();const i=e.filter(s=>s!==null);if(i.length===0)return 0;const n=await Promise.all(i.map(s=>s.computeDuration(t)));return Math.max(...n)}async getDurationFromMetadata(e,t){e??=await this.getTracks();const i=e.filter(a=>a!==null),s=(await Promise.all(i.map(a=>a.getDurationFromMetadata(t)))).filter(a=>a!==null);return s.length===0?null:Math.max(...s)}async getTracks(e){e&&=mr(e);const i=(await this._getTrackBackings()).map(n=>this._wrapBackingAsTrack(n));return Ki(i,e)}async getVideoTracks(e){e&&=mr(e);const i=(await this.getTracks()).filter(n=>n.isVideoTrack());return Ki(i,e)}async getAudioTracks(e){e&&=mr(e);const i=(await this.getTracks()).filter(n=>n.isAudioTrack());return Ki(i,e)}async getPrimaryVideoTrack(e){e&&=mr(e);const t=Et(e,{sortBy:async n=>[hr((await n.getDisposition()).default),hr(await n.hasPairableAudioTrack()),hr(!await n.hasOnlyKeyPackets()),ra(await n.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=mr(e);const t=await this.getPrimaryVideoTrack(),i=Et(e,{sortBy:async s=>[hr(!t||s.canBePairedWith(t)),hr((await s.getDisposition()).default),ra(await s.getBitrate())]});return(await this.getAudioTracks(i))[0]??null}async _getTrackBackings(){const e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const n=e.getType()==="video"?new $n(this,e):new Kn(this,e);return this._backingToTrack.set(e,n),n}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class na extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class ge extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class Zr{constructor(e){this.source=e}get fileSize(){const e=this.source._getFileSize();if(e===void 0)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new ge;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){const s=new Uint8Array(0);return new Ee(s,K(s),0,e,e)}const i=e+t,n=this.source._read(e,i,wo,ko);return A(n)?n.then(s=>s?new Ee(s.bytes,s.view,s.offset,e,i):null):n?new Ee(n.bytes,n.view,n.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new ge;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,oe(this.fileSizeNonStrict-e,t,i));{const n=this.requestSlice(e,i),s=a=>a||(g(this.fileSizeNonStrict!==null),this.requestSlice(e,oe(this.fileSizeNonStrict-e,t,i)));return A(n)?n.then(s):s(n)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);const e=1024;return(async()=>{const t=[];let i=0;for(;;){if(t.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let a=this.requestSliceRange(i,0,e);if(A(a)&&(a=await a),!a||a.length===0)break;const o=W(a,a.length);t.push(o),i+=a.length}const n=new Uint8Array(i);let s=0;for(const a of t)n.set(a,s),s+=a.length;return new Ee(n,K(n),0,0,i)})()}}class Ee{constructor(e,t,i,n,s){this.bytes=e,this.view=t,this.offset=i,this.start=n,this.end=s,this.bufferPos=n-i}static tempFromBytes(e){return new Ee(e,K(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(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new Ee(this.bytes,this.view,this.offset,e,e+t)}}const Pe=(r,e)=>{if(r.filePos<r.start||r.filePos+e>r.end)throw new RangeError(`Tried reading [${r.filePos}, ${r.filePos+e}), but slice is [${r.start}, ${r.end}). This is likely an internal error, please report it alongside the file that caused it.`)},W=(r,e)=>{Pe(r,e);const t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},U=r=>(Pe(r,1),r.view.getUint8(r.bufferPos++)),pr=(r,e)=>{Pe(r,2);const t=r.view.getUint16(r.bufferPos,e);return r.bufferPos+=2,t},ae=r=>{Pe(r,2);const e=r.view.getUint16(r.bufferPos,!1);return r.bufferPos+=2,e},Ze=r=>{Pe(r,3);const e=di(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},xn=r=>{Pe(r,2);const e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},bt=(r,e)=>{Pe(r,4);const t=r.view.getUint32(r.bufferPos,e);return r.bufferPos+=4,t},M=r=>{Pe(r,4);const e=r.view.getUint32(r.bufferPos,!1);return r.bufferPos+=4,e},Gt=r=>{Pe(r,4);const e=r.view.getUint32(r.bufferPos,!0);return r.bufferPos+=4,e},At=r=>{Pe(r,4);const e=r.view.getInt32(r.bufferPos,!1);return r.bufferPos+=4,e},gd=r=>{Pe(r,4);const e=r.view.getInt32(r.bufferPos,!0);return r.bufferPos+=4,e},sa=(r,e)=>{let t,i;return e?(t=bt(r,!0),i=bt(r,!0)):(i=bt(r,!1),t=bt(r,!1)),i*4294967296+t},Ce=r=>{const e=M(r),t=M(r);return e*4294967296+t},yd=r=>{const e=At(r),t=M(r);return e*4294967296+t},wd=r=>{const e=Gt(r);return gd(r)*4294967296+e},kd=r=>{Pe(r,4);const e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},No=r=>{Pe(r,8);const e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e},ne=(r,e)=>{Pe(r,e);let t="";for(let i=0;i<e;i++)t+=String.fromCharCode(r.bytes[r.bufferPos++]);return t},Uo=(r,e,t)=>xe.decode(W(r,e)).split(`
2`).map(s=>s.trim()).filter(s=>s.length>0&&!t?.ignore?.(s));var Bt;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})(Bt||(Bt={}));var Xt;(function(r){r[r.ISO_8859_1=0]="ISO_8859_1",r[r.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",r[r.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",r[r.UTF_8=3]="UTF_8"})(Xt||(Xt={}));const Jr=128,Me=10,Qt=["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","S
2ound 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"],bd=(r,e)=>{const t=r.filePos;e.raw??={},e.raw.TAG??=W(r,Jr-3),r.filePos=t;const i=Wt(r,30);i&&(e.title??=i);const n=Wt(r,30);n&&(e.artist??=n);const s=Wt(r,30);s&&(e.album??=s);const a=Wt(r,4),o=Number.parseInt(a,10);Number.isInteger(o)&&o>0&&(e.date??=new Date(String(o)));const c=W(r,30);let l;if(c[28]===0&&c[29]!==0){const d=c[29];d>0&&(e.trackNumber??=d),r.skip(-30),l=Wt(r,28),r.skip(2)}else r.skip(-30),l=Wt(r,30);l&&(e.comment??=l);const u=U(r);u<Qt.length&&(e.genre??=Qt[u])},Wt=(r,e)=>{const t=W(r,e),i=Vt(t.indexOf(0),t.length),n=t.subarray(0,i);let s="";for(let a=0;a<n.length;a++)s+=String.fromCharCode(n[a]);return s.trimEnd()},dt=r=>{const e=r.filePos,t=ne(r,3),i=U(r),n=U(r),s=U(r),a=M(r);if(t!=="ID3"||i===255||n===255||(a&2155905152)!==0)return r.filePos=e,null;let o=mn(a);return s&Bt.Footer&&(o+=Me),{majorVersion:i,revision:n,flags:s,size:o}},Ci=(r,e,t)=>{if(![2,3,4].includes(e.majorVersion)){H._warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}const i=e.flags&Bt.Footer?e.size-Me:e.size,n=W(r,i),s=new Td(e,n);if(e.flags&Bt.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&Bt.ExtendedHeader){const a=s.readU32();e.majorVersion===3?s.pos+=a:s.pos+=a-4}for(;s.pos<=s.bytes.length-s.frameHeaderSize();){const a=s.readId3V2Frame();if(!a)break;const o=s.pos,c=s.pos+a.size;let l=!1,u=!1,d=!1;if(e.majorVersion===3?(l=!!(a.flags&64),u=!!(a.flags&128)):e.majorVersion===4&&(l=!!(a.flags&4),u=!!(a.flags&8),d=!!(a.flags&2)||!!(e.flags&Bt.Unsynchronisation)),l){H._warn(`Skipping encrypted ID3v2 frame ${a.id}`),s.pos=c;continue}if(u){H._warn(`Skipping compressed ID3v2 frame ${a.id}`),s.pos=c;continue}if(d&&s.ununsynchronizeRegion(s.pos,c),t.raw??={},a.id==="TXXX"){const f=t.raw.TXXX??={},h=s.readId3V2TextEncoding(),p=s.readId3V2Text(h,c),m=s.readId3V2Text(h,c);f[p]??=m}else a.id[0]==="T"?t.raw[a.id]??=s.readId3V2EncodingAndText(c):t.raw[a.id]??=s.readBytes(a.size);switch(s.pos=o,a.id){case"TIT2":case"TT2":t.title??=s.readId3V2EncodingAndText(c);break;case"TIT3":case"TT3":t.description??=s.readId3V2EncodingAndText(c);break;case"TPE1":case"TP1":t.artist??=s.readId3V2EncodingAndText(c);break;case"TALB":case"TAL":t.album??=s.readId3V2EncodingAndText(c);break;case"TPE2":case"TP2":t.albumArtist??=s.readId3V2EncodingAndText(c);break;case"TRCK":case"TRK":{const h=s.readId3V2EncodingAndText(c).split("/"),p=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(p)&&p>0&&(t.trackNumber??=p),m&&Number.isInteger(m)&&m>0&&(t.tracksTotal??=m)}break;case"TPOS":case"TPA":{const h=s.readId3V2EncodingAndText(c).split("/"),p=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(p)&&p>0&&(t.discNumber??=p),m&&Number.isInteger(m)&&m>0&&(t.discsTotal??=m)}break;case"TCON":case"TCO":{const f=s.readId3V2EncodingAndText(c);let h=/^\((\d+)\)/.exec(f);
2if(h){const p=Number.parseInt(h[1]);if(Qt[p]!==void 0){t.genre??=Qt[p];break}}if(h=/^\d+$/.exec(f),h){const p=Number.parseInt(h[0]);if(Qt[p]!==void 0){t.genre??=Qt[p];break}}t.genre??=f}break;case"TDRC":case"TDAT":{const f=s.readId3V2EncodingAndText(c),h=new Date(f);Number.isNaN(h.getTime())||(t.date??=h)}break;case"TYER":case"TYE":{const f=s.readId3V2EncodingAndText(c),h=Number.parseInt(f,10);Number.isInteger(h)&&(t.date??=new Date(String(h)))}break;case"USLT":case"ULT":{const f=s.readU8();s.pos+=3,s.readId3V2Text(f,c),t.lyrics??=s.readId3V2Text(f,c)}break;case"COMM":case"COM":{const f=s.readU8();s.pos+=3,s.readId3V2Text(f,c),t.comment??=s.readId3V2Text(f,c)}break;case"APIC":case"PIC":{const f=s.readId3V2TextEncoding();let h;if(e.majorVersion===2){const w=s.readAscii(3);h=w==="PNG"?"image/png":w==="JPG"?"image/jpeg":"image/*"}else h=s.readId3V2Text(f,c);const p=s.readU8(),m=s.readId3V2Text(f,c).trimEnd(),y=c-s.pos;if(y>=0){const w=s.readBytes(y);t.images||(t.images=[]),t.images.push({data:w,mimeType:h,kind:p===3?"coverFront":p===4?"coverBack":"unknown",description:m})}}break;default:s.pos+=a.size;break}s.pos=c}};class Td{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){const e=[];for(let t=0;t<this.bytes.length;t++){const i=this.bytes[t];e.push(i),i===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){const i=[];for(let a=e;a<t;a++){const o=this.bytes[a];i.push(o),o===255&&a!==t-1&&this.bytes[a+1]===0&&a++}const n=this.bytes.subarray(0,e),s=this.bytes.subarray(t);this.bytes=new Uint8Array(n.length+i.length+s.length),this.bytes.set(n,0),this.bytes.set(i,n.length),this.bytes.set(s,n.length+i.length),this.view=new DataView(this.bytes.buffer)}readBytes(e){const t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){const e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){const e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){const e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+2);return this.pos+=3,e*256+t}readU32(){const e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let i=0;i<e;i++)t+=String.fromCharCode(this.view.getUint8(this.pos+i));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){const e=this.readAscii(3);if(e==="\0\0\0")return null;const t=this.readU24();return{id:e,size:t,flags:0}}else{const e=this.readAscii(4);if(e==="\0\0\0\0")return null;const t=this.readU32();let i=this.header.majorVersion===4?mn(t):t;const n=this.readU16(),s=this.pos,a=o=>{const c=this.pos+o;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=o;const l=this.readAscii(4);if(l!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(l))return!1}return!0};if(!a(i)){const o=this.header.majorVersion===4?t:mn(t);a(o)&&(i=o)}return this.pos=s,{id:e,size:i,flags:n}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const i=this.pos,n=this.readBytes(t-this.pos);switch(e){case Xt.ISO_8859_1:{let s="";for(let a=0;a<n.length;a++){const o=n[a];if(o===0){this.pos=i+a+1;break}s+=String.fromCharCode(o)}return s}case Xt.UTF_16_WITH_BOM:if(n[0]===255&&n[1]===254){const s=new TextDecoder("utf-16le"),a=Vt(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=i+Math.min(a+2,n.length),s.decode(n.subarray(2,a))}else if(n[0]===254&&n[1]===255){const s=new TextDecoder("utf-16be"),a=Vt(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=i+Math.min(a+2,n.length),s.decode(n.subarray(2,a))}else{const s=Vt(n.findIndex(a=>a===0),n.length);return this.pos=i+Math.min(s+1,n.length),xe.decode(n.subarray(0,s))}case Xt.UTF_16_BE_NO_BOM:{const s=new TextDecoder("utf-16be"),a=Vt(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=i+Math.min(a+2,n.length),s.decode(n.subarray(0,a))}case Xt.UTF_8:{const s=Vt(n.findIndex(a=>a===0),n.length);return this.pos=i+Math.min(s+1,n.length),xe.decode(n.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class Sd{constructor(e){this.mutex=new or,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,i){if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);let n=this.trackTimestampInfo.get(e);if(n){if(i&&(n.maxTimestampBeforeLastKeyPacket=n.maxTimestamp),n.maxTimestampBeforeLastKeyPacket!==null&&t<n.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${n.maxTimestampBeforeLastKeyPacket}s.`);n.maxTimestamp=Math.max(n.maxTimestamp,t)}else{if(!i)throw new Error("First packet must be a key packet.");
2n={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,n)}}}const aa=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,xd=r=>{const e=Math.floor(r/36e5),t=Math.floor(r%(3600*1e3)/(60*1e3)),i=Math.floor(r%(60*1e3)/1e3),n=r%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")};class qr{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{const t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const s of e.children)s&&this.writeBox(s);const i=this.writer.getPos(),n=e.size??i-t;this.writer.seek(t),this.writeBoxHeader(e,n),this.writer.seek(i)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const t=this.offsets.get(e);g(t!==void 0);const i=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(const i of e.children)i&&(t+=this.measureBox(i));return t}}}const q=new Uint8Array(8),ze=new DataView(q.buffer),ie=r=>[(r%256+256)%256],L=r=>(ze.setUint16(0,r,!1),[q[0],q[1]]),Gn=r=>(ze.setInt16(0,r,!1),[q[0],q[1]]),Wo=r=>(ze.setUint32(0,r,!1),[q[1],q[2],q[3]]),F=r=>(ze.setUint32(0,r,!1),[q[0],q[1],q[2],q[3]]),ot=r=>(ze.setInt32(0,r,!1),[q[0],q[1],q[2],q[3]]),Xe=r=>(ze.setUint32(0,Math.floor(r/2**32),!1),ze.setUint32(4,r,!1),[q[0],q[1],q[2],q[3],q[4],q[5],q[6],q[7]]),Pd=r=>(ze.setInt32(0,Math.floor(r/2**32),!1),ze.setUint32(4,r,!1),[q[0],q[1],q[2],q[3],q[4],q[5],q[6],q[7]]),Vo=r=>(ze.setInt16(0,2**8*r,!1),[q[0],q[1]]),De=r=>(ze.setInt32(0,2**16*r,!1),[q[0],q[1],q[2],q[3]]),Gi=r=>(ze.setInt32(0,2**30*r,!1),[q[0],q[1],q[2],q[3]]),Xi=(r,e)=>{const t=[];let i=r;do{let n=i&127;i>>=7,t.length>0&&(n|=128),t.push(n)}while(i>0||e);return t.reverse()},Y=(r,e=!1)=>{const t=Array(r.length).fill(null).map((i,n)=>r.charCodeAt(n));return e&&t.push(0),t},Lo=r=>{const e=r*(Math.PI/180),t=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[t,i,0,-i,t,0,0,0,1]},Ho=Lo(0),qo=r=>[De(r[0]),De(r[1]),Gi(r[2]),De(r[3]),De(r[4]),Gi(r[5]),De(r[6]),De(r[7]),Gi(r[8])],V=(r,e,t)=>({type:r,contents:e&&new Uint8Array(e.flat(10)),children:t}),Q=(r,e,t,i,n)=>V(r,[ie(e),Wo(t),i??[]],n),Cd=r=>r.isQuickTime?V("ftyp",[Y("qt  "),F(512),Y("qt  ")]):r.fragmented?r.cmaf?V("ftyp",[Y("iso5"),F(512),Y("iso5"),Y("iso6"),Y("mp41"),Y("cmfc"),Y("dash")]):V("ftyp",[Y("iso5"),F(512),Y("iso5"),Y("iso6"),Y("mp41")]):V("ftyp",[Y("isom"),F(512),Y("isom"),r.holdsAvc?Y("avc1"):[],Y("mp41")]),oa=()=>V("styp",[Y("iso5"),F(0),Y("iso5"),Y("iso6"),Y("mp41"),Y("cmfc"),Y("dash")]),ca=(r,e)=>{let t=r.maxWrittenEndTimestamp-r.minWrittenTimestamp;return Number.isFinite(t)||(t=0),Q("sidx",1,0,[F(1),F(Ne),Xe(te(r.minWrittenTimestamp,Ne)),Xe(0),L(0),L(1),F(e&2147483647),F(te(t,Ne)),F(0)])},jr=r=>({type:"mdat",largeSize:r}),Id=r=>({type:"free",size:r}),gr=r=>V("moov",void 0,[Ed(r.creationTime,r.trackDatas),...r.trackDatas.map(e=>_d(e,r.creationTime)),r.isFragmented?pf(r.trackDatas):null,_f(r)]),Ed=(r,e)=>{const t=Math.max(0,...e.map(a=>te(Ii(a),Ne)+te(a.startTimestampOffset??0,Ne))),i=Math.max(0,...e.map(a=>a.track.id))+1,n=!Tt(r)||!Tt(t),s=n?Xe:F;return Q("mvhd",+n,0,[s(r),s(r),F(Ne),s(t),De(1),Vo(1),Array(10).fill(0),qo(H
2o),Array(24).fill(0),F(i)])},Ii=r=>{if(r.samples.length===0)return 0;let e=1/0,t=-1/0;for(let i=0;i<r.samples.length;i++){const n=r.samples[i];n.timestamp<e&&(e=n.timestamp),n.timestamp+n.duration>t&&(t=n.timestamp+n.duration)}return e===1/0?0:t-e},_d=(r,e)=>{const t=Wf(r),i=r.startTimestampOffset!==null&&r.startTimestampOffset>0;return V("trak",void 0,[vd(r,e),i?Ad(r,r.startTimestampOffset):null,Bd(r,e),t.name!==void 0?V("udta",void 0,[V("name",[...Ke.encode(t.name)])]):null])},vd=(r,e)=>{const t=te(Ii(r),Ne)+te(r.startTimestampOffset??0,Ne),i=!Tt(e)||!Tt(t),n=i?Xe:F;let s;if(r.type==="video"){const c=r.track.metadata.rotation;s=Lo(c??0)}else s=Ho;let a=2;r.track.metadata.disposition?.default!==!1&&(a|=1);const o=r.type==="video"?0:r.type==="audio"?1:r.type==="subtitle"?2:Fe(r);return Q("tkhd",+i,a,[n(e),n(e),F(r.track.id),F(0),n(t),Array(8).fill(0),L(0),L(o),Vo(r.type==="audio"?1:0),L(0),qo(s),De(r.type==="video"?r.info.width:0),De(r.type==="video"?r.info.height:0)])},Ad=(r,e)=>{const t=te(e,Ne),i=te(Ii(r),Ne),n=!Tt(t)||!Tt(i),s=n?Xe:F,a=n?Pd:ot;return V("edts",void 0,[Q("elst",n?1:0,0,[F(2),s(t),a(-1),De(1),s(i),a(0),De(1)])])},Bd=(r,e)=>V("mdia",void 0,[Fd(r,e),Xn(!0,Rd[r.type],Md[r.type]),zd(r)]),Fd=(r,e)=>{const t=te(Ii(r),r.timescale),i=!Tt(e)||!Tt(t),n=i?Xe:F;return Q("mdhd",+i,0,[n(e),n(e),F(r.timescale),n(t),L(Go(r.track.metadata.languageCode??ye)),L(0)])},Rd={video:"vide",audio:"soun",subtitle:"text"},Md={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Xn=(r,e,t,i="\0\0\0\0")=>Q("hdlr",0,0,[r?Y("mhlr"):F(0),Y(e),Y(i),F(0),F(0),Y(t,!0)]),zd=r=>V("minf",void 0,[Ud[r.type](),Wd(),Hd(r)]),Od=()=>Q("vmhd",0,1,[L(0),L(0),L(0),L(0)]),Dd=()=>Q("smhd",0,0,[L(0),L(0)]),Nd=()=>Q("nmhd",0,0),Ud={video:Od,audio:Dd,subtitle:Nd},Wd=()=>V("dinf",void 0,[Vd()]),Vd=()=>Q("dref",0,0,[F(1)],[Ld()]),Ld=()=>Q("url ",0,1),Hd=r=>{const e=r.compositionTimeOffsetTable.length>1||r.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return V("stbl",void 0,[qd(r),cf(r),e?hf(r):null,e?mf(r):null,uf(r),df(r),ff(r),lf(r)])},qd=r=>{let e;if(r.type==="video")e=jd(Ff(r.track.source._codec,r.info.decoderConfig.codec),r);else if(r.type==="audio"){const t=Ko(r.track.source._codec,r.info.decoderConfig.codec,r.muxer.isQuickTime);g(t),e=Yd(t,r)}else r.type==="subtitle"&&(e=af(zf[r.track.source._codec],r));return g(e),Q("stsd",0,0,[F(1)],[e])},jd=(r,e)=>V(r,[Array(6).fill(0),L(1),L(0),L(0),Array(12).fill(0),L(e.info.width),L(e.info.height),F(4718592),F(4718592),F(0),L(1),ie(10),Y("Mediabunny"),Array(21).fill(0),L(e.info.hasAlphaChannel?32:24),Gn(65535)],[Rf[e.track.source._codec]?.(e)??null,$d(e),ec(e.info.decoderConfig.colorSpace)?null:Kd(e)]),$d=r=>r.info.pixelAspectRatio.num===r.info.pixelAspectRatio.den?null:V("pasp",[F(r.info.pixelAspectRatio.num),F(r.info.pixelAspectRatio.den)]),Kd=r=>{const e=r.info.decoderConfig.colorSpace;return V("colr",[Y(r.muxer.isQuickTime?"nclc":"nclx"),L(e?.primaries!=null?nr[e.primaries]:2),L(e?.transfer!=null?sr[e.transfer]:2),L(e?.matrix!=null?ar[e.matrix]:2),r.muxer.isQuickTime?[]:ie((e?.fullRange?1:0)<<7)])},Gd=r=>r.info.decoderConfig&&V("avcC",[...ke(r.info.decoderConfig.description)]),Xd=r=>r.info.decoderConfig&&V("hvcC",[...ke(r.info.decoderConfig.description)]),la=r=>{if(!r.info.decoderConfig)return null;const e=r.info.decoderConfig,t=e.codec.split("."),i=Number(t[1]),n=Number(t[2]),s=Number(t[3]),a=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(e.colorSpace?.fullRange??0),c=(s<<4)+(a<<1)+o,l=t[5]?Number(t[5]):e.colorSpace?.primaries?nr[e.colorSpace.primaries]:1,u=t[6]?Number(t[6]):e.colorSpace?.transfer?sr[e.colorSpace.transfer]:1,d=t[7]?Number(t[7]):e.colorSpace?.matrix?ar[e.colorSpace.matrix]:1;return Q("vpcC",1,0,[ie(i),ie(n),ie(c),ie(l),ie(u),ie(d),L(0)])},Qd=r=>V("av1C",Zc(r.info.decoderConfig.codec)),Yd=(r,e)=>{let t=0,i,n=16;const s=be.includes(e.track.source._codec);if(s){const a=e.track.source._codec,{sampleSize:o}=ut(a);n=8*o,n>16&&(t=1)}if(e.muxer.isQuickTime&&(t=1),t===0)i=[Array(6).fill(0),L(1),L(t),L(0),F(0),L(e.info.numberOfChannels),L(n),L(0),L(0),L(e.info.sampleRate<2**16?e.info.sampleRate:0),L(0)];else{const a=s?0:-2;i=[Array(6).fill(0),L(1),L(t),L(0),F(0),L(e.info.numberOfChannels),L(Math.min(n,16)),Gn(a),L(0),L(e.info.sampleRate<2**16?e.info.sampleRate:0),L(0),s?[F(1),F(n/8),F(e.info.numberOfChannels*n/8)]:[F(0),F(0),F(0)],F(2)]}return V(r,i,[Mf(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},Qi=r=>{let e;switch(r.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${r.track.source._codec}`)}let t=[...ie(e),...ie(21),...Wo(0),...F(0),...F(0)];
2if(r.info.decoderConfig.description){const i=ke(r.info.decoderConfig.description);t=[...t,...ie(5),...Xi(i.byteLength),...i]}return t=[...L(1),...ie(0),...ie(4),...Xi(t.length),...t,...ie(6),...ie(1),...ie(2)],t=[...ie(3),...Xi(t.length),...t],Q("esds",0,0,t)},mt=r=>V("wave",void 0,[Zd(r),Jd(r),V("\0\0\0\0")]),Zd=r=>V("frma",[Y(Ko(r.track.source._codec,r.info.decoderConfig.codec,r.muxer.isQuickTime))]),Jd=r=>{const{littleEndian:e}=ut(r.track.source._codec);return V("enda",[L(+e)])},ef=r=>{let e=r.info.numberOfChannels,t=3840,i=r.info.sampleRate,n=0,s=0,a=new Uint8Array(0);const o=r.info.decoderConfig?.description;if(o){g(o.byteLength>=18);const c=ke(o),l=za(c);e=l.outputChannelCount,t=l.preSkip,i=l.inputSampleRate,n=l.outputGain,s=l.channelMappingFamily,l.channelMappingTable&&(a=l.channelMappingTable)}return V("dOps",[ie(0),ie(e),L(t),F(i),Gn(n),ie(s),...a])},tf=r=>{const e=r.info.decoderConfig?.description;g(e);const t=ke(e);return Q("dfLa",0,0,[...t.subarray(4)])},Ve=r=>{const{littleEndian:e,sampleSize:t}=ut(r.track.source._codec),i=+e;return Q("pcmC",0,0,[ie(i),ie(8*t)])},rf=r=>{g(r.info.primingPacket);const e=Oa(r.info.primingPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");const t=new Uint8Array(3),i=new G(t);return i.writeBits(2,e.fscod),i.writeBits(5,e.bsid),i.writeBits(3,e.bsmod),i.writeBits(3,e.acmod),i.writeBits(1,e.lfeon),i.writeBits(5,e.bitRateCode),i.writeBits(5,0),V("dac3",[...t])},nf=r=>{g(r.info.primingPacket);const e=Na(r.info.primingPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let t=16;for(const a of e.substreams)t+=23,a.numDepSub>0?t+=9:t+=1;const i=Math.ceil(t/8),n=new Uint8Array(i),s=new G(n);s.writeBits(13,e.dataRate),s.writeBits(3,e.substreams.length-1);for(const a of e.substreams)s.writeBits(2,a.fscod),s.writeBits(5,a.bsid),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(3,a.bsmod),s.writeBits(3,a.acmod),s.writeBits(1,a.lfeon),s.writeBits(3,0),s.writeBits(4,a.numDepSub),a.numDepSub>0?s.writeBits(9,a.chanLoc):s.writeBits(1,0);return V("dec3",[...n])},sf=r=>{g(r.info.primingPacket);const e=Nn(r.info.primingPacket.data);if(!e)throw new Error("Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.");return V("ddts",[...Gc(e)])},af=(r,e)=>V(r,[Array(6).fill(0),L(1)],[Of[e.track.source._codec](e)]),of=r=>V("vttC",[...Ke.encode(r.info.config.description)]),cf=r=>Q("stts",0,0,[F(r.timeToSampleTable.length),r.timeToSampleTable.map(e=>[F(e.sampleCount),F(e.sampleDelta)])]),lf=r=>{if(r.samples.every(t=>t.type==="key"))return null;const e=[...r.samples.entries()].filter(([,t])=>t.type==="key");return Q("stss",0,0,[F(e.length),e.map(([t])=>F(t+1))])},uf=r=>Q("stsc",0,0,[F(r.compactlyCodedChunkTable.length),r.compactlyCodedChunkTable.map(e=>[F(e.firstChunk),F(e.samplesPerChunk),F(1)])]),df=r=>{if(r.type==="audio"&&r.info.requiresPcmTransformation){const{sampleSize:e}=ut(r.track.source._codec);return Q("stsz",0,0,[F(e*r.info.numberOfChannels),F(r.samples.reduce((t,i)=>t+te(i.duration,r.timescale),0))])}return Q("stsz",0,0,[F(0),F(r.samples.length),r.samples.map(e=>F(e.size))])},ff=r=>r.finalizedChunks.length>0&&re(r.finalizedChunks).offset>=2**32?Q("co64",0,0,[F(r.finalizedChunks.length),r.finalizedChunks.map(e=>Xe(e.offset))]):Q("stco",0,0,[F(r.finalizedChunks.length),r.finalizedChunks.map(e=>F(e.offset))]),hf=r=>Q("ctts",1,0,[F(r.compositionTimeOffsetTable.length),r.compositionTimeOffsetTable.map(e=>[F(e.sampleCount),ot(e.sampleCompositionTimeOffset)])]),mf=r=>{let e=1/0,t=-1/0,i=1/0,n=-1/0;g(r.compositionTimeOffsetTable.length>0),g(r.samples.length>0);for(let a=0;a<r.compositionTimeOffsetTable.length;a++){const o=r.compositionTimeOffsetTable[a];e=Math.min(e,o.sampleCompositionTimeOffset),t=Math.max(t,o.sampleCompositionTimeOffset)}for(let a=0;a<r.samples.length;a++){const o=r.samples[a];i=Math.min(i,te(o.timestamp,r.timescale)),n=Math.max(n,te(o.timestamp+o.duration,r.timescale))}const s=Math.max(-e,0);return n>=2**31?null:Q("cslg",0,0,[ot(s),ot(e),ot(t),ot(i),ot(n)])},pf=r=>V("mvex",void 0,r.map(gf)),gf=r=>Q("trex",0,0,[F(r.track.id),F(1),F(0),F(0),F(0)]),ua=(r,e)=>
2V("moof",void 0,[yf(r),...e.map(wf)]),yf=r=>Q("mfhd",0,0,[F(r)]),jo=r=>{let e=0,t=0;const i=0,n=0,s=r.type==="delta";return t|=+s,s?e|=1:e|=2,e<<24|t<<16|i<<8|n},wf=r=>V("traf",void 0,[kf(r),bf(r),Tf(r)]),kf=r=>{g(r.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const t=r.currentChunk.samples[1]??r.currentChunk.samples[0],i={duration:t.timescaleUnitsToNextSample,size:t.size,flags:jo(t)};return Q("tfhd",0,e,[F(r.track.id),F(i.duration),F(i.size),F(i.flags)])},bf=r=>(g(r.currentChunk),Q("tfdt",1,0,[Xe(te(r.currentChunk.startTimestamp,r.timescale))])),Tf=r=>{g(r.currentChunk);const e=r.currentChunk.samples.map(m=>m.timescaleUnitsToNextSample),t=r.currentChunk.samples.map(m=>m.size),i=r.currentChunk.samples.map(jo),n=r.currentChunk.samples.map(m=>te(m.timestamp-m.decodeTimestamp,r.timescale)),s=new Set(e),a=new Set(t),o=new Set(i),c=new Set(n),l=o.size===2&&i[0]!==i[1],u=s.size>1,d=a.size>1,f=!l&&o.size>1,h=c.size>1||[...c].some(m=>m!==0);let p=0;return p|=1,p|=4*+l,p|=256*+u,p|=512*+d,p|=1024*+f,p|=2048*+h,Q("trun",1,p,[F(r.currentChunk.samples.length),F(r.currentChunk.offset-r.currentChunk.moofOffset||0),l?F(i[0]):[],r.currentChunk.samples.map((m,y)=>[u?F(e[y]):[],d?F(t[y]):[],f?F(i[y]):[],h?ot(n[y]):[]])])},Sf=r=>V("mfra",void 0,[...r.map(xf),Pf()]),xf=r=>Q("tfra",1,0,[F(r.track.id),F(63),F(r.finalizedChunks.length),r.finalizedChunks.map(t=>[Xe(te(t.samples[0].timestamp,r.timescale)),Xe(t.moofOffset),F(t.trafIndex+1),F(1),F(1)])]),Pf=()=>Q("mfro",0,0,[F(0)]),Cf=()=>V("vtte"),If=(r,e,t,i,n)=>V("vttc",void 0,[n!==null?V("vsid",[ot(n)]):null,t!==null?V("iden",[...Ke.encode(t)]):null,e!==null?V("ctim",[...Ke.encode(xd(e))]):null,i!==null?V("sttg",[...Ke.encode(i)]):null,V("payl",[...Ke.encode(r)])]),Ef=r=>V("vtta",[...Ke.encode(r)]),_f=r=>{const e=[],t=r.format._options.metadataFormat??"auto",i=r.output._metadataTags;if(t==="mdir"||t==="auto"&&!r.isQuickTime){const n=Af(i);n&&e.push(n)}else if(t==="mdta"){const n=Bf(i);n&&e.push(n)}else(t==="udta"||t==="auto"&&r.isQuickTime)&&vf(e,r.output._metadataTags);return e.length===0?null:V("udta",void 0,e)},vf=(r,e)=>{for(const{key:t,value:i}of Ta(e))switch(t){case"title":r.push(Le("©nam",i));break;case"description":r.push(Le("©des",i));break;case"artist":r.push(Le("©ART",i));break;case"album":r.push(Le("©alb",i));break;case"albumArtist":r.push(Le("albr",i));break;case"genre":r.push(Le("©gen",i));break;case"date":r.push(Le("©day",i.toISOString().slice(0,10)));break;case"comment":r.push(Le("©cmt",i));break;case"lyrics":r.push(Le("©lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:Fe(t)}if(e.raw)for(const t in e.raw){const i=e.raw[t];i==null||t.length!==4||r.some(n=>n.type===t)||(typeof i=="string"?r.push(Le(t,i)):i instanceof Uint8Array&&r.push(V(t,Array.from(i))))}},Le=(r,e)=>{const t=Ke.encode(e);return V(r,[L(t.length),L(Go("und")),Array.from(t)])},da={"image/jpeg":13,"image/png":14,"image/bmp":27},$o=(r,e)=>{const t=[];for(const{key:i,value:n}of Ta(r))switch(i){case"title":t.push({key:e?"title":"©nam",value:Oe(n)});break;case"description":t.push({key:e?"description":"©des",value:Oe(n)});break;case"artist":t.push({key:e?"artist":"©ART",value:Oe(n)});break;case"album":t.push({key:e?"album":"©alb",value:Oe(n)});break;case"albumArtist":t.push({key:e?"album_artist":"aART",value:Oe(n)});break;case"comment":t.push({key:e?"comment":"©cmt",value:Oe(n)});break;case"genre":t.push({key:e?"genre":"©gen",value:Oe(n)});break;case"lyrics":t.push({key:e?"lyrics":"©lyr",value:Oe(n)});break;case"date":t.push({key:e?"date":"©day",value:Oe(n.toISOString().slice(0,10))});break;case"images":for(const s of n)s.kind==="coverFront"&&t.push({key:"covr",value:V("data",[F(da[s.mimeType]??0),F(0),Array.from(s.data)])});break;case"trackNumber":if(e){const s=r.tracksTotal!==void 0?`${n}/${r.tracksTotal}`:n.toString();t.push({key:"track",value:Oe(s)})}else t.push({key:"trkn",value:V("data",[F(0),F(0),L(0),L(n),L(r.tracksTotal??0),L(0)])});break;case"discNumber":e||t.push({key:"disc",value:V("data",[F(0),F(0),L(0),L(n),L(r.discsTotal??0),L(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:Fe(i)}if(r.raw)for(const i in r.raw){const n=r.raw[i];n==null||!e&&i.length!==4||t.some(s=>s.key===i)||(typeof n=="string"?t.push({key:i,value:Oe(n)}):n instanceof Uint8Array?t.push({key:i,value:V("data",[F(0),F(0),Array.from(n)])}):n instanceof Yt&&t.push({key:i,value:V("data",[F(da[n.mimeType]??0),F(0),Array.from(n.data)])}))}return t},Af=r=>{const e=$o(r,!1);return e.length===0?null:Q("meta",0,0,void 0,[Xn(!1,"mdir","","appl"),V("ilst",void 0,e.map(t=>V(t.key,void 0,[t.value])))])},Bf=r=>{const e=$o(r,!0);return e.length===0?null:V("meta",void 0,[Xn(!1,"mdta",""),Q("keys",0,0,[F(e.length)],e.map(t=>V("mdta",[...Ke.encode(t.key)]))),V("ilst",void 0,e.map((t,i)=>{const n=String.fromCharCode(...F(i+1));return V(n,void 0,[t.value])}))])},Oe=r=>V("data",[F(1),F(0),...Ke.encode(r)]),Ff=(r,e)=>{switch(r){case"avc":return e.startsWith("avc3")?"avc3":"avc1";
2case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return e}},Rf={avc:Gd,hevc:Xd,vp8:la,vp9:la,av1:Qd,prores:null},Ko=(r,e,t)=>{switch(r){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3";case"dts":return e}if(t)switch(r){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(r){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},Mf=(r,e)=>{switch(r){case"aac":return Qi;case"mp3":return Qi;case"opus":return ef;case"vorbis":return Qi;case"flac":return tf;case"ac3":return rf;case"eac3":return nf;case"dts":return sf}if(e)switch(r){case"pcm-s24":return mt;case"pcm-s24be":return mt;case"pcm-s32":return mt;case"pcm-s32be":return mt;case"pcm-f32":return mt;case"pcm-f32be":return mt;case"pcm-f64":return mt;case"pcm-f64be":return mt}else switch(r){case"pcm-s16":return Ve;case"pcm-s16be":return Ve;case"pcm-s24":return Ve;case"pcm-s24be":return Ve;case"pcm-s32":return Ve;case"pcm-s32be":return Ve;case"pcm-f32":return Ve;case"pcm-f32be":return Ve;case"pcm-f64":return Ve;case"pcm-f64be":return Ve}return null},zf={webvtt:"wvtt"},Of={webvtt:of},Go=r=>{g(r.length===3);let e=0;for(let t=0;t<3;t++)e<<=5,e+=r.charCodeAt(t)-96;return e};class Pn{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){g(!this.started),this.target._start(),this.started=!0}write(e){g(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return g(this.started&&!this.finalized),this.target._flush()}async finalize(){g(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}const i=t+e.byteLength-this.trackedStart;let n=this.trackedWrites.byteLength;for(;n<i;)n*=2;if(n!==this.trackedWrites.byteLength){const s=new Uint8Array(n);s.set(this.trackedWrites,0),this.trackedWrites=s}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}}class je extends Or{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit("write",{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new Nf(this,e)}}const Yi=2**16,Zi=2**32;class Ji extends je{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");
2if(this._options=e,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(Yi,{maxByteLength:Zi})}catch{this._buffer=new ArrayBuffer(Yi),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Yi);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>Zi)throw new Error(`ArrayBuffer exceeded maximum size of ${Zi} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{const i=new ArrayBuffer(t),n=new Uint8Array(i);n.set(this._bytes,0),this._buffer=i,this._bytes=n}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}}class Df extends je{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _close(){}}class Nf extends je{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}}class en{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("getTarget must be a function.")}}const Ne=57600,Uf=2082844800,Wf=r=>{const e={},t=r.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},te=(r,e,t=!0)=>{const i=r*e;return t?Math.round(i):i};class Vf extends Sd{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Ji,this.auxWriter=new Pn(this.auxTarget,!1),this.auxBoxWriter=new qr(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=se(),this.creationTime=Math.floor(Date.now()/1e3)+Uf,this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.formatOptions={...t._options},this.isQuickTime=t instanceof Yo,this.isCmaf=t instanceof ha,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof ha?1/0:1),this.auxWriter.start()}async start(){const e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(i=>this.formatOptions.fastStart!==void 0?this.formatOptions.fastStart==="fragmented":i instanceof Ji),this.boxWriter=new qr(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof Ji?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");const i=await this.output._getInitTarget(),n=new Pn(i,!0);n.start(),this.initWriter=n,this.initBoxWriter=new qr(n)}const t=this.output.tracks.some(i=>i.isVideoTrack()&&i.source._codec==="avc");{const i=this.initBoxWriter??this.boxWriter;if(g(i),this.formatOptions.onFtyp&&i.writer.startTrackingWrites(),i.writeBox(Cd({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){const{data:n,start:s}=i.writer.stopTrackingWrites();this.formatOptions.onFtyp(n,s)}this.ftypSize=i.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(const i of this.output.tracks)if(i.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(g(this.writer),g(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=jr(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush();for(const i of this.output.tracks)i.isVideoTrack()&&i.metadata.decoderConfig?this.getVideoTrackData(i,i.metadata.primingPacket??null,{decoderConfig:i.metadata.decoderConfig}):i.isAudioTrack()&&i.metadata.decoderConfig&&this.getAudioTrackData(i,i.metadata.primingPacket??null,{decoderConfig:i.metadata.decoderConfig});e()}allTracksAreKnown(){for(const e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return Ya({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,i){const n=this.trackDatas.find(h=>h.track===e);if(n)return n;$a(i,e.source._codec),g(i),g(i.decoderConfig);const s={...i.decoderConfig};
2g(s.codedWidth!==void 0),g(s.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!s.description){if(!t)throw new Error("No AVC description provided; you must therefore provide a priming packet.");const h=yi(t.data);if(!h)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=gc(h),a=!0}else if(e.source._codec==="hevc"&&!s.description){if(!t)throw new Error("No HEVC description provided; you must therefore provide a priming packet.");const h=ki(t.data);if(!h)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=Pc(h),a=!0}const o=uc(1/(e.metadata.frameRate??Ne),1e6).den,c=s.displayAspectWidth,l=s.displayAspectHeight,u=c===void 0||l===void 0?{num:1,den:1}
2:vr({num:c*s.codedHeight,den:l*s.codedWidth}),d=s.codec==="ap4h"||s.codec==="ap4x",f={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:u,decoderConfig:s,requiresAnnexBTransformation:a,hasAlphaChannel:d},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(f),this.trackDatas.sort((h,p)=>h.track.id-p.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),f}getAudioTrackData(e,t,i){const n=this.trackDatas.find(c=>c.track===e);if(n)return n;Ka(i,e.source._codec),g(i),g(i.decoderConfig);const s={...i.decoderConfig};let a=!1;if(e.source._codec==="aac"&&!s.description){if(!t)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const c=Dt(Ee.tempFromBytes(t.data));if(!c)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const l=Ot[c.samplingFrequencyIndex],u=Dr[c.channelConfiguration];if(l===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");s.description=Ca({objectType:c.objectType,outputSampleRate:l,outputNumberOfChannels:u}),a=!0}if(!t){if(e.source._codec==="ac3"||e.source._codec==="eac3")throw new Error("AC-3/E-AC-3 require a priming packet.");if(e.source._codec==="dts")throw new Error("DTS requires a priming packet.")}const o={muxer:this,track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&be.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,primingPacket:t},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((c,l)=>c.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){const i=this.trackDatas.find(s=>s.track===e);if(i)return i;cl(t),g(t),g(t.config);const n={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(n),this.trackDatas.sort((s,a)=>s.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(e,t,i){const n=await this.mutex.acquire();try{const s=this.getVideoTrackData(e,t,i);let a=t.data;if(s.info.requiresAnnexBTransformation){const c=[...Nr(a)].map(l=>a.subarray(l.offset,l.offset+l.length));if(c.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=Rn(c,4)}this.validateTimestamp(s.track,t.timestamp,t.type==="key");const o=this.createSampleForTrack(s,a,t.timestamp,t.duration,t.type);await this.registerSample(s,o)}finally{n()}}async addEncodedAudioPacket(e,t,i){const n=await this.mutex.acquire();try{const s=this.getAudioTrackData(e,t,i);let a=t.data;if(s.info.requiresAdtsStripping){const u=Dt(Ee.tempFromBytes(a));if(!u)throw new Error("Expected ADTS frame, didn't get one.");const d=u.crcCheck===null?oi:Mt;a=a.subarray(d)}this.validateTimestamp(s.track,t.timestamp,t.type==="key");let o=t.timestamp,c=t.duration;if(s.info.requiresPcmTransformation){const d=ut(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(c=a.byteLength/d/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){const f=o-s.info.expectedNextPcmPacketTimestamp;if(f<.01)o=s.info.expectedNextPcmPacketTimestamp;else{const h=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,f);o=s.info.expectedNextPcmPacketTimestamp+h}}s.info.expectedNextPcmPacketTimestamp=o+c}const l=this.createSampleForTrack(s,a,o,c,t.type);await this.registerSample(s,l)}finally{n()}}async padWithSilence(e,t,i){const n=te(i,e.timescale);if(i=n/e.timescale,n>0){const{sampleSize:s,silentValue:a}=ut(e.info.decoderConfig.codec),o=n*e.info.numberOfChannels,c=new Uint8Array(s*o).fill(a),l=this.createSampleForTrack(e,new Uint8Array(c.buffer),t,i,"key");await this.registerSample(e,l)}return i}async addSubtitleCue(e,t,i){const n=await this.mutex.acquire();try{const s=this.getSubtitleTrackData(e,i);this.validateTimestamp(s.track,t.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(t),await this.processWebVTTCues(s,t.timestamp))}finally{n()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){const i=new Set([]);for(const l of e.cueQueue)g(l.timestamp<=t),g(e.lastCueEndTimestamp<=l.timestamp+l.duration),i.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),i.add(l.timestamp+l.duration);const n=[...i].sort((l,u)=>l-u),s=n[0],a=n[1]??s;if(t<a)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);const l=Cf();this.auxBoxWriter.writeBox(l);const u=this.auxTarget._getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,u,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let l=0;l<e.cueQueue.length;l++){const u=e.cueQueue[l];if(u.timestamp>=a)break;aa.lastIndex=0;const d=aa.test(u.text),f=u.timestamp+u.duration;let h=e.cueToSourceId.get(u);if(h===void 0&&a<f&&(h=e.nextSourceId++,e.cueToSourceId.set(u,h)),u.notes){const m=Ef(u.notes);this.auxBoxWriter.writeBox(m)}const p=If(u.text,d?s:null,u.identifier??null,u.settings??null,h??null);this.auxBoxWriter.writeBox(p),f===a&&e.cueQueue.splice(l--,1)}const o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,o,s,a-s,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,i,n,s){return{timestamp:i,decodeTimestamp:i,duration:n,data:t,size:t.byteLength,type:s,timescaleUnitsToNextSample:te(n,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let n=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){const a=e.timestampProcessingQueue[s],o=te(a.duration,e.timescale);n+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleC
2ount:n,sampleDelta:1});else{const s=re(e.timeToSampleTable);s.sampleCount+=n}e.timestampProcessingQueue.length=0;return}const i=e.timestampProcessingQueue.map(n=>n.timestamp).sort((n,s)=>n-s);this.isFragmented||(e.startTimestampOffset??=i[0]);for(let n=0;n<e.timestampProcessingQueue.length;n++){const s=e.timestampProcessingQueue[n];s.decodeTimestamp=i[n];const a=te(s.timestamp-s.decodeTimestamp,e.timescale),o=te(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){g(e.lastSample);const c=te(s.decodeTimestamp,e.timescale,!1),l=Math.round(c-e.lastTimescaleUnits);if(g(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let u=re(e.timeToSampleTable);if(g(u),u.sampleCount===1){u.sampleDelta=l;const f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===l&&(f.sampleCount++,e.timeToSampleTable.pop(),u=f)}else u.sampleDelta!==l&&(u.sampleCount--,e.timeToSampleTable.push(u={sampleCount:1,sampleDelta:l}));u.sampleDelta===o?u.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const d=re(e.compositionTimeOffsetTable);g(d),d.sampleCompositionTimeOffset===a?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=te(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,g(e.lastSample),g(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){g(t.type==="key");const n=te(t.timestamp,e.timescale,!1),s=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,t){t.type==="key"&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart==="reserve")){const n=e.track.metadata.maximumPacketCount;if(g(n!==void 0),e.samples.length>n)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${n}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const n=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const s=this.trackDatas.every(a=>{if(e===a)return t.type==="key";const o=a.sampleQueue[0];return o?o.type==="key":a.closed});n>=this.minimumFragmentDuration&&s&&t.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=n>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),g(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(g(!this.isFragmented),g(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((i,n)=>i+te(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||re(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(const i of e.currentChunk.samples)g(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(g(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let t=null,i=1/0;for(const s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<i&&(t=s,i=s.sampleQueue[0].timestamp)}if(!t)break;const n=t.sampleQueue.shift();await this.addSampleToTrack(t,n)}}async finalizeFragment(e=!this.isCmaf){if(g(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;
2const h=this.initBoxWriter??this.boxWriter;g(h),this.formatOptions.onMoov&&h.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const p=gr(this);if(h.writeBox(p),this.formatOptions.onMoov){const{data:m,start:y}=h.writer.stopTrackingWrites();this.formatOptions.onMoov(m,y)}if(this.isCmaf){g(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new qr(this.writer);const m=this.boxWriter.measureBox(oa()),y=this.boxWriter.measureBox(ca(this,0));this.segmentHeaderSize=m+y,this.writer.seek(this.segmentHeaderSize)}}g(this.writer),g(this.boxWriter);const t=this.trackDatas.filter(h=>h.currentChunk);if(t.length===0){e&&await this.writer.flush();return}const i=this.nextFragmentNumber++,n=ua(i,t),s=this.writer.getPos(),a=s+this.boxWriter.measureBox(n);let o=a+st,c=1/0;for(let h=0;h<t.length;h++){const p=t[h];p.currentChunk.offset=o,p.currentChunk.moofOffset=s,p.currentChunk.trafIndex=h;for(const m of p.currentChunk.samples)o+=m.size;c=Math.min(c,p.currentChunk.startTimestamp)}const l=o-a,u=l>=2**32;if(u)for(const h of t)h.currentChunk.offset+=_t-st;this.formatOptions.onMoof&&this.writer.startTrackingWrites();const d=ua(i,t);if(this.boxWriter.writeBox(d),this.formatOptions.onMoof){const{data:h,start:p}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(h,p,c)}g(this.writer.getPos()===a),this.formatOptions.onMdat&&this.writer.startTrackingWrites();const f=jr(u);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(a+(u?_t:st));for(const h of t)for(const p of h.currentChunk.samples)this.writer.write(p.data),p.data=null;if(this.formatOptions.onMdat){const{data:h,start:p}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(h,p)}for(const h of t)h.finalizedChunks.push(h.currentChunk),this.finalizedChunks.push(h.currentChunk),h.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,t)):e.sampleQueue.push(t)}async createFastStartReserveMdat(){g(this.writer),g(this.boxWriter),this.ensureOneEnabledTrack();const e=gr(this),i=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;g(this.ftypSize!==null),this.writer.seek(this.ftypSize+i),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=jr(!0),this.boxWriter.writeBox(this.mdat);for(const n of this.trackDatas){for(const s of n.sampleQueue)await this.addSampleToTrack(n,s);n.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){g(this.fastStart==="reserve");let e=0;for(const t of this.trackDatas){const i=t.track.metadata.maximumPacketCount;g(i!==void 0),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){const t=await this.mutex.acquire(),i=this.trackDatas.find(n=>n.track===e);i&&(i.closed=!0,i.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(const e of["video","audio","subtitle"]){const t=this.trackDatas.filter(n=>n.type===e);if(t.length===0)continue;if(!t.some(n=>n.track.metadata.disposition?.default!==!1)){const n=t[0];n.track.metadata.disposition={...n.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){g(this.isFragmented);const e=await this.mutex.acquire();try{for(const t of this.trackDatas)t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0),this.processTimestamps(t);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart==="reserve"&&await this.createFastStartReserveMdat();for(const t of this.trackDatas)t.closed=!0,t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0),this.processTimestamps(t);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(const t of this.trackDatas)if(await this.finalizeCurrentChunk(t),t.startTimestampOffset!==null)for(let i=0;i<t.samples.length;i++){const n=t.samples[i];n.timestamp-=t.startTimestampOffset,n.decodeTimestamp-=t.startTimestampOffset}if(g(this.writer),g(this.boxWriter),this.fastStart==="in-memory"){this.mdat=jr(!1);let t;for(let n=0;n<2;n++){const s=gr(this),a=this.boxWriter.measureBox(s);
2t=this.boxWriter.measureBox(this.mdat);let o=this.writer.getPos()+a+t;for(const c of this.finalizedChunks){c.offset=o;for(const{data:l}of c.samples)g(l),o+=l.byteLength,t+=l.byteLength}if(o<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();const i=gr(this);if(this.boxWriter.writeBox(i),this.formatOptions.onMoov){const{data:n,start:s}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(n,s)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const n of this.finalizedChunks)for(const s of n.samples)g(s.data),this.writer.write(s.data),s.data=null;if(this.formatOptions.onMdat){const{data:n,start:s}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(n,s)}}else if(this.isFragmented)if(this.isCmaf){const t=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(oa()),this.boxWriter.writeBox(ca(this,t))}else{const t=this.writer.getPos(),i=Sf(this.trackDatas);this.boxWriter.writeBox(i);const n=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{g(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);g(t!==void 0);const i=this.writer.getPos()-t;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){const{data:s,start:a}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(s,a)}const n=gr(this);if(this.fastStart==="reserve"){g(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);const s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(Id(s))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.formatOptions.onMoov){const{data:s,start:a}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(s,a)}}e()}}class Lf{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples)}doChannelMixerSetup(){g(this.sourceNumberOfChannels!==null);const e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(i,n)=>i[n*e]:e===1&&t===4?this.channelMixer=(i,n,s)=>i[n*e]*+(s<2):e===1&&t===6?this.channelMixer=(i,n,s)=>i[n*e]*+(s===2):e===2&&t===1?this.channelMixer=(i,n)=>{const s=n*e;return .5*(i[s]+i[s+1])}:e===2&&t===4?this.channelMixer=(i,n,s)=>i[n*e+s]*+(s<2):e===2&&t===6?this.channelMixer=(i,n,s)=>i[n*e+s]*+(s<2):e===4&&t===1?this.channelMixer=(i,n)=>{const s=n*e;return .25*(i[s]+i[s+1]+i[s+2]+i[s+3])}:e===4&&t===2?this.channelMixer=(i,n,s)=>{const a=n*e;return .5*(i[a+s]+i[a+s+2])}:e===4&&t===6?this.channelMixer=(i,n,s)=>{const a=n*e;return s<2?i[a+s]:s===2||s===3?0:i[a+s-2]}:e===6&&t===1?this.channelMixer=(i,n)=>{const s=n*e;return Math.SQRT1_2*(i[s]+i[s+1])+i[s+2]+.5*(i[s+4]+i[s+5])}:e===6&&t===2?this.channelMixer=(i,n,s)=>{const a=n*e;return i[a+s]+Math.SQRT1_2*(i[a+2]+i[a+s+4])}:e===6&&t===4?this.channelMixer=(i,n,s)=>{const a=n*e;return s<2?i[a+s]+Math.SQRT1_2*i[a+2]:i[a+s+2]}:this.channelMixer=(i,n,s)=>s<e?i[n*e+s]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){const i=new Float32Array(t);i.set(this.tempSourceBuffer),this.tempSourceBuffer=i}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()),g(this.startTime!==null);const t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);const i=e.allocationSize({planeIndex:0,format:"f32"}),n=new Float32Array(this.tempSourceBuffer.buffer,0,i/4);e.copyTo(n,{planeIndex:0,format:"f32"});const s=e.timestamp-this.startTime,a=s+e.duration,o=Math.floor((s-1/this.sourceSampleRate)*this.targetSampleRate)+1,c=Math.ceil(a*this.targetSampleRate);for(let l=o;l<c;l++){if(l<this.bufferStartFrame)continue;for(;l>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;const u=l-this.bufferStartFrame;g(u<this.bufferSizeInFrames);const h=(l/this.targetSampleRate-s)*this.sourceSampleRate,p=Math.floor(h),m=Math.ceil(h),y=h-p;for(let w=0;w<this.targetNumberOfChannels;w++){let k=0,b=0;p>=0&&p<e.numberOfFrames&&(k=this.channelMixer(n,p,w)),m>=0&&m<e.numberOfFrames&&(b=this.channelMixer(n,m,w));const S=k+y*(b-k),T=u*this.targetNumberOfChannels+w;this.outputBuffer[T]+=S}this.maxWrittenFrame===null?this.maxWrittenFrame=u:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,u)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;g(this.startTime!==null);const e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));const i=new he({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(i),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}}var Hf=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,n;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(n=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");n&&(i=function(){try{n.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:i,async:t})}else t&&r.stack.push({async:!0});return e},qf=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var i,n=0;function s(){for(;i=e.stack.pop();)try{if(!i.async&&n===1)return n=0,e.stack.push(i),Promise.resolve().then(s);if(i.dispose){var a=i.dispose.call(i.value);if(i.async)return n|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else n|=1}catch(o){t(o)}
2if(n===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=r,i.suppressed=e,i});class Qn{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}}class Yn extends Qn{constructor(e){if(super(),this._connectedTrack=null,!_e.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${_e.join(", ")}.`);this._codec=e}}const Cn=(r,e)=>{if(r.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class jf extends Yn{constructor(e){super(e)}add(e,t){if(!(e instanceof Z))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),Cn(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}}class $f{setError(e){this.errorSet||(this.error=e,this.errorSet=!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.co
2dedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new fi,this.customEncoderQueueSize=0,this.defaultEncodeOptions={},this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t,i){const n=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();const s=this.encodingConfig,a=s.sizeChangeBehavior??"deny";let o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(o=!0,a==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(s.transform?.width!==void 0||s.transform?.height!==void 0||s.transform?.rotate!==void 0||s.transform?.crop!==void 0||s.transform?.force===!0||o&&a!=="passThrough"){let d=s.transform?.width,f=s.transform?.height,h=s.transform?.fit??"fill";o&&a!=="passThrough"&&(g(this.outputWidth),g(this.outputHeight),g(a!=="deny"),d=this.outputWidth,f=this.outputHeight,h=a);const p=await e.transform({width:d,height:f,roundDimensionsTo:2,crop:s.transform?.crop,rotate:s.transform?.rotate,fit:h,alpha:s.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=p.displayWidth,this.outputHeight=p.displayHeight),t&&e.close(),e=p,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);const u=s.transform?.frameRate;if(u!==void 0){const d=e.timestamp+e.duration,f=rs(e.timestamp,u);if(this.frameRateLastSample!==null)if(f<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=d;return}else await this.padFrameRate(f,i);e===n&&(e=e.clone(),t=!0),e.setTimestamp(f),e.setDuration(1/u),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=f,this.frameRateLastEndTimestamp=d}await this.processAndEncode(e,i)}finally{t&&e.close()}}async processAndEncode(e,t){const i=this.encodingConfig;let n;if(i.transform?.process){let s=i.transform.process(e);if(A(s)&&(s=await s),s===null)return;Array.isArray(s)||(s=[s]);const a=[];try{for(const o of s)o instanceof pe?a.push(o):typeof VideoFrame<"u"&&o instanceof VideoFrame?a.push(new pe(o)):a.push(new pe(o,{timestamp:e.timestamp,duration:e.duration}))}catch(o){for(const c of a)c!==e&&c.close();for(const c of s)(c instanceof pe&&c!==e||typeof VideoFrame<"u"&&c instanceof VideoFrame)&&c.close();throw o}n=a}else n=[e];try{for(const s of n){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(s),this.encoderInitialized||await this.ensureEncoderPromise),g(this.encoderInitialized),this.closed)break;const a=this.encodingConfig.keyFrameInterval??2,o=Math.floor(s.timestamp/a),c={...this.defaultEncodeOptions,...s.encodeOptions,...t},l={...c,keyFrame:c.keyFrame!==void 0?c.keyFrame:a===0||o!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=o,this.encodingConfig.onEncodedSample?.(s),this.customEncoder){this.customEncoderQueueSize++;const u=s.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(u,l)).catch(f=>this.setError(f)).finally(()=>{this.customEncoderQueueSize--,u.close()});this.customEncoderQueueSize>=4&&await d}else{g(this.encoder);const u=s.toVideoFrame(),d=X(this.preciseTimings,u.timestamp,h=>h.microsecondTimestamp),f=d!==-1?this.preciseTimings[d]:null;if(f&&f.microsecondTimestamp===u.timestamp?(f.timestamp!==s.timestamp&&(f.timestampIsValid=!1),f.duration!==s.duration&&(f.durationIsValid=!1)):(this.preciseTimings.splice(d+1,0,{microsecondTimestamp:u.timestamp,timestamp:s.timestamp,duration:s.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(!!u.format&&!u.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(u,l)}finally{u.close()}}else{this.splitter||(this.splitter=new Kf);
2const{colorFrame:p,alphaFrame:m}=await this.splitter.split(u);this.alphaFrameQueue.push(m);try{this.encoder.encode(p,l)}finally{p.close()}}else try{this.encoder.encode(u,l)}finally{u.close()}this.encoder.encodeQueueSize>=4&&await new Promise(h=>this.encoder.addEventListener("dequeue",h,{once:!0}))}await this.lastMuxerPromise}}finally{for(const s of n)s!==e&&s.close()}}async padFrameRate(e,t){const i=this.encodingConfig.transform.frameRate;g(this.frameRateLastSample);const n=Math.round((e-this.frameRateLastTimestamp)*i);for(let s=1;s<n;s++){const a={stack:[],error:void 0,hasError:!1};try{const o=Hf(a,this.frameRateLastSample.clone(),!1);o.setTimestamp(this.frameRateLastTimestamp+s/i),o.setDuration(1/i),await this.processAndEncode(o,t)}catch(o){a.error=o,a.hasError=!0}finally{qf(a)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const t=rr(this.encodingConfig.quality,this.encodingConfig.bitrate);g(t!==void 0);const i=vo({...this.encodingConfig,quality:t,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});let n=null,s;for(const o of i){const c=o.config;if(this.encodingConfig.onEncoderConfig?.(c),s=zo.find(u=>u.supports(this.encodingConfig.codec,c)),s){n=o;break}if(typeof VideoEncoder>"u")continue;if(c.alpha="discard",this.encodingConfig.alpha==="keep"&&(c.latencyMode="quality"),(c.width%2===1||c.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${c.width}x${c.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);try{if((await VideoEncoder.isConfigSupported(c)).supported){n=o;break}}catch{}}if(!n){if(typeof VideoEncoder>"u")throw new Error(hi("VideoEncoder"));const o=i[0].config,c=i.map(({config:l,quantizer:u})=>u!==null?`quantizer ${u}`:`${l.bitrate} bps`);throw new Error(`This specific encoder configuration (${o.codec}, ${c.join(" / ")}, ${o.width}x${o.height}, hardware acceleration: ${o.hardwareAcceleration??"no-preference"}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}const a=n.config;if(n.quantizer!==null&&(this.defaultEncodeOptions=Fo(this.encodingConfig.codec,n.quantizer)),s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=a,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof Z))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");Cn(this.source._connectedTrack,o),this.encodingConfig.onEncodedPacket?.(o,c),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,o,c).catch(l=>{this.setError(l)})},this.customEncoder.onError=o=>{this.setError(o)},await this.customEncoder.init();else{const o=[],c=[];let l=0,u=0;const d=(h,p,m)=>{const y={};if(p){const T=new Uint8Array(p.byteLength);p.copyTo(T),y.alpha=T}let w=Z.fromEncodedChunk(h,y);const k=X(this.preciseTimings,h.timestamp,T=>T.microsecondTimestamp),b=k!==-1?this.preciseTimings[k]:null;let S=null;this.emittedEncoderPackets===0&&w.type==="delta"&&m?.decoderConfig&&(S=bi(this.encodingConfig.codec,m.decoderConfig,w.data)),(b&&b.microsecondTimestamp===h.timestamp||S!==null)&&(w=w.clone({timestamp:b?.timestampIsValid?b.timestamp:void 0,duration:b?.durationIsValid?b.duration:void 0,type:S??void 0})),Cn(this.source._connectedTrack,w),this.encodingConfig.onEncodedPacket?.(w,m),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,w,m).catch(T=>{this.setError(T)}),this.emittedEncoderPackets++},f=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(h,p)=>{if(!this.alphaEncoder){d(h,null,p);return}const m=this.alphaFrameQueue.shift();g(m!==void 0),m?(this.alphaEncoder.encode(m,{...this.defaultEncodeOptions,keyFrame:h.type==="
2key"}),u++,m.close(),o.push({chunk:h,meta:p})):u===0?d(h,null,p):(c.push(l+u),o.push({chunk:h,meta:p}))},error:h=>{h.stack=f,this.setError(h)}}),this.encoder.configure(a),this.encodingConfig.alpha==="keep"){const h=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(p,m)=>{u--;const y=o.shift();for(g(y!==void 0),d(y.chunk,p,y.meta),l++;c.length>0&&c[0]===l;){c.shift();const w=o.shift();g(w!==void 0),d(w.chunk,null,w.meta)}},error:p=>{p.stack=h,this.setError(p)}}),this.alphaEncoder.configure(a)}}g(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){try{if(!e&&(this.checkForEncoderError(),this.frameRateLastSample)){const t=this.encodingConfig.transform.frameRate,i=rs(this.frameRateLastEndTimestamp,t);await this.padFrameRate(i)}this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await xa(25)))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(t=>this.setError(t)):this.encoder&&(this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}}let tn=null;class Kf{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!tn){const n=new Blob([`(${Gf.toString()})()`],{type:"application/javascript"});tn=URL.createObjectURL(n)}this.worker=new Worker(tn),this.worker.addEventListener("message",n=>{const s=n.data,a=this.pendingRequests.get(s.id);a&&(this.pendingRequests.delete(s.id),"error"in s?a.reject(new Error(s.error)):a.resolve({colorFrame:s.colorFrame,alphaFrame:s.alphaFrame}))}),this.worker.addEventListener("error",n=>{const s=new Error(n.message||"Color/alpha splitter worker error.");for(const a of this.pendingRequests.values())a.reject(s);this.pendingRequests.clear()})}const t=this.nextRequestId++,i=se();return this.pendingRequests.set(t,i),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),i.promise}close(){this.worker?.terminate(),this.worker=null;const e=new Error("Color/alpha splitter closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}const Gf=()=>{let r=null,e=Promise.resolve();self.addEventListener("message",s=>{const{id:a,sourceFrame:o}=s.data;e=e.then(async()=>{try{const{colorFrame:c,alphaFrame:l}=await t(o);self.postMessage({id:a,colorFrame:c,alphaFrame:l},{transfer:[c,l]})}catch(c){self.postMessage({id:a,error:c.message})}finally{o.close()}})});const t=async s=>{const a=s.format;if(!a)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const o=s.allocationSize();if((!r||r.byteLength!==o)&&(r=new Uint8Array(o)),await s.copyTo(r),a==="RGBA"||a==="BGRA")return i(r,a,s);if(a==="I420A"||a==="I420AP10"||a==="I420AP12"||a==="I422A"||a==="I422AP10"||a==="I422AP12"||a==="I444A"||a==="I444AP10"||a==="I444AP12")return n(r,a,s);throw new Error(`CPU color/alpha splitting does not support format '${a}'.`)},i=(s,a,o)=>{const c=o.visibleRect?.width??o.codedWidth,l=o.visibleRect?.height??o.codedHeight,u=c*l,d=Math.ceil(c/2),f=Math.ceil(l/2),h=u+d*f*2,p=new Uint8Array(h);for(let k=0,b=3;k<u;k++,b+=4)p[k]=s[b];p.fill(128,u);const m=new VideoFrame(s,{format:a==="RGBA"?"RGBX":"BGRX",codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0}),y={format:"I420",codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0,transfer:[p.buffer]},w=new VideoFrame(p,y);return{colorFrame:m,alphaFrame:w}},n=(s,a,o)=>{const c=o.visibleRect?.width??o.codedWidth,l=o.visibleRect?.height??o.coded
2Height,u=a.includes("P10"),d=a.includes("P12"),f=u||d?2:1;let h,p;a.startsWith("I420")?(h=Math.ceil(c/2),p=Math.ceil(l/2)):a.startsWith("I422")?(h=Math.ceil(c/2),p=l):(h=c,p=l);const m=c*l,y=h*p,w=m*f,k=y*f,b=m*f,S=w+k*2,T=a.replace("A",""),P=Math.ceil(c/2),I=Math.ceil(l/2),C=P*I,x=C*f,E=b+2*x,_=new Uint8Array(E),v=S;_.set(s.subarray(v,v+b),0);const R=b,O=u?512:d?2048:128;f===1?_.fill(O,R):new Uint16Array(_.buffer,R,2*C).fill(O);const N=u?"I420P10":d?"I420P12":"I420",D=new VideoFrame(s.subarray(0,S),{format:T,codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0}),$={format:N,codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0,transfer:[_.buffer]},J=new VideoFrame(_,$);return{colorFrame:D,alphaFrame:J}}};class fa extends Yn{constructor(e){Xu(e),super(e.codec),this._encoder=new $f(this,e)}add(e,t){if(!(e instanceof pe))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Zn extends Qn{constructor(e){if(super(),this._connectedTrack=null,!Re.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Re.join(", ")}.`);this._codec=e}}class Xf extends Zn{constructor(e){super(e)}add(e,t){if(!(e instanceof Z))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}}class Qf{setError(e){this.errorSet||(this.error=e,this.errorSet=!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new fi,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;const i=this.encodingConfig;i.transform?.numberOfChannels!==void 0||i.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new Lf({targetNumberOfChannels:i.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:i.transform.sampleRate??e.sampleRate,onSample:async s=>{await this.processAndEncode(s,!0)}})),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){const i=this.encodingConfig;if(i.transform?.sampleFormat!==void 0&&$u(e.format)!==i.transform.sampleFormat){const n=Gu(e,i.transform.sampleFormat);t&&e.close(),e=n,t=!0}if(i.transform?.process)try{let n=i.transform.process(e);if(A(n)&&(n=await n),n===null)return;Array.isArray(n)||(n=[n]);try{for(const s of n)if(!(s instanceof he))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");for(const s of n)await this.encodeSample(s,!0)}finally{for(const s of n)s instanceof he&&s.close()}}finally{t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),g(this.encoderInitialized),this.closed)return;{const i=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{const s=i-this.lastEndSampleIndex;if(s>=64){const a=new he({data:new Float32Array(s*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:s,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(a,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;const i=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(i)).catch(s=>this.setError(s)).finally(()=>{this.customEncoderQueueSize--,i.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{g(this.encoder);const i=e.toAudioData();this.encoder.encode(i),i.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(n=>this.encoder.addEventListener("dequeue",n,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){g(this.outputSampleSize),g(this.writeOutputValue);const{numberOfChannels:i,numberOfFrames:n,sampleRate:s,timestamp:a}=e,o=2048,c=[];for(let f=0;f<n;f+=o){const h=Math.min(o,e.numberOfFrames-f),p=h*i*this.outputSampleSize,m=new ArrayBuffer(p),y=new DataView(m);c.push({frameCount:h,view:y})}const l=e.allocationSize({planeIndex:0,format:"f32-planar"}),u=new Float32Array(l/Float32Array.BYTES_PER_ELEMENT);for(let f=0;f<i;f++){e.copyTo(u,{planeIndex:f,format:"f32-planar"});for(let h=0;h<c.length;h++){const{frameCount:p,view:m}=c[h];for(let y=0;y<p;y++)this.writeOutputValue(m,(y*i+f)*this.outputSampleSize,u[h*o+y])}}t&&e.close();const d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:s}};for(let f=0;f<c.length;f++){const{frameCount:h,view:p}=c[f],m=p.buffer,y=f*o,w=new Z(new Uint8Array(m),"key",a+y/s,h/s);this.encodingConfig.onEncodedPacket?.(w,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,w,d)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const{numberOfChannels:t,sampleRate:i}=e,n=rr(this.encodingConfig.quality,this.encodingConfig.bitrate),s=Bo({numberOfChannels:t,sampleRate:i,...this.encodingConfig,quality:n});this.encodingConfig.onEncoderConfig?.(s);const a=Oo.find(o=>o.supports(this.encodingConfig.codec,s));if(a)this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=s,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof Z))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(o,c),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,o,c).catch(l=>{this.setError(l)})},this.customEncoder.onError=o=>{this.setError(o)},await this.customEncoder.init();else if(be.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error(hi("AudioEncoder"));let o;try{o=(await AudioEncoder.isConfigSupported(s)).supported??!1}catch{o=!1}
2if(!o)throw new Error(`This specific encoder configuration (${s.codec}, ${s.bitrate} bps, ${s.numberOfChannels} channels, ${s.sampleRate} Hz) is not supported in this environment. Consider using another codec or changing your audio parameters.`);const c=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(l,u)=>{if(this.encodingConfig.codec==="aac"&&u?.decoderConfig){let f=!1;if(!u.decoderConfig.description||u.decoderConfig.description.byteLength<2?f=!0:f=Fn(ke(u.decoderConfig.description)).objectType===0,f){const h=Number(re(s.codec.split(".")));u.decoderConfig.description=Ca({objectType:h,outputNumberOfChannels:u.decoderConfig.numberOfChannels,outputSampleRate:u.decoderConfig.sampleRate})}}let d=Z.fromEncodedChunk(l);d=d.clone({timestamp:ei(d.timestamp,s.sampleRate),duration:l.duration!=null?ei(d.duration,s.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(d,u),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,d,u).catch(f=>{this.setError(f)})},error:l=>{l.stack=c,this.setError(l)}}),this.encoder.configure(s)}g(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;const e=this.encodingConfig.codec,{dataType:t,sampleSize:i,littleEndian:n}=ut(e);switch(this.outputSampleSize=i,i){case 1:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint8(a,oe((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(s,a,o)=>{s.setInt8(a,oe(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(s,a,o)=>{const c=oe(Math.floor(o*32767),-32768,32767);s.setUint8(a,td(c))}:t==="alaw"?this.writeOutputValue=(s,a,o)=>{const c=oe(Math.floor(o*32767),-32768,32767);s.setUint8(a,id(c))}:g(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint16(a,oe((o+1)*32767.5,0,65535),n):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt16(a,oe(Math.round(o*32767),-32768,32767),n):g(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(s,a,o)=>vn(s,a,oe((o+1)*83886075e-1,0,16777215),n):t==="signed"?this.writeOutputValue=(s,a,o)=>ac(s,a,oe(Math.round(o*8388607),-8388608,8388607),n):g(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint32(a,oe((o+1)*21474836475e-1,0,4294967295),n):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt32(a,oe(Math.round(o*2147483647),-2147483648,2147483647),n):t==="float"?this.writeOutputValue=(s,a,o)=>s.setFloat32(a,o,n):g(!1);break;case 8:t==="float"?this.writeOutputValue=(s,a,o)=>s.setFloat64(a,o,n):g(!1);break;default:Fe(i),g(!1)}}async flushAndClose(e){try{e||(this.checkForEncoderError(),this.resampler&&await this.resampler.finalize()),this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&await this.encoder.flush())}finally{this.closed=!0,this.resampler=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(t=>this.setError(t)):this.encoder&&this.encoder.state!=="closed"&&this.encoder.close()}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}}class Yf extends Zn{constructor(e){Qu(e),super(e.codec),this._encoder=new Qf(this,e)}add(e){if(!(e instanceof he))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Zf extends Qn{constructor(e){if(super(),this._connectedTrack=null,!Ar.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Ar.join(", ")}.`);this._codec=e}}class Xo{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>_e.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Re.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Ar.includes(e))}_codecUnsupportedHint(e){return""}_isFragmentedIsobmff(){return!1}}class Jn extends Xo{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!zr(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");
2if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:0,max:4294967295}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new Vf(e,this)}_isFragmentedIsobmff(){return this._options.fastStart==="fragmented"}}class Qo extends Jn{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[..._e,...Jt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Ar]}_codecUnsupportedHint(e){return new Yo().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class ha extends Jn{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[..._e,...Jt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Ar]}}class Yo extends Jn{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[..._e,...Re]}_codecUnsupportedHint(e){return new Qo().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}const ma=["video","audio","subtitle"];class Vr{constructor(e,t,i,n,s){this.id=e,this.output=t,this.type=i,this.source=n,this.metadata=s}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof Vr))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const t=ns(this.metadata.group),i=ns(e.metadata.group);for(const n of t)if(this.type!==e.type&&i.some(o=>n===o)||i.some(o=>n._pairedGroups.has(o)))return!0;return!1}}class Jf extends Vr{constructor(e,t,i,n){super(e,t,"video",i,n)}}class eh extends Vr{constructor(e,t,i,n){super(e,t,"audio",i,n)}}class th extends Vr{constructor(e,t,i,n){super(e,t,"subtitle",i,n)}}class Ue{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof Ue))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}}const rn=r=>{if(!r||typeof r!="object")throw new TypeError("metadata must be an object.");if(r.languageCode!==void 0&&!_r(r.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(r.name!==void 0&&typeof r.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(r.disposition!==void 0&&mc(r.disposition),r.maximumPacketCount!==void 0&&(!Number.isInteger(r.maximumPacketCount)||r.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(r.group!==void 0&&!(r.group instanceof Ue)&&(!Array.isArray(r.group)||r.group.some(e=>!(e instanceof Ue))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class pa extends Or{get target(){const e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);const t=this._getRootTarget();if(A(t))throw new TypeError(e);return t}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new Ue,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new or,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof Xo))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof je||e.target instanceof en))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof je&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof je)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof je&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){g(this._target instanceof en);const t=this._target.getTarget(e),i=n=>{if(!(n instanceof je))throw new TypeError("getTarget must return a Target.");return n};return A(t)?t.then(i):i(t)}async _getTarget(e){g(this._target instanceof en);const t=await this._getTargetValidated(e);return this._emit("target",{target:t,request:e,isRoot:e.isRoot}),this.state==="canceled"?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}
2async _getInitTarget(){if(g(this._initTarget!==null),this._initTarget instanceof je)return this._initTarget;const e=await this._initTarget();return this.state==="canceled"?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof je)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;const e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),i=n=>(this.state==="canceled"?n._close():this._rememberTarget(n),this._emit("target",{target:n,request:e,isRoot:!0}),this._rootTarget=n,n);return A(t)?this._rootTargetPromise=t.then(i):i(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{const t=await this._getRootTarget(),i=new Pn(t,typeof e=="boolean"?e:e(t));return i.start(),i})()}addVideoTrack(e,t={}){if(!(e instanceof Yn))throw new TypeError("source must be a VideoSource.");if(rn(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);if(t.decoderConfig!==void 0&&$a({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof Z))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(t.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new Jf(this.tracks.length+1,this,e,i))}addAudioTrack(e,t={}){if(!(e instanceof Zn))throw new TypeError("source must be an AudioSource.");if(rn(t),t.decoderConfig!==void 0&&Ka({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof Z))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(t.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new eh(this.tracks.length+1,this,e,i))}addSubtitleTrack(e,t={}){if(!(e instanceof Zf))throw new TypeError("source must be a SubtitleSource.");rn(t);const i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new th(this.tracks.length+1,this,e,i))}setMetadataTags(e){if(un(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");const t=this.format.getSupportedTrackCounts(),i=this.tracks.reduce((a,o)=>a+(o.type===e.type?1:0),0),n=t[e.type].max;if(i===n)throw new Error(n===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${n} ${e.type} track${n===1?"":"s"}.`);const s=t.total.max;if(this.tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks${s===1?"":"s"} in total.`);if(e.isVideoTrack()){const a=this.format.getSupportedVideoCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){const a=this.format.getSupportedAudioCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}
2else if(e.isSubtitleTrack()){const a=this.format.getSupportedSubtitleCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){const e=this.format.getSupportedTrackCounts();for(const i of ma){const n=this.tracks.reduce((a,o)=>a+(o.type===i?1:0),0),s=e[i].min;if(n<s)return!1}const t=e.total.min;return!(this.tracks.length<t)}async start(){const e=this.format.getSupportedTrackCounts();for(const i of ma){const n=this.tracks.reduce((a,o)=>a+(o.type===i?1:0),0),s=e[i].min;if(n<s)throw new Error(s===e[i].max?`${this.format._name} requires exactly ${s} ${i} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${i} track${s===1?"":"s"}.`)}const t=e.total.min;if(this.tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?"":"s"}.`:`${this.format._name} requires at least ${t} track${t===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(H._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";const i=this._mutex.acquire();try{await this._muxer.start();const n=this.tracks.map(s=>s.source._start());await Promise.all(n)}finally{(await i)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return H._warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&H._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire();try{const t=this.tracks.map(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await Promise.all([...this._unfinalizedTargets].map(i=>i._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(H._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire();try{const t=this.tracks.map(i=>i.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(t),await this._muxer.finalize(),this._rootWriterPromise){const i=await this._rootWriterPromise;i.finalized||(await i.flush(),await i.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}finally{await Promise.all([...this._unfinalizedTargets].map(t=>t._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}}var yr=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,n;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(n=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");n&&(i=function(){try{n.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:i,async:t})}else t&&r.stack.push({async:!0});return e},$r=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var i,n=0;function s(){for(;i=e.stack.pop();)try{if(!i.async&&n===1)return n=0,e.stack.push(i),Promise.resolve().then(s);if(i.dispose){var a=i.dispose.call(i.value);if(i.async)return n|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else n|=1}catch(o){t(o)}if(n===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=r,i.suppressed=e,i});const Kr=r=>{if(!r||typeof r!="object")throw new TypeError("options.video, when provided, must be an object.");if(r?.discard!==void 0&&typeof r.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if(r?.forceTranscode!==void 0&&typeof r.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(r?.codec!==void 0&&!_e.includes(r.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${_e.join(", ")}.`);const e=r?.bitrate;if(r?.quality!==void 0&&!(r.quality instanceof le))throw new TypeError("options.video.quality, when provided, must be a Quality.");if(r?.quality!==void 0&&e!==void 0)throw new TypeError("options.video.quality and options.video.bitrate c
2annot both be provided.");if(e!==void 0&&!(e instanceof le)&&(!Number.isInteger(e)||e<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(r?.width!==void 0&&(!Number.isInteger(r.width)||r.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if(r?.height!==void 0&&(!Number.isInteger(r.height)||r.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if(r?.fit!==void 0&&!["fill","contain","cover"].includes(r.fit))throw new TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");if(r?.width!==void 0&&r.height!==void 0&&r.fit===void 0)throw new TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if(r?.rotate!==void 0&&![0,90,180,270].includes(r.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(r?.allowRotationMetadata!==void 0&&typeof r.allowRotationMetadata!="boolean")throw new TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if(r?.crop!==void 0&&li(r.crop,"options.video."),r?.frameRate!==void 0&&(!Number.isFinite(r.frameRate)||r.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.");if(r?.alpha!==void 0&&!["discard","keep"].includes(r.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if(r?.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if(r?.process!==void 0&&typeof r.process!="function")throw new TypeError("options.video.process, when provided, must be a function.");if(r?.processedWidth!==void 0&&(!Number.isInteger(r.processedWidth)||r.processedWidth<=0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if(r?.processedHeight!==void 0&&(!Number.isInteger(r.processedHeight)||r.processedHeight<=0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.");if(r?.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(r.hardwareAcceleration))throw new TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(r?.group!==void 0&&!(r.group instanceof Ue||Array.isArray(r.group)&&r.group.every(t=>t instanceof Ue)))throw new TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},Gr=r=>{if(!r||typeof r!="object")throw new TypeError("options.audio, when provided, must be an object.");if(r?.discard!==void 0&&typeof r.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(r?.forceTranscode!==void 0&&typeof r.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(r?.codec!==void 0&&!Re.includes(r.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${Re.join(", ")}.`);const e=r?.bitrate;if(r?.quality!==void 0&&!(r.quality instanceof le))throw new TypeError("options.audio.quality, when provided, must be a Quality.");if(r?.quality!==void 0&&e!==void 0)throw new TypeError("options.audio.quality and options.audio.bitrate cannot both be provided.");if(e!==void 0&&!(e instanceof le)&&(!Number.isInteger(e)||e<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(r?.numberOfChannels!==void 0&&(!Number.isInteger(r.numberOfChannels)||r.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(r?.sampleRate!==void 0&&(!Number.isInteger(r.sampleRate)||r.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if(r?.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(r.sampleFormat))throw new TypeError("options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(r?.process!==void 0&&typeof r.process!="function")throw new TypeError("options.audio.process, when provided, must be a function.");
2if(r?.processedNumberOfChannels!==void 0&&(!Number.isInteger(r.processedNumberOfChannels)||r.processedNumberOfChannels<=0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if(r?.processedSampleRate!==void 0&&(!Number.isInteger(r.processedSampleRate)||r.processedSampleRate<=0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.");if(r?.group!==void 0&&!(r.group instanceof Ue||Array.isArray(r.group)&&r.group.every(t=>t instanceof Ue)))throw new TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},nn=2,sn=48e3;class Zo{static async init(e){const t=new Zo(e);return await t._init(),t}constructor(e){if(this.state="idle",this._nextOutputTrackId=0,this._outputTrackIds=[],this._outputOwnTrackGroups=[],this._trackPumps=[],this._composable=!1,this._executed=!1,this._executionUntil=1/0,this._pauseRequested=!1,this._synchronizer=new rh(this),this._totalDuration=null,this._maxTimestamps=new Map,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.input instanceof Pi))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof pa))throw new TypeError("options.output must be an Output.");if(e.tracks!==void 0&&e.tracks!=="all"&&e.tracks!=="primary")throw new TypeError("options.tracks, when provided, must be either 'all' or 'primary'.");if(e.composable!==void 0&&typeof e.composable!="boolean")throw new TypeError("options.composable, when provided, must be a boolean.");const t=e.composable??!1;if(t){if(e.tags!==void 0)throw new TypeError("options.tags cannot be set by a composable conversion; set metadata directly on the output instead.");if(e.output.state!=="pending")throw new TypeError("options.output must not have been started yet.")}else if(e.output.tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!=="pending")throw new TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(e.video!==void 0&&typeof e.video!="function")if(Array.isArray(e.video))for(const i of e.video)Kr(i);else Kr(e.video);if(e.audio!==void 0&&typeof e.audio!="function")if(Array.isArray(e.audio))for(const i of e.audio)Gr(i);else Gr(e.audio);if(e.trim!==void 0&&(!e.trim||typeof e.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(e.trim?.start!==void 0&&!Number.isFinite(e.trim.start))throw new TypeError("options.trim.start, when provided, must be a finite number.");if(e.trim?.end!==void 0&&!Number.isFinite(e.trim.end))throw new TypeError("options.trim.end, when provided, must be a finite number.");if(e.trim?.start!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(e.tags!==void 0&&(typeof e.tags!="object"||!e.tags)&&typeof e.tags!="function")throw new TypeError("options.tags, when provided, must be an object or a function.");if(typeof e.tags=="object"&&un(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!="boolean")throw new TypeError("options.showWarnings, when provided, must be a boolean.");this._options=e,this._composable=t,this.input=e.input,this.output=e.output}async _init(){const e=await this.input.getFormat();let t,i=this._options.tracks;if(i===void 0&&(i=e.name.includes("(HLS)")?"primary":"all"),i==="all")t=await this.input.getTracks();else if(i==="primary"){const l=await this.input.getPrimaryVideoTrack(),u=await this.input.getPrimaryAudioTrack();t=[l,u].filter(d=>d!==null)}else Fe(i),g(!1);const n=this.output.format.getSupportedTrackCounts();let s=1,a=1;const o=[],c=[];for(const l of t){let u;if(l.isVideoTrack())if(this._options.video)if(typeof this._options.video=="function"){const h=await this._options.video(l,s)??{};if(Array.isArray(h))for(const p of h)Kr(p);else Kr(h);u=Array.isArray(h)?h:[h],s++}else u=Array.isArray(this._options.video)?this._options.video:[this._options.video];else u=[{}];else if(l.isAudioTrack())if(this._options.audio)if(typeof this._options.audio=="function"){const h=await this._options.audio(l,a)??{};if(Array.isArray(h))for(const p of h)Gr(p);else Gr(h);u=Array.isArray(h)?h:[h],a++}else u=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else u=[{}];else g(!1);const d=u.filter(h=>h.discard);for(const h of d)this.discardedTracks.push({track:l,reason:"discarded_by_user",trackOptions:h});if(u.length===d.length){u.length===0&&this.discardedTracks.push({track:l,reason:"discarded_by_user",trackOptions:{}});continue}const f=u.filter(h=>!h.discard);o.push(l),c.push(f)}this._options.trim?.start!==void 0?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(o),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp);for(let l=0;l<o.length;l++){const u=o[l],d=c[l];for(const f of d){if(this.output.tracks.length===n.total.max){this.discardedTracks.push({track:u,reason:"max_track_count_reached",trackOptions:f});continue}if(this.output.tracks.reduce((m,y)=>m+(y.type===u.type?1:0),0)===n[u.type].max){this.discardedTracks.push({track:u,reason:"max_track_count_of_type_reached",trackOptions:f});continue}const p=this._nextOutputTrackId++;u.isVideoTrack()?await this._processVideoTrack(u,f,p):u.isAudioTrack()?await this._processAudioTrack(u,f,p):g(!1)}}for(let l=0;l<this.utilizedTracks.length-1;l++)for(let u=l+1;u<this.utilizedTracks.length;u++){const d=this.utilizedTracks[l],f=this.utilizedTracks[u],h=this._outputOwnTrackGroups[l],p=this._outputOwnTrackGroups[u];g(h!==void 0),g(p!==void 0),h&&p&&d.canBePairedWith(f)&&h.pairWith(p)}if(!this._composable){const l=await this.input.getMetadataTags();let u;if(this._options.tags){const h=typeof this._options.tags=="function"?await this._options.tags(l):this._options.tags;un(h),u=h}else u=l;const d=e.mimeType===this.output.format.mimeType,f=l.raw===u.raw;l.raw&&f&&!d&&delete u.raw,this.output.setMetadataTags(u)}if(this._composable?this.isValid=!0:this.isValid=this.output.hasEnoughTracks()&&this.output.tracks.length>0,this._options.showWarnings??!0){const l=[],u=this.discardedTracks.filter(d=>d.reason!=="discarded_by_user");u.length>0&&l.push("Some tracks had to be discarded from the conversion:",u),this.isValid||(l.length>0&&l.push(`
3
4`),l.push(this._getInvalidityExplanation().join(""))),l.length>0&&H._warn(...l)}}_getInvalidityExplanation(){const e=[];
4if(this.discardedTracks.length===0)e.push("Due to missing tracks, this conversion cannot be executed.");else{const t=this.discardedTracks.every(i=>i.reason==="discarded_by_user"||i.reason==="no_encodable_target_codec")&&this.discardedTracks.some(i=>i.reason==="no_encodable_target_codec");if(e.push("Due to discarded tracks, this conversion cannot be executed."),t){const i=this.discardedTracks.flatMap(s=>{if(s.reason==="discarded_by_user")return[];let a;return s.track.type==="video"?a=this.output.format.getSupportedVideoCodecs():s.track.type==="audio"?a=this.output.format.getSupportedAudioCodecs():a=this.output.format.getSupportedSubtitleCodecs(),a.filter(o=>!s.trackOptions.codec||o===s.trackOptions.codec)}),n=[...new Set(i)];n.length===1?e.push(`
5Tracks were discarded because your environment is not able to encode '${n[0]}' with the provided parameters.`):e.push(`
6Tracks were discarded because your environment is not able to encode any of the codecs ${n.map(s=>`'${s}'`).join(", ")} with the provided parameters.`),n.includes("mp3")&&e.push(`
7The @mediabunny/mp3-encoder extension package provides support for encoding MP3.`),n.includes("aac")&&e.push(`
8The @mediabunny/aac-encoder extension package provides support for encoding AAC.`),(n.includes("ac3")||n.includes("eac3"))&&e.push(`
9The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),n.includes("flac")&&e.push(`
10The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(`
11Check the discardedTracks field for more info.`)}return e}async execute(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.until!==void 0&&(typeof e.until!="number"||Number.isNaN(e.until)))throw new TypeError("options.until, when provided, must be a number.");if(e.pauseSignal!==void 0&&!(e.pauseSignal instanceof AbortSignal))throw new TypeError("options.pauseSignal, when provided, must be an AbortSignal.");if(!this.isValid)throw new Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
12`+this._getInvalidityExplanation().join(""));if(this.state==="executing")throw new Error("Cannot call execute() while a previous call to execute() is still running.");if(this.state==="canceled")throw new ga;if(this.state==="done")return;if(this._composable&&this.output.state==="pending")throw new Error("A composable conversion requires the output to be started. Call start() on the output before executing the conversion.");this.state="executing",this._executionUntil=e.until??1/0,this._pauseRequested=e.pauseSignal?.aborted??!1;const t=()=>{this.state==="executing"&&(this._pauseRequested=!0,this._synchronizer.resolveAll())};e.pauseSignal?.addEventListener("abort",t);for(const n of this._trackPumps)n.done||(n.resolvers=se());if(this._executed)for(const n of this._trackPumps)n.wake?.();else{this._executed=!0;for(const n of this._outputTrackIds)this._synchronizer.declareTrack(n);if(this.onProgress){const s=[...new Set(this.utilizedTracks)].map(async o=>await o.isLive()?1/0:await o.getDurationFromMetadata()??await o.computeDuration()),a=Math.max(0,...await Promise.all(s));this._computeProgress=!0,this._totalDuration=Math.min(a-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(const o of this._outputTrackIds)this._maxTimestamps.set(o,0);this.onProgress?.(0,0)}this._composable||await this.output.start();for(const n of this._trackPumps)n.start()}try{await Promise.all(this._trackPumps.map(n=>n.resolvers.promise))}catch(n){throw this.state!=="canceled"&&this.cancel(),n}finally{e.pauseSignal?.removeEventListener("abort",t)}if(this.state==="canceled")throw new ga;const i=this._trackPumps.every(n=>n.done);if(this.state=i?"done":"idle",i&&(this._composable||await this.output.finalize(),this._computeProgress)){const n=Math.min(...this._maxTimestamps.values());this.onProgress?.(1,n)}}async cancel(){if(this.state!=="done"){if(this.state==="canceled"){H._warn("Conversion already canceled.");return}this.state="canceled";for(const e of this._trackPumps)e.wake?.();this._synchronizer.resolveAll(),this._composable||await this.output.cancel()}}async _processVideoTrack(e,t,i){const n=await e.getCodec();if(!n){this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});return}let s;const a=await e.getRotation(),o=Cr(a+(t.rotate??0));let c=o;const l=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??
12!0),u=await e.getSquarePixelWidth(),d=await e.getSquarePixelHeight(),[f,h]=o%180===0?[u,d]:[d,u];let p=t.crop;p&&(p=Sn(p,f,h));const[m,y]=p?[p.width,p.height]:[f,h];let w=m,k=y;const b=w/k;t.width!==void 0&&t.height===void 0?(w=Nt(t.width),k=Nt(Math.round(w/b))):t.width===void 0&&t.height!==void 0?(k=Nt(t.height),w=Nt(Math.round(k*b))):t.width!==void 0&&t.height!==void 0&&(w=Nt(t.width),k=Nt(t.height));const S=await e.getFirstTimestamp();let T=this.output.format.getSupportedVideoCodecs();const P=!!t.forceTranscode||S<this._startTimestamp||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.quality!==void 0||t.bitrate!==void 0||!T.includes(n)||t.codec&&t.codec!==n||w!==m||k!==y||o!==0&&!l||!!p,I=t.alpha??"discard";if(P){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});return}t.codec&&(T=T.filter($=>$===t.codec));const _=rr(t.quality,t.bitrate)??new le("high"),v=await ed(T,{width:t.process&&t.processedWidth?t.processedWidth:w,height:t.process&&t.processedHeight?t.processedHeight:k,quality:_});if(!v){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});return}const R={codec:v,quality:_,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??"passThrough",alpha:I,hardwareAcceleration:t.hardwareAcceleration,transform:{}};g(R.transform);let O=w!==m||k!==y||o!==0&&(!l||t.process!==void 0)||!!p||u!==await e.getCodedWidth()||d!==await e.getCodedHeight();if(!O){const $={stack:[],error:void 0,hasError:!1};try{const J=new pa({format:new Qo,target:new Df}),ue=new fa(R);J.addVideoTrack(ue),await J.start();const Ae=new ta(e),Te=yr($,await Ae.getSample(S),!1);if(Te)try{await ue.add(Te),Te.close(),await J.finalize()}catch(Ei){H._warn("An error occurred when probing encoder support. Falling back to rerender path.",Ei),J.cancel(),O=!0,R.transform.force=!0}else await J.cancel()}catch(J){$.error=J,$.hasError=!0}finally{$r($)}}t.frameRate&&(R.transform.frameRate=t.frameRate),t.process&&(R.transform.process=t.process),O&&(c=0,R.transform.width=w,R.transform.height=k,R.transform.fit=t.fit??"fill",R.transform.rotate=Cr(o-a),R.transform.crop=p,R.transform.alpha=I);let N=null;R.onEncodedSample=$=>{N=$.timestamp};const D=new fa(R);s=D,this._registerTrackPump(async $=>{const J=new ta(e);for await(const ue of J.samples(this._startTimestamp,this._endTimestamp)){const Ae={stack:[],error:void 0,hasError:!1};try{const Te=yr(Ae,ue,!1);if(this.state==="canceled")break;const Ei=Math.max(Te.timestamp-this._startTimestamp,0);Te.setTimestamp(Ei),this._reportProgress(i,Te.timestamp+Te.duration),await D.add(Te),Te.close(),N!==null&&(this._synchronizer.shouldWait(i,N)&&await this._synchronizer.wait(N),await this._checkpoint($,N))}catch(Te){Ae.error=Te,Ae.hasError=!0}finally{$r(Ae)}}D.close(),this._synchronizer.closeTrack(i)})}else{const E=new jf(n);s=E,this._registerTrackPump(async _=>{const v=new ir(e),O={decoderConfig:await e.getDecoderConfig()??void 0};for await(const N of v.packets(void 0,void 0,{verifyKeyPackets:!0})){if(this.state==="canceled"||N.timestamp>=this._endTimestamp)break;const D=N.clone({timestamp:N.timestamp-this._startTimestamp,sideData:I==="discard"?{}:N.sideData});g(D.timestamp>=0),this._reportProgress(i,D.timestamp+D.duration),await E.add(D,O),this._synchronizer.shouldWait(i,D.timestamp)&&await this._synchronizer.wait(D.timestamp),await this._checkpoint(_,D.timestamp)}E.close(),this._synchronizer.closeTrack(i)})}let C=null;!t.group&&!this._composable&&(C=new Ue);const x=await e.getLanguageCode();this.output.addVideoTrack(s,{frameRate:t.frameRate,languageCode:_r(x)?x:void 0,name:await e.getName()??void 0,disposition:await e.getDisposition(),rotation:c,group:C??t.group}),this.utilizedTracks.push(e),this._outputTrackIds.push(i),this._outputOwnTrackGroups.push(C)}async _processAudioTrack(e,t,i){const n=await e.getCodec();if(!n){this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});return}let s;const a=await e.getNumberOfChannels(),o=await e.getSampleRate(),c=await e.getFirstTimestamp();let l=t.numberOfChannels??a,u=t.sampleRate??o;const d=c<this._startTimestamp;let f=c>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,h=this.output.format.getSupp
12ortedAudioCodecs();if(!t.forceTranscode&&!t.quality&&!t.bitrate&&l===a&&u===o&&!d&&!f&&h.includes(n)&&(!t.codec||t.codec===n)&&!t.process&&t.sampleFormat===void 0){const y=new Xf(n);s=y,this._registerTrackPump(async w=>{const k=new ir(e),S={decoderConfig:await e.getDecoderConfig()??void 0};for await(const T of k.packets()){if(this.state==="canceled"||T.timestamp>=this._endTimestamp)break;const P=T.clone({timestamp:T.timestamp-this._startTimestamp});g(P.timestamp>=0),this._reportProgress(i,P.timestamp+P.duration),await y.add(P,S),this._synchronizer.shouldWait(i,P.timestamp)&&await this._synchronizer.wait(P.timestamp),await this._checkpoint(w,P.timestamp)}y.close(),this._synchronizer.closeTrack(i)})}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});return}let w=null;t.codec&&(h=h.filter(I=>I===t.codec));const k=rr(t.quality,t.bitrate)??new le("high"),b=await Js(h,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:l,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:u,quality:k});if(!b.some(I=>Jt.includes(I))&&h.some(I=>Jt.includes(I))&&(l!==nn||u!==sn)){const C=(await Js(h,{numberOfChannels:nn,sampleRate:sn,quality:k})).find(x=>Jt.includes(x));C&&(w=C,l=nn,u=sn)}else w=b[0]??null;if(w===null){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});return}const S={codec:w,quality:k,transform:{sampleFormat:t.sampleFormat,process:t.process}};g(S.transform),l!==a&&(S.transform.numberOfChannels=l),u!==o&&(S.transform.sampleRate=u);let T=null;S.onEncodedSample=I=>{T=I.timestamp};const P=new Yf(S);s=P,this._registerTrackPump(async I=>{const C=new dd(e);for await(const x of C.samples(this._startTimestamp,this._endTimestamp)){const E={stack:[],error:void 0,hasError:!1};try{const _=yr(E,x,!1);if(this.state==="canceled")break;if(f){const D={stack:[],error:void 0,hasError:!1};try{const $=c-this._startTimestamp,J=Math.round($*o),ue=tt(_.format),Ae=new Uint8Array(ue*J*a);(_.format==="u8"||_.format==="u8-planar")&&Ae.fill(2**7);const Te=yr(D,new he({data:Ae,format:_.format,numberOfChannels:a,sampleRate:o,timestamp:0}),!1);await this._registerAudioSample(I,Te,P,i,()=>T),f=!1}catch($){D.error=$,D.hasError=!0}finally{$r(D)}}let v=0,R=_.numberOfFrames;_.timestamp<this._startTimestamp&&(v=Math.round((this._startTimestamp-_.timestamp)*_.sampleRate)),_.timestamp+_.duration>this._endTimestamp&&(R=Math.round((this._endTimestamp-_.timestamp)*_.sampleRate));let O;if(v>0||R<_.numberOfFrames){const D=_.trim(v,R);if(_.close(),O=D,D.numberOfFrames===0){D.close();continue}}else O=_;const N=yr(E,O,!1);N.setTimestamp(N.timestamp-this._startTimestamp),await this._registerAudioSample(I,N,P,i,()=>T)}catch(_){E.error=_,E.hasError=!0}finally{$r(E)}}P.close(),this._synchronizer.closeTrack(i)})}let p=null;!t.group&&!this._composable&&(p=new Ue);const m=await e.getLanguageCode();this.output.addAudioTrack(s,{languageCode:_r(m)?m:void 0,name:await e.getName()??void 0,disposition:await e.getDisposition(),group:p??t.group}),this.utilizedTracks.push(e),this._outputTrackIds.push(i),this._outputOwnTrackGroups.push(p)}async _registerAudioSample(e,t,i,n,s){this._reportProgress(n,t.timestamp+t.duration),await i.add(t),t.close();const a=s();a!==null&&(this._synchronizer.shouldWait(n,a)&&await this._synchronizer.wait(a),await this._checkpoint(e,a))}_registerTrackPump(e){const t={done:!1,resolvers:se(),wake:null,start:()=>{e(t).then(()=>{t.done=!0,t.resolvers.resolve()},i=>{t.resolvers.reject(i)})}};this._trackPumps.push(t)}async _checkpoint(e,t){for(;this.state!=="canceled"&&(t>=this._executionUntil||this._pauseRequested);){e.resolvers.resolve();const{promise:i,resolve:n}=se();e.wake=n,await i}}_reportProgress(e,t){if(!this._computeProgress)return;g(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));const i=Math.min(...this._maxTimestamps.values()),n=oe(i/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n,i))}}class ga extends Error{constructor(e="Conversion has been canceled."){super(e),this.name="ConversionCanceledError"}}const ya=1;class rh{constructor(e){this.maxTimestamps=new Map,this.resolvers=[],this.conversion=e}declareTrack(e){this.maxTimestamps.set(e,0)}shouldWait(e,t){const i=this.maxTimestamps.get(e);g(i!==void 0),this.maxTimestamps.set(e,Math.max(t,i));const n=this.computeMinAndMaybeResolve();return this.conversion.state==="canceled"||this.conversion._pauseRequested||t>=this.conversion._executionUntil?!1:t-n>ya}wait(e){const{promise:t,resolve:i}=se();return this.resolvers.push({timestamp:e,resolve:i}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}resolveAll(){for(const e of this.resolvers)e.resolve();this.resolvers.length=0}computeMinAndMaybeResolve(){let e=1/0;for(const[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){const i=this.resolvers[t];i.timestamp-e<ya&&(i.resolve(),this.resolvers.splice(t,1),t--)}return e}}const Jo=Symbol.for("mediabunny loaded");globalThis[Jo]&&H._error(`[WARNING]
13Mediabunny was loaded twice. This will likely cause Mediabunny not to work correctly. Check if multiple dependencies are importing different versions of Mediabunny, or if something is being bundled incorrectly.`);globalThis[Jo]=!0;export{Fu as ADTS,nh as ALL_FORMATS,ma as ALL_TRACK_TYPES,Re as AUDIO_CODECS,xu as AdtsInputFormat,Pa as AttachedFile,he as AudioSample,dr as AudioSampleResource,dd as AudioSampleSink,Yf as AudioSampleSource,Zn as AudioSource,Do as BaseMediaSampleSink,ih as BlobSource,Ji as BufferTarget,ha as CmafOutputFormat,Zo as Conversion,ga as ConversionCanceledError,cu as CustomPathedSource,Xf as EncodedAudioPacketSource,Z as EncodedPacket,ir as EncodedPacketSink,jf as EncodedVideoPacketSource,Or as EventEmitter,Ru as FLAC,Su as FlacInputFormat,zu as HLS,Co as HlsInputFormat,Pi as Input,Kn as InputAudioTrack,ge as InputDisposedError,Qe as InputFormat,Wr as InputTrack,$n as InputVideoTrack,xo as IsobmffInputFormat,Jn as IsobmffOutputFormat,He as LogLevel,H as Logging,Eu as MATROSKA,vu as MP3,Cu as MP4,Mu as MPEG_TS,Po as MatroskaInputFormat,Qn as MediaSource,Yo as MovOutputFormat,ku as Mp3InputFormat,gu as Mp4InputFormat,Qo as Mp4OutputFormat,Pu as MpegTsInputFormat,Jt as NON_PCM_AUDIO_CODECS,Df as NullTarget,Bu as OGG,Tu as OggInputFormat,pa as Output,eh as OutputAudioTrack,Xo as OutputFormat,th as OutputSubt
13itleTrack,Vr as OutputTrack,Ue as OutputTrackGroup,Jf as OutputVideoTrack,be as PCM_AUDIO_CODECS,Ur as PathedSource,en as PathedTarget,Iu as QTFF,le as Quality,yu as QuickTimeInputFormat,fu as RangedSource,Nf as RangedTarget,lu as ReadableStreamSource,Yt as RichImageData,Ar as SUBTITLE_CODECS,Ge as Source,qn as SourceRef,Zf as SubtitleSource,je as Target,na as UnsupportedInputFormatError,_e as VIDEO_CODECS,Tn as VIDEO_SAMPLE_PIXEL_FORMATS,pe as VideoSample,Li as VideoSampleColorSpace,xt as VideoSampleResource,ta as VideoSampleSink,fa as VideoSampleSource,Yn as VideoSource,Au as WAVE,_u as WEBM,bu as WaveInputFormat,wu as WebMInputFormat,Ju as canEncodeAudio,Zu as canEncodeVideo,ra as desc,Js as getEncodableAudioCodecs,ed as getFirstEncodableVideoCodec,hr as prefer};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.