1function g(r){if(!r)throw new Error("Assertion failed.")}const ei=r=>{const e=(r%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${r}.`)},ee=r=>r&&r[r.length-1],Tt=r=>r>=0&&r<2**32,M=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)},st=r=>{const e=M(r);return(e&1)===0?-(e>>1):e+1>>1},nc=(r,e,t,i)=>{for(let n=e;n<t;n++){const s=Math.floor(n/8);let a=r[s];const o=7-(n&7);a&=~(1<<o),a|=(i&1<<t-n-1)>>t-n-1<<o,r[s]=a}},fe=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),$=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),Se=new TextDecoder,be=new TextEncoder,yn=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),zt={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Je=yn(zt),Nt={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},et=yn(Nt),Ut={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},tt=yn(Ut),wn=r=>!!r&&!!r.primaries&&!!r.transfer&&!!r.matrix&&r.fullRange!==void 0,ba=r=>!r||r.primaries==null&&r.transfer==null&&r.matrix==null&&r.fullRange==null,Ta={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},ti=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r);class nr{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 sc=/^[0-9a-fA-F]+$/,xr=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),ac=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),Ar=(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},G=(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=G(r,t(e),t);r.splice(i+1,0,e)},oe=()=>{let r,e;return{promise:new Promise((i,n)=>{r=i,e=n}),resolve:r,reject:e}},Qi=(r,e)=>{const t=r.indexOf(e);t!==-1&&r.splice(t,1)},Sa=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return r[t]},bn=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1},oc=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},cc=r=>{if(!(Symbol.iterator in r)&&!(Symbol.asyncIterator in r))throw new TypeError("Argument must be an iterable or async iterable.")},Ee=r=>{throw new Error(`Unexpected value: ${r}`)},ri=(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},lc=(r,e,t)=>ri(r,e,t)<<8>>8,Tn=(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))},uc=(r,e,t,i)=>{t=ae(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),Tn(r,e,t,i)},ae=(r,e,t)=>Math.max(e,Math.min(t,r)),dc=(r,e,t)=>r+(e-r)*t,he="und",Cr=r=>{const e=Math.round(r);return Math.abs(r/e-1)<10*Number.EPSILON?e:r},Yi=(r,e)=>Math.round(r/e)*e,tr=(r,e)=>Math.round(r*e)/e,Ti=(r,e)=>Math.floor(r/e)*e,rs=(r,e)=>Math.floor(r*e)/e,fc=r=>{let e=0;for(;r;)e++,r>>=1;return e},Zi=r=>{let e=0;for(;r!==0;)r&=r-1,e++;return e},hc=/^[a-z]{3}$/,Sn=r=>hc.test(r),kt=1e6*(1+Number.EPSILON),mc=(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 ii{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let Si=null;const wr=()=>Si!==null?Si:Si=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWeb
1Kit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let xi=null;const xa=()=>xi!==null?xi:xi=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox");let Ci=null;const Ji=()=>Ci!==null?Ci:Ci=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),ni=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.`,pc=(async()=>{})().constructor,A=r=>r instanceof pc||r instanceof Promise?!0:typeof r?.then=="function",Lt=(r,e)=>r!==-1?r:e,is=(r,e,t,i)=>r<=i&&t<=e,xn=function*(r){for(const e in r){const t=r[e];t!==void 0&&(yield{key:e,value:t})}},gc=r=>{switch(r.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},Ca=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},Pa=(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},Cn=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},sr=r=>typeof r=="number"&&!Number.isNaN(r),gt=(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("/")},gr=(r,e)=>{let t=0;for(let i=0;i<r.length;i++)e(r[i])&&t++;return t},Pn=(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},rr=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}},Pi=(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.`)},Ia=r=>new Promise(e=>setTimeout(e,r)),ns=r=>Array.isArray(r)?r:[r];class Br{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 rh=r=>Math.ceil(r/2)*2,kc=r=>r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype&&Object.values(r).every(e=>typeof e=="string");var We;(function(r){r[r.Silent=0]="Silent",r[r.Errors=1]="Errors",r[r.Warnings=2]="Warnings",r[r.Info=3]="Info"})(We||(We={}));class H{constructor(){}static get level(){return H._level}static set level(e){if(e!==We.Silent&&e!==We.Errors&&e!==We.Warnings&&e!==We.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 Br}static on(e,t,i){return H._emitter.on(e,t,i)}static _error(...e){H._emitter._emit("error",e),H._level>=We.Errors&&console.error(...e)}
1static _warn(...e){H._emitter._emit("warn",e),H._level>=We.Warnings&&console.warn(...e)}static _info(...e){H._emitter._emit("info",e),H._level>=We.Info&&console.info(...e)}}H._level=We.Info;H._emitterInstance=null;class Zt{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 In{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 yc=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 Zt)&&!(e instanceof In)&&!kc(e))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}},lt={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},wc=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 K{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 K(this.bytes);return e.pos=this.pos,e}}const St=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],ar=[-1,1,2,3,4,5,6,8],En=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new K(r),t=Ii(e),{frequencyIndex:i,sampleRate:n}=Ei(e),s=e.readBits(4);let a=null;s>=1&&s<=7&&(a=ar[s]);let o=t,c=!1,l=n;if(t===5||t===29)c=t===29,l=Ei(e).sampleRate,o=Ii(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}Ii(e)===5&&e.readBits(1)&&(l=Ei(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}},Ii=r=>{const e=r.readBits(5);return e===31?32+r.readBits(6):e},Ei=r=>{const e=r.readBits(4);return e===15?{frequencyIndex:e,sampleRate:r.readBits(24)}:{frequencyIndex:e,sampleRate:e<St.length?St[e]:null}},_n=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=ar.indexOf(n);if(s===-1)throw new TypeError(`Unsupported number of channels: ${r.outputNumberOfChannels}`);let a=16;r.objectType>=32&&(a+=6),en(i)===15&&(a+=24),e&&(a+=9,en(r.outputSampleRate)===15&&(a+=24));const o=Math.ceil(a/8),c=new Uint8Array(o),l=new K(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=en(e);r.writeBits(4,t),t===15&&r.writeBits(24,e)},en=r=>{const e=St.indexOf(r);return e===-1?15:e};const si=[48e3,44100,32e3],Ea=[24e3,22050,16e3];var le;(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"})(le||(le={}));var se;(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"})(se||(se={}));const Fr=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})},_a=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=ri(i,t,!1):(g(e===4),n=i.getUint32(t,!1)),t+=e,yield{offset:t,length:n},t+=n}},va=(r,e)=>{if(e.description){const n=(fe(e.description)[4]&3)+1;return _a(r,n)}else return Fr(r)},ai=r=>r&31,oi=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)},_i=new Uint8Array([0,0,0,1]),Aa=r=>{const e=r.reduce((n,s)=>n+_i.byteLength+s.byteLength,0),t=new Uint8Array(e);let i=0;for(const n of r)t.set(_i,i),i+=_i.byteLength,t.set(n,i),i+=n.byteLength;return t},vn=(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:Tn(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},bc=(r,e)=>{if(e.description){const n=(fe(e.description)[4]&3)+1;return vn(r,n)}else return Aa(r)},ci=r=>{try{const e=[],t=[],i=[];for(const o of Fr(r)){const c=r.subarray(o.offset,o.offset+o.length),l=ai(c[0]);l===le.SPS?e.push(c):l===le.PPS?t.push(c):l===le.SPS_EXT&&i.push(c)}if(e.length===0||t.length===0)return null;const n=e[0],s=li(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}},Tc=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)},Ba=r=>{try{const e=$(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,k=e.getUint8(t++);f.chromaFormat=h,f.bitDepthLumaMinus8=p,f.bitDepthChromaMinus8=m;const y=[];for(let w=0;w<k;w++){const b=e.getUint16(t,!1);t+=2,y.push(r.subarray(t,t+b)),t+=b}f.sequenceParameterSetExt=y}return f}catch(e){return H._error("Error deserializing AVC Decoder Configuration Record:",e),null}},Fa={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}},li=r=>{try{const e=new K(oi(r));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;const i=e.readAlignedByte(),n=e.readAlignedByte(),s=e.readAlignedByte();M(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=M(e),a===3&&(l=e.readBits(1)),o=M(e),c=M(e),e.skipBits(1),e.readBits(1))){for(let v=0;v<(a!==3?8:12);v++)if(e.readBits(1)){const D=v<6?16:64;let V=8,L=8;for(let te=0;te<D;te++){if(L!==0){const pe=st(e);L=(V+pe+256)%256}V=L===0?V:L}}}M(e);const u=M(e);if(u===0)M(e);else if(u===1){e.skipBits(1),st(e),st(e);const B=M(e);for(let v=0;v<B;v++)st(e)}M(e),e.skipBits(1);const d=M(e),f=M(e),h=16*(d+1),p=16*(f+1);let m=h,k=p;const y=e.readBits(1);if(y||e.skipBits(1),e.skipBits(1),e.readBits(1)){const B=M(e),v=M(e),O=M(e),D=M(e);let V,L;if((l===0?a:0)===0)V=1,L=2-y;else{const pe=a===3?1:2,ze=a===1?2:1;V=pe,L=ze*(2-y)}m-=V*(B+v),k-=L*(O+D)}let b=2,S=2,T=2,P=0,E={num:1,den:1},I=null,C=null;if(e.readBits(1)){if(e.readBits(1)){const ze=e.readBits(8);if(ze===255)E={num:e.readBits(16),den:e.readBits(16)};else{const Jn=Fa[ze];Jn&&(E=Jn)}}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)&&(M(e),M(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));const L=e.readBits(1);L&&os(e);const te=e.readBits(1);te&&os(e),(L||te)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),M(e),M(e),M(e),M(e),I=M(e),C=M(e))}if(I===null){g(C===null);const B=n&16;if((i===44||i===86||i===100||i===110||i===122||i===244)&&B)I=0,C=0;else{const v=d+1,O=f+1,D=(2-y)*O,V=Gr.find(te=>te.level>=s)??ee(Gr),L=Math.min(Math.floor(V.maxDpbMbs/(v*D)),16);I=L,C=L}}return g(C!==null),{profileIdc:i,constraintFlags:n,levelIdc:s,frameMbsOnlyFlag:y,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:h,codedHeight:p,displayWidth:m,displayHeight:k,pixelAspectRatio:E,colourPrimaries:b,matrixCoefficients:T,transferCharacteristics:S,fullRangeFlag:P,numReorderFrames:I,maxDecFrameBuffering:C}}catch(e){return H._error("Error parsing AVC SPS:",e),null}},os=r=>{const e=M(r);
1r.skipBits(4),r.skipBits(4);for(let t=0;t<=e;t++)M(r),M(r),r.skipBits(1);r.skipBits(5),r.skipBits(5),r.skipBits(5),r.skipBits(5)},Sc=(r,e)=>{if(e.description){const n=(fe(e.description)[21]&3)+1;return vn(r,n)}else return Aa(r)},$r=(r,e)=>{if(e.description){const n=(fe(e.description)[21]&3)+1;return _a(r,n)}else return Fr(r)},ir=r=>r>>1&63,An=r=>{try{const e=new K(oi(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}=xc(e,t);M(e);const u=M(e);let d=0;u===3&&(d=e.readBits(1));const f=M(e),h=M(e);let p=f,m=h;if(e.readBits(1)){const v=M(e),O=M(e),D=M(e),V=M(e);let L=1,te=1;const pe=d===0?u:0;pe===1?(L=2,te=2):pe===2&&(L=2,te=1),p-=(v+O)*L,m-=(D+V)*te}const k=M(e),y=M(e);M(e);const b=e.readBits(1)?0:t;let S=0;for(let v=b;v<=t;v++)M(e),S=M(e),M(e);M(e),M(e),M(e),M(e),M(e),M(e),e.readBits(1)&&e.readBits(1)&&Cc(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),M(e),M(e),e.skipBits(1));const T=M(e);if(Pc(e,T),e.readBits(1)){const v=M(e);for(let O=0;O<v;O++)M(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let P=2,E=2,I=2,C=0,_=0,B={num:1,den:1};if(e.readBits(1)){const v=Ec(e,t);B=v.pixelAspectRatio,P=v.colourPrimaries,E=v.transferCharacteristics,I=v.matrixCoefficients,C=v.fullRangeFlag,_=v.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:B,colourPrimaries:P,transferCharacteristics:E,matrixCoefficients:I,fullRangeFlag:C,maxDecFrameBuffering:S+1,spsMaxSubLayersMinus1:t,spsTemporalIdNestingFlag:i,generalProfileSpace:n,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:k,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:_}}catch(e){return H._error("Error parsing HEVC SPS:",e),null}},ui=r=>{try{const e=[],t=[],i=[],n=[];for(const l of Fr(r)){const u=r.subarray(l.offset,l.offset+l.length),d=ir(u[0]);d===se.VPS_NUT?e.push(u):d===se.SPS_NUT?t.push(u):d===se.PPS_NUT?i.push(u):(d===se.PREFIX_SEI_NUT||d===se.SUFFIX_SEI_NUT)&&n.push(u)}if(t.length===0||i.length===0)return null;const s=An(t[0]);if(!s)return null;let a=0;if(i.length>0){const l=i[0],u=new K(oi(l));u.skipBits(16),M(u),M(u),u.skipBits(1),u.skipBits(1),u.skipBits(3),u.skipBits(1),u.skipBits(1),M(u),M(u),st(u),u.skipBits(1),u.skipBits(1),u.readBits(1)&&M(u),st(u),st(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:se.VPS_NUT,nalUnits:e}]:[],...t.length?[{arrayCompleteness:1,nalUnitType:se.SPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:se.PPS_NUT,nalUnits:i}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ir(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}},xc=(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;u++)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}},Cc=r=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!r.readBits(1))M(r);else{const n=Math.min(64,1<<4+(e<<1));e>1&&st(r);for(let s=0;s<n;s++)st(r)}},Pc=(r,e)=>{const t=[];for(let i=0;i<e;i++)t[i]=Ic(r,i,e,t)},Ic=(r,e,t,i)=>{let n=0,s=0,a=0;if(e!==0&&(s=r.readBits(1)),s){if(e===t){const c=M(r);a=e-(c+1)}else a=e-1;r.readBits(1),M(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=M(r),c=M(r);for(let l=0;l<o;l++)M(r),r.readBits(1);for(let l=0;l<c;l++)M(r),r.readBits(1);n=o+c}return n},Ec=(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=Fa[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)&&(M(r),M(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(M(r),M(r),M(r),M(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&M(r),r.readBits(1)&&_c(r,!0,e)),r.readBits(1)&&(r.readBits(1),r.readBits(1),r.readBits(1),a=M(r),M(r),M(r),M(r),M(r)),{pixelAspectRatio:o,colourPrimaries:t,transferCharacteristics:i,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},_c=(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?M(r):l=r.readBits(1)===1;let u=1;l||(u=M(r)+1),i&&cs(r,u,s),n&&cs(r,u,s)}},cs=(r,e,t)=>{for(let i=0;i<e;i++)M(r),M(r),t&&(M(r),M(r)),r.readBits(1)},vc=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.nal
1UnitType&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)},Ac=r=>{try{const e=$(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,k=e.getUint16(t,!1);t+=2;const y=e.getUint8(t++),w=y>>6&3,b=y>>3&7,S=y>>2&1,T=y&3,P=e.getUint8(t++),E=[];for(let I=0;I<P;I++){const C=e.getUint8(t++),_=C>>7&1,B=C&63,v=e.getUint16(t,!1);t+=2;const O=[];for(let D=0;D<v;D++){const V=e.getUint16(t,!1);t+=2,O.push(r.subarray(t,t+V)),t+=V}E.push({arrayCompleteness:_,nalUnitType:B,nalUnits:O})}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:k,constantFrameRate:w,numTemporalLayers:b,temporalIdNested:S,lengthSizeMinusOne:T,arrays:E}}catch(e){return H._error("Error deserializing HEVC Decoder Configuration Record:",e),null}};var ge;(function(r){r[r.audAllowed=0]="audAllowed",r[r.beforeFirstVcl=1]="beforeFirstVcl",r[r.afterFirstVcl
1=2]="afterFirstVcl",r[r.eoBitstreamAllowed=3]="eoBitstreamAllowed",r[r.noMoreDataAllowed=4]="noMoreDataAllowed"})(ge||(ge={}));const Bc=(r,e)=>{const t=new Set;let i=ge.audAllowed;for(const s of $r(r,e)){if(i===ge.noMoreDataAllowed){t.add(s.offset);continue}const a=ir(r[s.offset]);if(i===ge.eoBitstreamAllowed&&a!==37){t.add(s.offset);continue}let o=!1;a===35?i>ge.audAllowed?o=!0:i=ge.beforeFirstVcl:a<=31?i>ge.afterFirstVcl?o=!0:i=ge.afterFirstVcl:a===36?i!==ge.afterFirstVcl?o=!0:i=ge.eoBitstreamAllowed:a===37?i<ge.afterFirstVcl?o=!0:i=ge.noMoreDataAllowed:a===32||a===33||a===34||a===39||a>=41&&a<=44||a>=48&&a<=55?i>ge.beforeFirstVcl?o=!0:i=ge.beforeFirstVcl:(a===38||a===40||a>=45&&a<=47||a>=56&&a<=63)&&i<ge.afterFirstVcl&&(o=!0),o&&t.add(s.offset)}if(t.size===0)return null;const n=[];for(const s of $r(r,e))t.has(s.offset)||n.push(r.subarray(s.offset,s.offset+s.length));return Sc(n,e)},Fc={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}},Ra=r=>{const e=new K(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 I=e.readBits(1),C=e.readBits(1);d=!I&&!C?3:I&&!C?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,k=p+1,y=m*k;let w=ee(yt).level;for(const E of yt)if(y<=E.maxPictureSize){w=E.level;break}const b=Fc[u],S=b?.colourPrimaries??2,T=b?.transferCharacteristics??2,P=b?.matrixCoefficients??2;return{profile:s,level:w,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:S,transferCharacteristics:T,matrixCoefficients:P}},Rc=r=>r.colourPrimaries!==2||r.transferCharacteristics!==2||r.matrixCoefficients!==2,Ma=function*(r){const e=new K(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)}},Bn=r=>{for(const{type:e,data:t}of Ma(r)){if(e!==1)continue;const i=new K(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 C=i.readBits(1);let _=0;if(C){if(i.skipBits(32),i.skipBits(32),i.readBits(1)){let D=0;for(;D<32&&!i.readBits(1);)D++;D<32&&i.skipBits(D)}_=i.readBits(1),_&&(c=i.readBits(5),i.skipBits(32),i.skipBits(5),i.skipBits(5))}const B=i.readBits(1),v=i.readBits(5);for(let O=0;O<=v;O++){i.skipBits(12);const D=i.readBits(5);if(O===0&&(a=D),D>7){const V=i.readBits(1);O===0&&(o=V)}if(_&&i.readBits(1)){const L=c+1;i.skipBits(L),i.skipBits(L),i.skipBits(1)}B&&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 C=i.readBits(1);C&&(i.skipBits(1),i.skipBits(1));const _=i.readBits(1);let B=0;_?B=2:B=i.readBits(1),B>0&&(i.readBits(1)||i.skipBits(1)),C&&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 k=0;n!==1&&(k=i.readBits(1));let y=2,w=2,b=2;i.readBits(1)&&(y=i.readBits(8),w=i.readBits(8),b=i.readBits(8));let T=0,P=1,E=1,I=0;return k?T=i.readBits(1):y===1&&w===13&&b===0?(T=1,P=0,E=0):(T=i.readBits(1),n===0?(P=1,E=1):n===1?(P=0,E=0):m===12?(P=i.readBits(1),E=P?i.readBits(1):0):(P=1,E=0),P&&E&&(I=i.readBits(2))),{profile:n,level:a,tier:o,bitDepth:m,monochrome:k,chromaSubsamplingX:P,chromaSubsamplingY:E,chromaSamplePosition:I,videoFullRangeFlag:T,colourPrimaries:y,transferCharacteristics:w,matrixCoefficients:b}}return null},Mc=r=>r.colourPrimaries!==2||r.transferCharacteristics!==2||r.matrixCoefficients!==2,Oa=r=>{if(r.length<36)return null;const t=$(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)}},Fn=r=>{const e=$(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}},Oc=[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],Dc=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:Oc[e]*i}},zc=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 K(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}},di=(r,e,t)=>{switch(r){case"avc":{for(const i of va(t,e)){const n=t[i.offset],s=ai(n);if(s>=le.NON_IDR_SLICE&&s<=le.SLICE_DPC)return"delta";if(s===le.IDR)return"key";if(s===le.SEI&&!Ji()){const a=t.subarray(i.offset,i.offset+i.length),o=oi(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 K(o);f.pos=8*c;const h=M(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 $r(t,e)){const n=ir(t[i.offset]);if(n<se.BLA_W_LP)return"delta";if(n<=se.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{const i=new K(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 Ma(t))if(n===1){const a=new K(s);a.skipBits(4),i=!!a.readBits(1)}else if(n===3||n===6||n===7){if(i)return"key";const a=new K(s);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}case"prores":return"key";default:Ee(r),g(!1)}};var Jt;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(Jt||(Jt={}));const tn=(r,e)=>{const t=$(r);let i=0;const n=t.getUint32(i,!0);i+=4;const s=Se.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=Se.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=Ca(f),p=$(h),m=p.getUint32(0,!1),k=p.getUint32(4,!1),y=String.fromCharCode(...h.subarray(8,8+k)),w=p.getUint32(8+k,!1),b=Se.decode(h.subarray(12+k,12+k+w)),S=p.getUint32(k+w+28),T=h.subarray(k+w+32,k+w+32+S);e.images??=[],e.images.push({data:T,mimeType:y,kind:m===3?"coverFront":m===4?"coverBack":"unknown",name:void 0,description:b||void 0})}break}}},Rn=[2,1,2,3,3,4,4,5],Da=r=>{if(r.length<7||r[0]!==11||r[1]!==119)return null;const e=new K(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);
1return{fscod:t,bsid:n,bsmod:s,acmod:a,lfeon:o,bitRateCode:c}},Nc=[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],Uc=1536,za=[1,2,3,6],Na=r=>{if(r.length<6||r[0]!==11||r[1]!==119)return null;const e=new K(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=za[a];let d;return n<3?d=si[n]/1e3:d=Ea[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}]}},Vc=r=>{if(r.length<2)return null;const e=new K(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>0?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?si[e.fscod]:e.fscod2!==null&&e.fscod2<3?Ea[e.fscod2]:null},Va=r=>{const e=r.substreams[0];g(e);let t=Rn[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},Wc=1683496997,Wr=18,rn=10,Lc=4096,ls=32,Mn=20,Hc=8,qc=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],jc=[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],$c=[16,16,20,20,0,24,24,0],Kr=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Kc=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Gc=8,Xc=44646,Qc=[32e3,44100,48e3,0],Yc=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Wa=[512,1024,2048,4096],On=r=>{const e=Ha(r),t=$(r);let i=e?Math.ceil(e.frameSize/4)*4:0,n=null;for(;i+4<=r.length&&t.getUint32(i)===Wc;){const a=Lr(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=On(r);return e?.core?e.hasExtensions?"dtsh":"dtsc":null},Ha=r=>{if(r.length<Wr||r[0]!==127||r[1]!==254||r[2]!==128||r[3]!==1)return null;const e=new K(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%Hc!==0)return null;const n=e.readBits(14)+1;if(n<96)return null;const s=e.readBits(6);if(s>=Kr.length)return null;const a=qc[e.readBits(4)];if(a===0)return null;const o=jc[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=$c[e.readBits(3)];if(l===0)return null;const u=c!==0;return{frameSize:n,sampleRate:a,numberOfChannels:Kr[s]+(u?1:0),sampleCount:i*ls,channelLayout:Kc[s]|(u?Gc:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:l}},Lr=r=>{if(r.length<rn||r[0]!==100||r[1]!==88||r[2]!==32||r[3]!==37)return null;const e=new K(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=Qc[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 y=0;y<u;y++)f.push(e.readBits(t+1));for(const y of f)e.skipBits(8*Zi(y));if(e.readBits(1)){e.skipBits(2);const y=e.readBits(2)+1<<2,w=e.readBits(2)+1;e.skipBits(w*y)}for(let y=0;y<d;y++)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=Yc[e.readBits(4)],m=e.readBits(8)+1;let k=0;if(e.readBits(1)&&(m>2&&e.skipBits(1),m>6&&e.skipBits(1),e.readBits(1))){const y=e.readBits(2)+1<<2;k=e.readBits(y)}return c===0||e.getBitsLeft()<0?o:{frameSize:a,asset:{sampleRate:p,numberOfChannels:m,sampleC
1ount:Math.round(l*p/c),channelLayout:k,pcmResolution:h}}},Zc=r=>{if(r.length<Mn)return null;const e=$(r),t=e.getUint32(0);if(t===0)return null;const i=new K(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=el(o):a<Kr.length&&(c=Kr[a]+s),{sampleRate:t,maxBitrate:e.getUint32(4),avgBitrate:e.getUint32(8),pcmSampleDepth:r[12],sampleCount:Wa[n],channelLayout:o,numberOfChannels:c}},Jc=r=>{const e=new Uint8Array(Mn),t=$(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 K(e);return n.seekToByte(13),n.writeBits(2,Math.max(Wa.indexOf(r.sampleCount),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},el=r=>Zi(r)+Zi(r&Xc);const _e=["avc","hevc","vp9","av1","vp8","prores"],me=["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"],fi=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],De=[...fi,...me],Dt=["webvtt"],Gr=[{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}],yt=[{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",Rt=["ap4x","ap4h","apch","apcn","apcs","apco"],Xr=["dtsc","dtsh","dtsl","dtse"],tl=[{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}],rl=(r,e,t,i,n)=>{if(r==="avc"){const a=Math.ceil(e/16)*Math.ceil(t/16),o=Gr.find(f=>a<=f.maxMacroblocks&&i<=f.maxBitrate)??ee(Gr),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)??ee(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.${(yt.find(l=>a<=l.maxPictureSize&&i<=l.maxBitrate)??ee(yt)).level.toString().padStart(2,"0")}.08`}else if(r==="av1"){const a=e*t,o=ds.find(u=>a<=u.maxPictureSize&&i<=u.maxBitrate)??ee(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=tl.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 Ee(r)}throw new TypeError(`Unhandled codec '${String(r)}'.`)},il=r=>{const e=r.split("."),t=Number(e[1]),i=Number(e[2]),n=Number(e[3]),s=e[4]?Number(e[4]):1;return[1,1,t,2,1,i,3,1,n,4,1,s]},qa=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,k=e[5]?Number(e[5][2]):0,y=(l<<7)+(d<<6)+(f<<5)+(h<<4)+(p<<3)+(m<<2)+k;return[n,c,y,0]},Dn=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}.${xr(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}.${xr(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 k=$(t),y=k.getUint8(1);l=y>>6&3,u=y&31,d=es(k.getUint32(2)),f=y>>5&1,h=k.getUint8(12),p=[];for(let w=0;w<6;w++)p.push(k.getUint8(6+w))}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(k=>k.toString(16).toUpperCase()).join(".")),m}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){const w=r.width*r.height;let b=ee(yt).level;for(const S of yt)if(w<=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"),k=a.videoFullRangeFlag.toString().padStart(2,"0");let y=`vp09.${l}.${u}.${d}.${f}`;return y+=`.${h}.${p}.${m}.${k}`,y.endsWith(fs)&&(y=y.slice(0,-fs.length)),y}else if(e==="av1"){if(!o){const S=r.width*r.height;let T=ee(yt).level;for(const P of yt)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?zt[i.primaries]:1,k=i?.transfer?Nt[i.transfer]:1,y=i?.matrix?Ut[i.matrix]:1,w=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+=`.${k.toString().padStart(2,"0")}`,b+=`.${y.toString().padStart(2,"0")}`,b+=`.${w}`,b.endsWith(hs)&&(b=b.slice(0,-hs.length)),b}else{if(e==="prores")return c??"apch";e!==null&&Ee(e)}}throw new TypeError(`Unhandled codec '${e}'.`)},ja=r=>{switch(r.codec){case"avc":{let e=r.avcCodecInfo?.sequenceParameterSets[0];if(!e&&r.codecDescription&&(e=Ba(r.codecDescription)?.sequenceParameterSets[0]),e){const t=li(e);if(t)return{primaries:Je[t.colourPrimaries],transfer:et[t.transferCharacteristics],matrix:tt[t.matrixCoefficients],fullRange:!!t.fullRangeFlag}}}break;case"hevc":{let e=r.hevcCodecInfo?.arrays.find(t=>t.nalUnitType===se.SPS_NUT)?.nalUnits[0];if(!e&&r.codecDescription&&(e=Ac(r.codecDescription)?.arrays.find(t=>t.nalUnitType===se.SPS_NUT)?.nalUnits[0]),e){const t=An(e);if(t)return{primaries:Je[t.colourPrimaries],transfer:et[t.transferCharacteristics],matrix:tt[t.matrixCoefficients],fullRange:!!t.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(r.vp9CodecInfo)return{primaries:Je[r.vp9CodecInfo.colourPrimaries],transfer:et[r.vp9CodecInfo.transferCharacteristics],matrix:tt[r.vp9CodecInfo.matrixCoefficients],fullRange:!!r.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(r.av1CodecInfo)return{primaries:Je[r.av1CodecInfo.colourPrimaries],transfer:et[r.av1CodecInfo.transferCharacteristics],matrix:tt[r.av1CodecInfo.matrixCoefficients],fullRange:!!r.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(r.proresCodecInfo)return{primaries:Je[r.proresCodecInfo.colourPrimaries],transfer:et[r.proresCodecInfo.transferCharacteristics],matrix:tt[r.proresCodecInfo.matrixCoefficients],fullRange:r.proresCodecInfo.fullRange};break}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},nl=(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(me.includes(r))return r;throw new TypeError(`Unhandled codec '${r}'.`)},zn=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=En(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&&me.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},Rr=48e3,$a=/^pcm-([usf])(\d+)(be)?$/,$e=r=>
1{if(g(me.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=$a.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}},at=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":Rt.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":Xr.includes(r)?"dts":r==="ulaw"?"ulaw":r==="alaw"?"alaw":$a.test(r)?r:r==="webvtt"?"webvtt":null,sl=r=>r==="avc"?{avc:{format:"avc"}}:r==="hevc"?{hevc:{format:"hevc"}}:{},al=r=>r==="aac"?{aac:{format:"aac"}}:r==="opus"?{opus:{format:"opus"}}:{},ol=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Rt],cl=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,ll=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,ul=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,dl=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Nn=(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(!ol.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&&!ti(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(zt);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(Nt);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(Ut);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(", ")}.`);
1if(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(!cl.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(!ll.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(!ul.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(!dl.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(Rt.some(t=>r.decoderConfig.codec.startsWith(t))&&!Rt.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: ${Rt.join(", ")}.`);if(e!==null&&at(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}'.`)},fl=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],Un=(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(!fl.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&&!ti(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(!Xr.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: ${Xr.join(", ")}.`)}else if((r.decoderConfig.codec.startsWith("pcm")||r.decoderConfig.codec.startsWith("ulaw")||r.decoderConfig.codec.startsWith("alaw"))&&!me.includes(r.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${me.join(", ")}).`);if(e!==null&&at(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}'.`)},Ka=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 Mt=4,hl=[44100,48e3,32e3],ml=[-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,pl=(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,gl=(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,k=s>>2&1,y=s&3,w=ml[a*16*4+l*16+u];if(w===-1)return{header:null,bytesAdvanced:1};const b=w*1e3,S=hl[d]>>a+o,T=pl(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:k,emphasis:y,audioSamplesInFrame:P},bytesAdvanced:1}},nn=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t};var Qr;(function(r){r[r.FrameCount=1]="FrameCount",r[r.FileSize=2]="FileSize",r[r.Toc=4]="Toc"})(Qr||(Qr={}));const Pr=r=>r===3?1:2;class ut{constructor(e){this.input=e}dispose(){}}const ve=new Uint8Array(0);class Y{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.");
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(kt*this.timestamp)}get microsecondDuration(){return Math.trunc(kt*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 Y(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 Y(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=$(r);let t=0;const i=e.getUint8(t);t+=1,t+=3;const n=xr(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(xr(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&&Pa(r.data,e.data);const rt=8,vt=16,mt=r=>{let e=R(r);const t=ie(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}},xt=r=>Bt(r)/65536,vi=r=>Bt(r)/1073741824,Ai=r=>{let e=0;for(let t=0;t<4;t++){e<<=7;const i=z(r);if(e|=i&127,(i&128)===0)break}return e},Ne=r=>{let e=ne(r);return r.skip(2),e=Math.min(e,r.remainingLength),Se.decode(N(r,e))},kl=r=>{const e=mt(r);if(!e||e.name!=="data"||r.remainingLength<8)return null;const t=R(r);r.skip(4);const i=N(r,e.contentSize-8);switch(t){case 1:return Se.decode(i);case 2:return new TextDecoder("utf-16be").decode(i);case 13:return new Zt(i,"image/jpeg");case 14:return new Zt(i,"image/png");case 27:return new Zt(i,"image/bmp");default:return i}};const Le=16,Xe=new Uint32Array(256),Ht=new Uint32Array(256),qt=new Uint32Array(256),jt=new Uint32Array(256),$t=new Uint32Array(256),ce=new Uint32Array(256),eo=new Uint32Array(10);let to=!1;const yl=()=>{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);Xe[s]=a<<24|a<<16|a<<8|a,ce[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;Ht[s]=f,qt[s]=f>>>8|f<<24,jt[s]=f>>>16|f<<16,$t[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(Le/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Le),this.out=new Uint8Array(Le),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||yl();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]^Xe[a>>>16&255]&4278190080^Xe[a>>>8&255]&16711680^Xe[a>>>0&255]&65280^Xe[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]=Ht[Xe[o>>>24&255]&255]^qt[Xe[o>>>16&255]&255]^jt[Xe[o>>>8&255]&255]^$t[Xe[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 y=1;y<10;y++){const w=y*4;l=Ht[e>>>24]^qt[n>>>16&255]^jt[i>>>8&255]^$t[t&255]^this.roundkey[w],u=Ht[t>>>24]^qt[e>>>16&255]^jt[n>>>8&255]^$t[i&255]^this.roundkey[w+1],d=Ht[i>>>24]^qt[t>>>16&255]^jt[e>>>8&255]^$t[n&255]^this.roundkey[w+2],f=Ht[n>>>24]^qt[i>>>16&255]^jt[t>>>8&255]^$t[e&255]^this.roundkey[w+3],e=l,t=u,i=d,n=f}const h=ce[e>>>24&255]&4278190080^ce[n>>>16&255]&16711680^ce[i>>>8&255]&65280^ce[t>>>0&255]&255^this.roundkey[40],p=ce[t>>>24&255]&4278190080^ce[e>>>16&255]&16711680^ce[n>>>8&255]&65280^ce[i>>>0&255]&255^this.roundkey[41],m=ce[i>>>24&255]&4278190080^ce[t>>>16&255]&16711680^ce[e>>>8&255]&65280^ce[n>>>0&255]&255^this.roundkey[42],k=ce[n>>>24&255]&4278190080^ce[i>>>16&255]&16711680^ce[t>>>8&255]&65280^ce[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,k^this.iv[3],!1),this.iv[0]=s,this.iv[1]=a,this.iv[2]=o,this.iv[3]=c}}const wl=(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=N(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 k=p.subarray(0,f-m);c.enqueue(k),c.close(),t()}},cancel:()=>{t()}})};class Wn extends ut{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,rt,vt);if(A(n)&&(n=await n),!n)break;const s=e,a=mt(n);if(!a)break;if(a.name==="ftyp"||a.name==="styp"){const o=ie(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=R(n),a=this.reader.fileSize-s;if(a>=0&&a<=this.reader.fileSize-vt){let o=this.reader.requestSliceRange(a,rt,vt);if(A(o)&&(o=await o),o){const c=mt(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!==Wn)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&&me.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){g(e.info?.type==="audio");const s=$e(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=G(t.sampleTimingEntries,h,I=>I.startIndex),k=t.sampleTimingEntries[m],y=G(t.sampleTimingEntries,p,I=>I.startIndex),w=t.sampleTimingEntries[y],b=k.startDecodeTimestamp+(h-k.startIndex)*k.delta,T=w.startDecodeTimestamp+(p-w.startIndex)*w.delta-b,P=ee(a);P&&P.delta===T?P.count++:a.push({startIndex:l.startChunkIndex+f,startDecodeTimestamp:b,count:1,delta:T});const E=l.samplesPerChunk*s.sampleSize*e.info.numberOfChannels;o.push(E)}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,rt,vt);A(t)&&(t=await t),g(t);const i=mt(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)Bi(a,u.timestamp);else{const d=G(c,s.moofOffset-1,f=>f.moofOffset);if(d!==-1){const f=c[d];Bi(a,f.endTimestamp)}}a.startTimestampIsFinal=!0}const l=G(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-rt&&this.traverseBox(e););}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-rt;){const i=e.filePos,n=mt(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=i+n.totalSize}}traverseBox(e){const t=e.filePos,i=mt(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=z(e);e.skip(3),a===1?(e.skip(16),this.movieTimescale=R(e),this.movieDurationInTimescale=Ce(e)):(e.skip(8),this.movieTimescale=R(e),this.movieDurationInTimescale=R(e))}break;case"trak":{const a={id:-1,demuxer:this,trackBacking:null,disposition:{...lt,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:he,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=z(e),l=!!(Qe(e)&1);if(a.disposition.default=l,o===0)e.skip(8),a.id=R(e),e.skip(4),a.durationInMovieTimescale=R(e);else if(o===1)e.skip(16),a.id=R(e),e.skip(4),a.durationInMovieTimescale=Ce(e);else throw new Error(`Incorrect track header version ${o}.`);e.skip(16);const u=[xt(e),xt(e),vi(e),xt(e),xt(e),vi(e),xt(e),xt(e),vi(e)],d=ei(Yi(xl(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=z(e);e.skip(3);let c=!1,l=0;const u=R(e);for(let d=0;d<u;d++){const f=o===1?Ce(e):R(e),h=o===1?yd(e):Bt(e),p=xt(e);
1if(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=z(e);e.skip(3),o===0?(e.skip(8),a.timescale=R(e),a.durationInMediaTimescale=R(e)):o===1&&(e.skip(16),a.timescale=R(e),a.durationInMediaTimescale=Ce(e));let c=ne(e);if(c>0){a.languageCode="";for(let l=0;l<3;l++)a.languageCode=String.fromCharCode(96+(c&31))+a.languageCode,c>>=5;Sn(a.languageCode)||(a.languageCode=he)}}break;case"hdlr":{const a=this.currentTrack;if(!a)break;e.skip(8);const o=ie(e,4);o==="vide"?a.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...Ta},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=z(e);e.skip(3);const c=R(e);for(let l=0;l<c;l++){const u=e.filePos,d=mt(e);if(!d)break;a.internalCodecId=d.name;const f=d.name.toLowerCase();if(a.info.type==="video"){e.skip(24),a.info.width=ne(e),a.info.height=ne(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":Rt.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=ne(e);e.skip(6);let p=ne(e),m=ne(e);e.skip(4);let k=R(e)/65536,y=null;o===0&&h>0&&(h===1?(e.skip(4),m=8*R(e),e.skip(8)):h===2&&(e.skip(4),k=Lo(e),p=R(e),e.skip(4),m=R(e),y=R(e),e.skip(8))),a.info.numberOfChannels=p,a.info.sampleRate=k,a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos));const w=f==="enca"?a.frmaCodecString:f;if(a.frmaCodecString=null,w!=="mp4a")if(w==="opus")a.info.codec="opus",a.info.sampleRate=Rr;else if(w==="flac")a.info.codec="flac";else if(w==="ulaw")a.info.codec="ulaw";else if(w==="alaw")a.info.codec="alaw";else if(w==="ac-3")a.info.codec="ac3";else if(w==="ec-3")a.info.codec="eac3";else if(Xr.includes(w))a.info.codec="dts",a.info.dtsFormat=w;else if(w==="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} for codec 'twos'.`),a.info.codec=null);else if(w==="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(w==="raw ")a.info.codec="pcm-u8";else if(w==="in24")a.info.codec=a.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(w==="in32")a.info.codec=a.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(w==="fl32")a.info.codec=a.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(w==="fl64")a.info.codec=a.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(w==="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(w==="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(w==="lpcm"&&y!==null){const b=m+7>>3,S=!!(y&1),T=!!(y&2),P=y&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 w===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=ie(e,4).toLowerCase();a.frmaCodecString=c}break;case"schm":{const a=this.currentTrack;if(!a)break;e.skip(4);const o=ie(e,4);
1o==="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=z(e);e.skip(3),e.skip(1);const c=z(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=z(e)!==0,a.encryptionInfo.defaultPerSampleIvSize=z(e),a.encryptionInfo.defaultKid=xr(N(e,16)),a.encryptionInfo.defaultIsProtected&&a.encryptionInfo.defaultPerSampleIvSize===0){const l=z(e),u=new Uint8Array(16);u.set(N(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=N(e,i.contentSize)}break;case"hvcC":{const a=this.currentTrack;if(!a||(g(a.info),i.contentSize===0))break;a.info.codecDescription=N(e,i.contentSize)}break;case"vpcC":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="video"),e.skip(4);const o=z(e),c=z(e),l=z(e),u=l>>4,d=l>>1&7,f=l&1,h=z(e),p=z(e),m=z(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=z(e),c=o>>5,l=o&31,u=z(e),d=u>>7,f=u>>6&1,h=u>>5&1,p=u>>4&1,m=u>>3&1,k=u>>2&1,y=u&3,w=c===2&&f?h?12:10:f?10:8;e.skip(1);const b=N(e,i.contentSize-4),S=Bn(b);a.info.av1CodecInfo={profile:c,level:l,tier:d,bitDepth:w,monochrome:p,chromaSubsamplingX:m,chromaSubsamplingY:k,chromaSamplePosition:y,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=ie(e,4);if(o!=="nclx"&&o!=="nclc")break;const c=ne(e),l=ne(e),u=ne(e);let d;o==="nclx"&&(d=!!(z(e)&128)),a.info.colorSpace={primaries:Je[c],transfer:et[l],matrix:tt[u],fullRange:d}}break;case"pasp":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="video");const o=R(e),c=R(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=z(e);g(o===3),Ai(e),e.skip(2);const c=z(e),l=(c&128)!==0,u=(c&64)!==0,d=(c&32)!==0;if(l&&e.skip(2),u){const k=z(e);e.skip(k)}d&&e.skip(2);const f=z(e);g(f===4);const h=Ai(e),p=e.filePos,m=z(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 k=z(e);g(k===5);const y=Ai(e);if(a.info.codecDescription=N(e,y),a.info.codec==="aac"){const w=En(a.info.codecDescription);w.outputNumberOfChannels!==null&&(a.info.numberOfChannels=w.outputNumberOfChannels),w.outputSampleRate!==null&&(a.info.sampleRate=w.outputSampleRate)}}}break;case"enda":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="audio"),a.info.pcmLittleEndian=!!(ne(e)&255)}break;case"pcmC":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="audio"),e.skip(4);const o=z(e);a.info.pcmLittleEndian=!!(o&1),a.info.pcmSampleSize=z(e)}break;case"dOps":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="audio"),e.skip(1);const o=z(e),c=ne(e),l=R(e),u=pn(e),d=z(e);let f;d!==0?f=N(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=z(e),m=Qe(e);if((p&o)===Jt.STREAMINFO){e.skip(10);const y=R(e),w=y>>>12,b=(y>>9&7)+1;a.info.sampleRate=w,a.info.numberOfChannels=b,e.skip(20)}else e.skip(m);if(p&c)break}const u=e.filePos;e.filePos=l;const d=N(e,u-l),f=new Uint8Array(4+d.byteLength);new DataView(f.buffer).setUint32(0,1716281667,!1),f.set(d,4),a.info.codecDescription=f}break;case"dac3":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="audio");const o=N(e,3),c=new K(o),l=c.readBits(2);c.skipBits(8);const u=c.readBits(3),d=c.readBits(1);l<3&&(a.info.sampleRate=si[l]),a.info.numberOfChannels=Rn[u]+d}break;case"dec3":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="audio");const o=N(e,i.contentSize),c=Vc(o);if(!c){H._warn("Invalid dec3 box contents, ignoring.");break}const l=Ua(c);l!==null&&(a.info.sampleRate=l),a.info.numberOfChannels=Va(c)}break;case"ddts":{const a=this.currentTrack;if(!a)break;g(a.info?.type==="audio");const o=N(e,Math.min(i.contentSize,Mn)),c=Zc(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=R(e);let c=0,l=0;for(let u=0;u<o;u++){const d=R(e),f=R(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=R(e);let c=0;for(let l=0;l<o;l++){const u=R(e),d=Bt(e);
1a.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=R(e),c=R(e);if(o===0)for(let l=0;l<c;l++){const u=R(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);const o=z(e),c=R(e),l=N(e,Math.ceil(c*o/8)),u=new K(l);for(let d=0;d<c;d++){const f=u.readBits(o);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=R(e);for(let c=0;c<o;c++){const l=R(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=R(e);for(let l=0;l<o;l++){const u=R(e)-1,d=R(e),f=R(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=R(e);for(let c=0;c<o;c++){const l=R(e);a.sampleTable.chunkOffsets.push(l)}}break;case"co64":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=R(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=z(e);e.skip(3);const o=a===1?Ce(e):R(e);this.movieDurationInTimescale=o}break;case"trex":{e.skip(4);const a=R(e),o=R(e),c=R(e),l=R(e),u=R(e);this.fragmentTrackDefaults.push({trackId:a,defaultSampleDescriptionIndex:o,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:u})}break;case"tfra":{const a=z(e);e.skip(3);const o=R(e),c=this.tracks.find(w=>w.id===o);if(!c)break;const l=R(e),u=(l&48)>>4,d=(l&12)>>2,f=l&3,h=[z,ne,Qe,R],p=h[u],m=h[d],k=h[f],y=R(e);for(let w=0;w<y;w++){const b=a===1?Ce(e):R(e),S=a===1?Ce(e):R(e);p(e),m(e),k(e),c.fragmentLookupTable.push({timestamp:b,moofOffset:S})}c.fragmentLookupTable.sort((w,b)=>w.timestamp-b.timestamp);for(let w=0;w<c.fragmentLookupTable.length-1;w++){const b=c.fragmentLookupTable[w],S=c.fragmentLookupTable[w+1];b.timestamp===S.timestamp&&(c.fragmentLookupTable.splice(w+1,1),w--)}}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[ee(a.presentationTimestamps).sampleIndex];a.startTimestamp=o.presentationTimestamp,a.endTimestamp=c.presentationTimestamp+c.duration;const{currentFragmentState:l}=this.currentTrack;g(l),l.startTimestamp!==null&&(Bi(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(N(e,i.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(a):this.currentTrack||this.pss
1hBoxes.push(a)}break;case"tfhd":{g(this.currentFragment),e.skip(1);const a=Qe(e),o=!!(a&1),c=!!(a&2),l=!!(a&8),u=!!(a&16),d=!!(a&32),f=!!(a&65536),h=!!(a&131072),p=R(e),m=this.tracks.find(y=>y.id===p);if(!m)break;const k=this.fragmentTrackDefaults.find(y=>y.trackId===p);this.currentTrack=m,m.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:k?.defaultSampleDescriptionIndex??null,defaultSampleDuration:k?.defaultSampleDuration??null,defaultSampleSize:k?.defaultSampleSize??null,defaultSampleFlags:k?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},o?m.currentFragmentState.baseDataOffset=Ce(e):h&&(m.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(m.currentFragmentState.sampleDescriptionIndex=R(e)),l&&(m.currentFragmentState.defaultSampleDuration=R(e)),u&&(m.currentFragmentState.defaultSampleSize=R(e)),d&&(m.currentFragmentState.defaultSampleFlags=R(e)),f&&(m.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const a=this.currentTrack;if(!a)break;g(a.currentFragmentState);const o=z(e);e.skip(3);const c=o===0?R(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=z(e),c=Qe(e),l=!!(c&1),u=!!(c&4),d=!!(c&256),f=!!(c&512),h=!!(c&1024),p=!!(c&2048),m=R(e);let k=null;l&&(k=Bt(e));let y=null;u&&(y=R(e));let w;this.currentFragment.trackData.has(a.id)?(w=this.currentFragment.trackData.get(a.id),k!==null&&(w.currentOffset=a.currentFragmentState.baseDataOffset+k)):(w={track:a,currentTimestamp:0,currentOffset:a.currentFragmentState.baseDataOffset+(k??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(a.id,w));for(let b=0;b<m;b++){let S;d?S=R(e):(g(a.currentFragmentState.defaultSampleDuration!==null),S=a.currentFragmentState.defaultSampleDuration);let T;f?T=R(e):(g(a.currentFragmentState.defaultSampleSize!==null),T=a.currentFragmentState.defaultSampleSize);let P;h?P=R(e):(g(a.currentFragmentState.defaultSampleFlags!==null),P=a.currentFragmentState.defaultSampleFlags),b===0&&y!==null&&(P=y);let E=0;p&&(o===0?E=R(e):E=Bt(e));const I=!(P&65536);w.samples.push({presentationTimestamp:w.currentTimestamp+E,duration:S,byteOffset:w.currentOffset,byteSize:T,isKeyFrame:I,encryption:null}),w.currentOffset+=T,w.currentTimestamp+=S}this.currentFragment.implicitBaseDataOffset=w.currentOffset}break;case"saiz":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;if(e.skip(1),Qe(e)&1){const f=ie(e,4),h=R(e);if(f!==a.encryptionInfo.scheme||h!==0)break}const c=z(e),l=R(e);let u=null;c===0&&l>0&&(u=N(e,l));const d=ks(a);d.defaultSampleInfoSize=c,d.sampleSizes=u,d.sampleCount=l}break;case"saio":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;const o=z(e);if(Qe(e)&1){const f=ie(e,4),h=R(e);if(f!==a.encryptionInfo.scheme||h!==0)break}const l=R(e);if(l===0)break;l>1&&H._warn("Multiple saio entries are not supported; using the first offset only.");let u=o===0?R(e):Number(Ce(e));this.currentFragment&&(u+=this.currentFragment.moofOffset);const d=ks(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=!!(Qe(e)&2),u=R(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(N(e,d),0):h.set(a.encryptionInfo.defaultConstantIv,0);let p=null;if(l){const k=ne(e);p=[];for(let y=0;y<k;y++){const w=ne(e),b=R(e);p.push({clearLen:w,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]??=Ne(c):this.metadataTags.raw[o.name]??=N(c,o.contentSize),c.filePos=l}switch(o.name){case"meta":c.skip(-o.headerSize),this.traverseBox(c);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=Se.decode(N(c,o.contentSize)):this.metadataTags.title??=Ne(c);break;case"©des":this.currentTrack||(this.metadataTags.description??=Ne(c));break;case"©ART":this.currentTrack||(this.metadataTags.artist??=Ne(c));break;case"©alb":this.currentTrack||(this.metadataTags.album??=Ne(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Ne(c));break;case"©gen":this.currentTrack||(this.metadataTags.genre??=Ne(c));break;case"©day":if(!this.currentTrack){const l=new Date(Ne(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"©cmt":this.currentTrack||(this.metadataTags.comment??=Ne(c));break;case"©lyr":this.currentTrack||(this.metadataTags.lyrics??=Ne(c));break}}}break;case"meta":{if(this.currentTrack)break;const o=R(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=R(e);for(let o=0;o<a;o++){const c=R(e);e.skip(4);const l=Se.decode(N(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=kl(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 Zt?(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=$(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=$(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 Cr(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=sn(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=G(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=bl(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=bn(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=Sl(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=Tl(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=N(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??=ys(this.internalTrack.encryptionInfo),u&&(s=await ws(this.internalTrack,u,s,null))}}const a=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=n.duration/this.internalTrack.timescale,c=new Y(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=N(u,s.byteSize),this.internalTrack.encryptionInfo){const d=s.encryption??ys(this.internalTrack.encryptionInfo);d&&(a=await ws(this.internalTrack,d,a,e))}}const o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,l=ne
1w Y(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:k,correctSampleFound:y}=t(e);if(y)return this.fetchPacketInFragment(e,k,s);k!==-1&&(c=e,l=k)}const u=G(this.internalTrack.fragmentLookupTable,i,k=>k.timestamp),d=u!==-1?this.internalTrack.fragmentLookupTable[u]:null,f=G(this.internalTrack.fragmentPositionCache,i,k=>k.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 k=a.reader.requestSliceRange(m,rt,vt);if(A(k)&&(k=await k),!k)break;const y=m,w=mt(k);if(!w)break;if(w.name==="moof"){o=await a.readFragment(y);const{sampleIndex:b,correctSampleFound:S}=t(o);if(S)return this.fetchPacketInFragment(o,b,s);b!==-1&&(c=o,l=b)}m=y+w.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){const k=this.internalTrack.fragmentLookupTable[u-1];g(!k||k.timestamp<d.timestamp);const y=k?.timestamp??-1/0;return this.performFragmentedLookup(null,t,y,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&&ci(t.data)}else if(this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription){const t=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=t&&ui(t.data)}else if(this.internalTrack.info.codec==="vp9"&&(!this.internalTrack.info.vp9CodecInfo||!Rc(this.internalTrack.info.vp9CodecInfo))){const t=await this.getFirstPacket({}),i=t&&Ra(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||!Mc(this.internalTrack.info.av1CodecInfo))){const t=await this.getFirstPacket({}),i=t&&Bn(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&&Oa(t.data)}if(!wn(this.internalTrack.info.colorSpace)){const t=ja(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:Dn(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:zn(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}}const sn=(r,e)=>{if(r.presentationTimestamps){const t=G(r.presentationTimestamps,e,i=>i.presentationTimestamp);return t===-1?-1:r.presentationTimestamps[t].sampleIndex}else{const t=G(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)}},bl=(r,e)=>{if(!r.keySampleIndices)return sn(r,e);if(r.presentationTimestamps){const t=G(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(Ar(r.keySampleIndices,n,a=>a)!==-1)return n}return-1}else{const t=sn(r,e),i=G(r.keySampleIndices,t,n=>n);return r.keySampleIndices[i]??-1}},Tl=(r,e)=>{const t=G(r.sampleTimingEntries,e,y=>y.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=G(r.sampleCompositionTimeOffsets,e,y=>
1y.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=G(r.sampleToChunk,e,y=>y.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 y=h;y<h+u.samplesPerChunk;y++){const w=r.sampleSizes[y];y<e&&(m+=w),p+=w}let k=i.delta;if(r.presentationTimestamps){const y=r.presentationTimestampIndexMap[e];g(y!==void 0),y<r.presentationTimestamps.length-1&&(k=r.presentationTimestamps[y+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:k,sampleOffset:m,sampleSize:c,chunkOffset:f,chunkSize:p,isKeyFrame:r.keySampleIndices?Ar(r.keySampleIndices,e,y=>y)!==-1:!0}},Sl=(r,e)=>{if(!r.keySampleIndices)return e+1;const t=G(r.keySampleIndices,e,i=>i);return r.keySampleIndices[t+1]??-1},Bi=(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},xl=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,ks=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(N(n,s),0):l.set(e.defaultConstantIv,0);let u=null;if(c>s){const d=ne(n);u=[];for(let f=0;f<d;f++){const h=ne(n),p=R(n);u.push({clearLen:h,protectedLen:p})}}a.push({iv:l,subsamples:u})}return t.resolved=a,a},ys=r=>r.defaultConstantIv?{iv:r.defaultConstantIv,subsamples:null}:null,ws=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&&sc.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:ac(u)})();r.demuxer.decryptionKeyCache.set(s,c),a=await c}return n.scheme==="cenc"||n.scheme==="cens"?Cl(a,n,e,t):Pl(a,n,e,t)},Cl=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},Pl=(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};class an{constructor(e){this.value=e}}class on{constructor(e){this.value=e}}class ao{constructor(e){this.value=e}}class ft{constructor(e){this.value=e}}var x;(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"})(x||(x={}));const Il=[x.EBML,x.Segment],Ir=[x.SeekHead,x.Info,x.Cluster,x.Tracks,x.Cues,x.Attachments,x.Chapters,x.Tags],Hr=[...Il,...Ir],bs=r=>r<256?1:r<65536?2:r<1<<24?3:r<2**32?4:r<2**40?5:6,Ts=r=>r<1n<<8n?1:r<1n<<16n?2:r<1n<<24n?3:r<1n<<32n?4:r<1n<<40n?5:r<1n<<48n?6:r<1n<<56n?7:8,Ss=r=>r>=-64&&r<64?1:r>=-8192&&r<8192?2:r>=-1048576&&r<1<<20?3:r>=-134217728&&r<1<<27?4:r>=-17179869184&&r<2**34?5:6,El=r=>{if(r<127)return 1;if(r<16383)return 2;if(r<(1<<21)-1)return 3;if(r<(1<<28)-1)return 4;if(r<2**35-1)return 5;if(r<2**42-1)return 6;throw new Error("EBML varint size not supported "+r)};class _l{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=bs(e)){let i=0;switch(t){case 6:this.helperView.setUint8(i++,e/2**40|0);case 5:this.helperView.setUint8(i++,e/2**32|0);case 4:this.helperView.setUint8(i++,e>>24);case 3:this.helperView.setUint8(i++,e>>16);case 2:this.helperView.setUint8(i++,e>>8);case 1:this.helperView.setUint8(i++,e);break;default:throw new Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,i))}writeUnsignedBigInt(e,t=Ts(e)){let i=0;for(let n=t-1;n>=0;n--)this.helperView.setUint8(i++,Number(e>>BigInt(n*8)&0xffn));this.writer.write(this.helper.subarray(0,i))}writeSignedInt(e,t=Ss(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=El(e)){let i=0;switch(t){case 1:this.helperView.setUint8(i++,128|e);break;case 2:this.helperView.setUint8(i++,64|e>>8),this.helperView.setUint8(i++,e);break;case 3:this.helperView.setUint8(i++,32|e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 4:this.helperView.setUint8(i++,16|e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 5:this.helperView.setUint8(i++,8|e/2**32&7),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 6:this.helperView.setUint8(i++,4|e/2**40&3),this.helperView.setUint8(i++,e/2**32|0),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;default:throw new Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,i))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split("").map(t=>t.charCodeAt(0))))}writeEBML(e){if(e!==null)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(const t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){const t=this.writer.getPos(),i=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+i);const n=this.writer.getPos();if(this.dataOffsets.set(e,n),this.writeEBML(e.data),e.size!==-1){const s=this.writer.getPos()-n,a=this.writer.getPos();this.writer.seek(t),this.writeVarInt(s,i),this.writer.seek(a)}}else if(typeof e.data=="number"){const t=e.size??bs(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data=="bigint"){const t=e.size??Ts(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}
1else if(typeof e.data=="string")this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof an)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof on)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof ao){const t=e.size??Ss(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof ft){const t=be.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else Ee(e.data)}}const cn=8,Ae=2,it=2*cn,oo=r=>{if(r.remainingLength<1)return null;const e=z(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=z(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+=z(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+=z(r);return t},vl=(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(z(r));return t},Ln=r=>{const e=oo(r);return e===null||r.remainingLength<e?null:j(r,e)},co=r=>{if(r.remainingLength<1)return null;if(z(r)===255)return;r.skip(-1);const t=kr(r);if(t===null)return null;if(t!==72057594037927940)return t},Ze=r=>{g(r.remainingLength>=Ae);const e=Ln(r);if(e===null)return null;const t=co(r);return t===null?null:{id:e,size:t}},Kt=(r,e)=>{const t=N(r,e);let i=0;for(;i<e&&t[i]!==0;)i+=1;return String.fromCharCode(...t.subarray(0,i))},or=(r,e)=>{const t=N(r,e);let i=0;for(;i<e&&t[i]!==0;)i+=1;return Se.decode(t.subarray(0,i))},Fi=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?bd(r):Lo(r)},ln=async(r,e,t,i)=>{const n=new Set(t);let s=e;for(;i===null||s<i;){let a=r.requestSliceRange(s,Ae,it);if(A(a)&&(a=await a),!a)break;const o=Ze(a);if(!o)break;if(n.has(o.id))return{pos:s,found:!0};ht(o.size),s=a.filePos+o.size}return{pos:i!==null&&i>s?i:s,found:!1}},lo=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<cn)break;for(let c=0;c<o.length-cn;c++){o.filePos=a;const l=Ln(o);if(l!==null&&s.has(l))return a;a++}}return null},ye={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","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function ht(r){if(r===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}const uo=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isWebM?"webm":"x-matroska");if(r.codecStrings.length>0){const i=[...new Set(r.codecStrings.filter(Boolean))];t+=`; codecs="${i.join(", ")}"`}return t};var Ye;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(Ye||(Ye={}));var Yr;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(Yr||(Yr={}));var br;
1(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})(br||(br={}));const Ri=[{id:x.SeekHead,flag:"seekHeadSeen"},{id:x.Info,flag:"infoSeen"},{id:x.Tracks,flag:"tracksSeen"},{id:x.Cues,flag:"cuesSeen"}],fo=10*2**20;class Al extends ut{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 uo({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,Ae,it);if(A(t)&&(t=await t),!t)break;const i=Ze(t);if(!i)break;const n=i.id;let s=i.size;const a=t.filePos;if(n===x.EBML){ht(s);let o=this.reader.requestSlice(a,s);if(A(o)&&(o=await o),!o)break;this.readContiguousElements(o)}else if(n===x.Segment){if(await this.readSegment(a,s),s===void 0||this.reader.fileSize===null)break}else if(n===x.Cluster){if(this.reader.fileSize===null)break;s===void 0&&(s=(await ln(this.reader,a,Hr,this.reader.fileSize)).pos-a);const o=ee(this.segments);o&&(o.elementEndPos=a+s)}ht(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,Ae,it);if(A(o)&&(o=await o),!o)break;const c=i,l=Ze(o);if(!l||!Ir.includes(l.id)&&l.id!==x.Void){const p=await lo(this.reader,c,Ir,Math.min(this.currentSegment.elementEndPos??1/0,c+fo));if(p){i=p;continue}else break}const{id:u,size:d}=l,f=o.filePos,h=Ri.findIndex(p=>p.id===u);if(h!==-1){const p=Ri[h].flag;this.currentSegment[p]=!0,ht(d);let m=this.reader.requestSlice(f,d);A(m)&&(m=await m),m&&this.readContiguousElements(m)}else if(u===x.Tags||u===x.Attachments){u===x.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,ht(d);let p=this.reader.requestSlice(f,d);A(p)&&(p=await p),p&&this.readContiguousElements(p)}else if(u===x.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=Ri.find(p=>p.id===o.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+o.segmentPosition,Ae,it);if(A(l)&&(l=await l),!l)continue;const u=Ze(l);if(!u)continue;const{id:d,size:f}=u;if(d!==c.id)continue;ht(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,Ae,it);A(i)&&(i=await i),g(i);const n=e,s=Ze(i);g(s);const a=s.id;g(a===x.Cluster);let o=s.size;const c=i.filePos;o===void 0&&(o=(await ln(this.reader,c,Hr,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,Hr);u.elementEndPos=d}for(const[,d]of u.trackData){const f=d.track;g(d.blocks.length>0);let h=!1;for(let y=0;y<d.blocks.length;y++){const w=d.blocks[y];
1w.timestamp+=u.timestamp,h||=w.lacing!==Ye.None}d.presentationTimestamps=d.blocks.map((y,w)=>({timestamp:y.timestamp,blockIndex:w})).sort((y,w)=>y.timestamp-w.timestamp);for(let y=0;y<d.presentationTimestamps.length;y++){const w=d.presentationTimestamps[y],b=d.blocks[w.blockIndex];if(d.firstKeyFrameTimestamp===null&&b.isKeyFrame&&(d.firstKeyFrameTimestamp=b.timestamp),y<d.presentationTimestamps.length-1){const S=d.presentationTimestamps[y+1];b.duration=S.timestamp-b.timestamp}else b.duration===0&&f.defaultDuration!=null&&b.lacing===Ye.None&&(b.duration=f.defaultDuration)}h&&(this.expandLacedBlocks(d.blocks,f),d.presentationTimestamps=d.blocks.map((y,w)=>({timestamp:y.timestamp,blockIndex:w})).sort((y,w)=>y.timestamp-w.timestamp));const p=d.blocks[d.presentationTimestamps[0].blockIndex],m=d.blocks[ee(d.presentationTimestamps).blockIndex];d.startTimestamp=p.timestamp,d.endTimestamp=m.timestamp+m.duration;const k=G(f.clusterPositionCache,d.startTimestamp,y=>y.startTimestamp);(k===-1||f.clusterPositionCache[k].elementStartPos!==n)&&f.clusterPositionCache.splice(k+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}expandLacedBlocks(e,t){for(let i=0;i<e.length;i++){const n=e[i];if(n.lacing===Ye.None)continue;n.decoded||(n.data=this.decodeBlockData(t,n.data),n.decoded=!0);const s=Te.tempFromBytes(n.data),a=[],o=z(s)+1;switch(n.lacing){case Ye.Xiph:{let l=0;for(let u=0;u<o-1;u++){let d=0;for(;s.bufferPos<s.length;){const f=z(s);if(d+=f,f<255){a.push(d),l+=d;break}}}a.push(s.length-(s.bufferPos+l))}break;case Ye.FixedSize:{const l=s.length-1,u=Math.floor(l/o);for(let d=0;d<o;d++)a.push(u)}break;case Ye.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,y=(1<<(s.bufferPos-h)*7-1)-1,w=m-y;u+=w,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=N(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:Ye.None,decoded:!0,postProcessed:!1,mainAdditional:n.mainAdditional})}i+=o,i--}}async loadSegmentMetadata(e){for(const t of e.seekEntries){if(!(t.id===x.Tags&&!e.tagsSeen)){if(!(t.id===x.Attachments&&!e.attachmentsSeen))continue}let i=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,Ae,it);if(A(i)&&(i=await i),!i)continue;const n=Ze(i);if(!n||n.id!==t.id)continue;const{size:s}=n;ht(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===x.Tags?e.tagsSeen=!0:t.id===x.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=Ae;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){const i=Ze(e);if(!i||t&&t.includes(i.id))return!1;const{id:n,size:s}=i,a=e.filePos;switch(ht(s),n){case x.DocType:this.isWebM=Kt(e,s)==="webm";break;case x.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 x.SeekID:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.id=j(e,s)}break;case x.SeekPosition:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=j(e,s)}break;case x.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=j(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case x.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Fi(e,s)}break;case x.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...lt,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!==Yr.Block||o.data.algorithm!==br.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===ye.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPr
1ivate;else if(this.currentTrack.codecId===ye.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(c===ye.vp8)this.currentTrack.info.codec="vp8";else if(c===ye.vp9)this.currentTrack.info.codec="vp9";else if(c===ye.av1)this.currentTrack.info.codec="av1";else if(c===ye.prores){const u=this.currentTrack.codecPrivate?Se.decode(this.currentTrack.codecPrivate):"";Rt.includes(u)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=u)}const l=this.currentTrack;this.currentTrack.trackBacking=new Bl(l),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){c===ye.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===ye.mp3?this.currentTrack.info.codec="mp3":c===ye.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Rr):c===ye.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ye.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ye.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ye.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ye.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 Fl(l),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case x.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=j(e,s)}break;case x.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:{...Ta},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 x.FlagEnabled:{if(!this.currentTrack)break;j(e,s)||(this.currentTrack=null)}break;case x.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!j(e,s)}break;case x.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!j(e,s)}break;case x.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!j(e,s)}break;case x.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!j(e,s)}break;case x.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!j(e,s)}break;case x.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!j(e,s)}break;case x.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=Kt(e,s)}break;
1case x.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=N(e,s)}break;case x.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=j(e,s)}break;case x.Name:{if(!this.currentTrack)break;this.currentTrack.name=or(e,s)}break;case x.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Kt(e,s),Sn(this.currentTrack.languageCode)||(this.currentTrack.languageCode=he)}break;case x.LanguageBCP47:{if(!this.currentTrack)break;const c=Kt(e,s).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=he,this.currentTrack.hasLanguageBcp47=!0}break;case x.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case x.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=j(e,s)}break;case x.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=j(e,s)}break;case x.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=j(e,s)}break;case x.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=j(e,s)}break;case x.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=j(e,s)}break;case x.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=j(e,s)===1}break;case x.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case x.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video")break;const o=j(e,s),c=tt[o];this.currentTrack.info.colorSpace.matrix=c}break;case x.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 x.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video")break;const o=j(e,s),c=et[o];this.currentTrack.info.colorSpace.transfer=c}break;case x.Primaries:{if(this.currentTrack?.info?.type!=="video")break;const o=j(e,s),c=Je[o];this.currentTrack.info.colorSpace.primaries=c}break;case x.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case x.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;const c=-Fi(e,s);try{this.currentTrack.info.rotation=ei(c)}catch{}}break;case x.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(a,s))}break;case x.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=Fi(e,s)}break;case x.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=j(e,s)}break;case x.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=j(e,s)}break;case x.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,s)),this.currentCueTime=null}break;case x.CueTime:this.currentCueTime=j(e,s);break;case x.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 x.CueTrack:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=j(e,s)}break;case x.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 x.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=j(e,s)}break;case x.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=pn(e),u=z(e),d=u>>1&3;let f=!!(u&128);c.track.info?.type==="audio"&&c.track.info.codec&&(f=!0);const h=N(e,s-(e.filePos-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 x.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,s)),this.currentBlock=null}break;case x.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=pn(e),d=z(e)>>1&3,f=N(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 x.BlockAdditions:this.readContiguousElements(e.slice(a,s));break;case x.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 x.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=N(e,s)}break;case x.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=j(e,s)}break;case x.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=j(e,s)}break;case x.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case x.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,s));break;case x.Targets:this.readContiguousElements(e.slice(a,s));break;case x.TargetTypeValue:j(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case x.TagTrackUID:case x.TagEditionUID:case x.TagChapterUID:case x.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case x.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,s))}break;case x.TagName:this.currentSimpleTagName=or(e,s);break;case x.TagString:{if(!this.currentSimpleTagName)break;const o=or(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case x.TagBinary:{if(!this.currentSimpleTagName)break;const o=N(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case x.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 In(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 x.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=vl(e,s)}break;case x.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=or(e,s)}break;
1case x.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Kt(e,s)}break;case x.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=N(e,s)}break;case x.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=or(e,s)}break;case x.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,s)),this.currentTrack.decodingInstructions.sort((o,c)=>c.order-o.order)}break;case x.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Yr.Block,data:null},this.readContiguousElements(e.slice(a,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case x.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=j(e,s)}break;case x.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=j(e,s)}break;case x.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:br.Zlib,settings:null},this.readContiguousElements(e.slice(a,s))}break;case x.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=j(e,s)}break;case x.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=N(e,s)}break;case x.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 br.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 ho{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 Cr(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=G(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=bn(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);$(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 Y(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:y,correctBlockFound:w}=t(e);if(w)return this.fetchPacketInCluster(e,y,s);y!==-1&&(l=e,u=y)}const d=G(this.internalTrack.cuePoints,i,y=>y.time),f=d!==-1?this.internalTrack.cuePoints[d]:null,h=G(this.internalTrack.clusterPositionCache,i,y=>y.startTimestamp),p=h!==-1?this.internalTrack.clusterPositionCache[h]:null,m=Math.max(f?.clusterPosition??0,p?.elementStartPos??0)||null;let k;for(e?m===null||e.elementStartPos>=m?(k=e.elementEndPos,c=e):k=m:k=m??o.clusterSeekStartPos;o.elementEndPos===null||k<=o.elementEndPos-Ae;){if(c){const I=c.trackData.get(this.internalTrack.id);if(I&&I.startTimestamp>n)break}let y=a.reader.requestSliceRange(k,Ae,it);if(A(y)&&(y=await y),!y)break;const w=k,b=Ze(y);if(!b||!Ir.includes(b.id)&&b.id!==x.Void){const I=await lo(a.reader,w,Ir,Math.min(o.elementEndPos??1/0,w+fo));if(I){k=I;continue}else break}const S=b.id;let T=b.size;const P=y.filePos;if(S===x.Cluster){c=await a.readCluster(w,o),T=c.elementEndPos-P;const{blockIndex:I,correctBlockFound:C}=t(c);if(C)return this.fetchPacketInCluster(c,I,s);I!==-1&&(l=c,u=I)}T===void 0&&(g(S!==x.Cluster),T=(await ln(a.reader,P,Hr,o.elementEndPos)).pos-P);const E=P+T;if(o.elementEndPos===null){let I=a.reader.requestSliceRange(E,Ae,it);if(A(I)&&(I=await I),!I)break;if(Ln(I)===x.Segment){o.elementEndPos=E;break}}k=E}if(f&&(!l||l.elementStartPos<f.clusterPosition)){const y=this.internalTrack.cuePoints[d-1];g(!y||y.time<f.time);const w=y?.time??-1/0;return this.performClusterLookup(null,t,w,n,s)}return l?this.fetchPacketInCluster(l,u,s):null}}class Bl extends ho{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}
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?ci(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?ui(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Ra(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Bn(e.data):null,proresCodecInfo:this.internalTrack.info.codec==="prores"&&e?Oa(e.data):null,proresFormat:this.internalTrack.info.proresFormat};
1if(!wn(this.internalTrack.info.colorSpace)){const s=ja(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:Dn(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 Fl extends ho{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:zn({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 un=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,Mt,a);if(A(o)&&(o=await o),!o||o.length<Mt)break;for(;o.remainingLength>=Mt;){const c=o.filePos,l=R(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&&Pr(d.header.channel)===Pr(i.channel)))return{header:d.header,startPos:s};o.filePos=c+d.bytesAdvanced,s=o.filePos}}return null};class Rl extends ut{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 nr,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 Ml(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,Be);if(A(o)&&(o=await o),!o){this.lastSampleLoaded=!0;return}const c=ct(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}const e=await un(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=R(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=N(l,12),d=$(u),f=d.getUint32(0,!1);this.xingData={frameCount:f&Qr.FrameCount?d.getUint32(4,!1):null,fileSize:f&Qr.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,Be);if(A(n)&&(n=await n),!n)break;const s=ct(n);if(!s)break;i=!0;let a=this.reader.requestSlice(n.filePos,s.size);if(A(a)&&(a=await a),!a)break;ki(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),ie(n,3)==="TAG"&&Td(n,this.metadataTags)}return this.metadataTags}finally{e()}}}class Ml{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=gl(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 he}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return g(this.demuxer.firstFrameHeader),Pr(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...lt}}async getDecoderConfig(){return g(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:Pr(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=N(s,i.dataSize)}return new Y(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=Ar(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=G(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 mo=1399285583,Ol=79764919,po=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^Ol:e<<1;po[r]=e>>>0&4294967295}const Dl=r=>{const e=$(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^po[i>>>24^s])>>>0}return e.setUint32(22,t,!0),i},zl=(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<<fc(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=Dc(r).durationInSamples);return{durationInSamples:i,vorbisBlockSize:n}},Nl=r=>{let e="audio/ogg";if(r.codecStrings){const t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};const At=27,er=282,Ul=er+65025,Tr=r=>{const e=r.filePos;if(Xt(r)!==mo)return null;r.skip(1);const i=z(r),n=wd(r),s=Xt(r),a=Xt(r),o=Xt(r),c=z(r),l=new Uint8Array(c);for(let h=0;h<c;h++)l[h]=z(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}},Vl=(r,e)=>{for(;r.filePos<e-3;){const t=Xt(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===mo)return!0;r.skip(1)}}return!1};class Wl extends ut{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,At,er);if(A(t)&&(t=await t),!t)break;const i=Tr(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 Ll(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=$(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:zc(s.data).modeBlockflags},tn(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=Fn(e.data);t.numberOfChannels=s.outputChannelCount,t.sampleRate=Rr,t.codecInfo.opusInfo={preSkip:s.preSkip},tn(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=N(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,At,er);if(A(p)&&(p=await p),!p)return null;const m=Tr(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,At,er);if(A(n)&&(n=await n),!n)return null;const s=Tr(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 Nl({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class Ll{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new nr,this.internalSampleRate=e.codecInfo.codec==="opus"?Rr: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 he}getDisposition(){return{...lt,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}=zl(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new Y(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=Cr(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 w=s.headerStartPos,b=Math.floor((w+a)/2);let S=b;for(;;){const T=Math.min(S+Ul,a-At);let P=this.demuxer.reader.requestSlice(S,T-S);if(A(P)&&(P=await P),g(P),!Vl(P,T)){a=b+At;continue e}let I=this.demuxer.reader.requestSliceRange(P.filePos,At,er);A(I)&&(I=await I),g(I);const C=Tr(I);g(C);let _=!1;if(C.serialNumber===this.bitstream.serialNumber)_=!0;else{let v=this.demuxer.reader.requestSlice(C.headerStartPos,C.totalSize);A(v)&&(v=await v),g(v);const O=N(v,C.totalSize);_=Dl(O)===C.checksum}if(!_){S=C.headerStartPos+4;continue}if(_&&C.serialNumber!==this.bitstream.serialNumber){S=C.headerStartPos+C.totalSize;continue}if(C.granulePosition===-1){S=C.headerStartPos+C.totalSize;continue}this.granulePositionToTimestampInSamples(C.granulePosition)>i?a=C.headerStartPos:(s=C,o.push(C));continue e}}let c=n.startPage;for(const w of o){if(w.granulePosition===s.granulePosition)break;(!c||w.headerStartPos>c.headerStartPos)&&(c=w)}let l=c;const u=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===s.granulePosition);){const w=l.headerStartPos+l.totalSize;let b=this.demuxer.reader.requestSliceRange(w,At,er);A(b)&&(b=await b),g(b);const S=Tr(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 w={data:ve,endPage:p,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(w)){const S=Cs(u,l,d);g(S);const T=xs(u,S.page,S.segmentIndex);T&&(l=T.page,d=T.segmentIndex)}else for(;;){const S=Cs(u,l,d);if(!S)break;const T=xs(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 k=null,y=null;for(;l!==null;){g(d!==null);const w=await this.demuxer.readPacket(l,d);if(!w)break;if(!(l.headerStartPos===n.startPage.headerStartPos&&d<n.startSegmentIndex)){let T=this.createEncodedPacketFromOggPacket(w,{timestampInSamples:f,vorbisLastBlocksize:y?.vorbisBlockSize??null},t);g(T);let P=this.encodedPacketToMetadata.get(T);if(g(P),!h&&w.endPage.headerStartPos===p.headerStartPos&&w.endSegmentIndex===m?(f=this.granulePositionToTimestampInSamples(l.granulePosition),h=!0,T=this.createEncodedPacketFromOggPacket(w,{timestampInSamples:f-P.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},t),g(T),P=this.encodedPacketToMetadata.get(T),g(P)):f+=P.durationInSamples,k=T,y=P,h&&(Math.max(f,0)>i||Math.max(P.timestampInSamples,0)===i))break}const S=await this.demuxer.findNextPacketStart(w);if(!S)break;l=S.startPage,d=S.startSegmentIndex}return k}async getPacketSequential(e,t){const i=await this.sequentialScanMutex.acquire();try{const n=Cr(e*this.internalSampleRate);e=n/this.internalSampleRate;const s=G(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(ee(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 xs=(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=Sa(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}},Cs=(r,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};const i=Sa(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 Hl extends ut{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=ie(e,4),i=t!=="RIFX",n=t==="RF64",s=wt(e,i);let a=n?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(ie(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=ie(f,4),p=wt(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 k=this.reader.requestSlice(m,p);if(A(k)&&(k=await k),!k)break;const y=oa(k,i);l=oa(k,i),a=Math.min(y+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 ql(this))})()}async parseFmtChunk(e,t,i){let n=this.reader.requestSlice(e,t);if(A(n)&&(n=await n),!n)return;let s=mr(n,i);const a=mr(n,i),o=wt(n,i);n.skip(4);const c=mr(n,i);let l;if(t===14?l=8:l=mr(n,i),t>=18&&s!==357){const u=mr(n,i),d=t-18;if(Math.min(d,u)>=22&&s===we.EXTENSIBLE){n.skip(6);const h=N(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=ie(n,4);if(s!=="INFO"&&s!=="INF0")return;let a=n.filePos;for(;a<=e+t-8;){n.filePos=a;const o=ie(n,4),c=wt(n,i),l=N(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=ct(i);if(n){const s=t-Be;if(n.size=Math.min(n.size,s),n.size>0){const a=i.slice(e+Be,n.size);ki(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 Vt=2048;class ql{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 he}getDisposition(){return{...lt}}async getPacketAtIndex(e,t){g(e>=0),g(this.demuxer.audioInfo);const i=e*Vt*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const n=Math.min(Vt*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=N(c,n)}const a=e*Vt/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 Y(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/Vt,(this.demuxer.dataSize-1)/(Vt*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/Vt);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Er=7,bt=9,ot=r=>{const e=r.filePos,t=N(r,9),i=new K(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 Zr=1024;class jl extends ut{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new nr,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 $l(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,Be);if(A(a)&&(a=await a),!a){this.lastSampleLoaded=!0;return}const o=ct(a);if(!o)break;this.lastLoadedPos=a.filePos+o.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,Er,bt);if(A(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}const t=ot(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=St[t.samplingFrequencyIndex];g(i!==void 0);const n=Zr/i,s={timestamp:this.nextTimestampInSamples/i,duration:n,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=Zr,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,Be);if(A(i)&&(i=await i),!i)break;const n=ct(i);if(!n)break;let s=this.reader.requestSlice(i.filePos,n.size);if(A(s)&&(s=await s),!s)break;ki(s,n,this.metadataTags),t=i.filePos+n.size}return this.metadataTags}finally{e()}}}class $l{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}
1getTimeResolution(){return this.getSampleRate()/Zr}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 he}getCodec(){return"aac"}getInternalCodecId(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){g(this.demuxer.firstFrameHeader);const e=ar[this.demuxer.firstFrameHeader.channelConfiguration];return g(e!==void 0),e}getSampleRate(){g(this.demuxer.firstFrameHeader);const e=St[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return g(e!==void 0),e}getDisposition(){return{...lt}}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=N(s,i.dataSize)}return new Y(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=Ar(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=G(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 Kl=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,Gl=(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}},Xl=r=>{let e=0;const t=new K(N(r,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);const i=[],n=e-1,s=new K(N(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)},Ql=(r,e)=>{if(e==="uncommon-u16")return ne(r)+1;if(e==="uncommon-u8")return z(r)+1;if(typeof e=="number")return e;Ee(e),g(!1)},Yl=(r,e)=>e==="uncommon-u16"?ne(r):e==="uncommon-u16-10"?ne(r)*10:e==="uncommon-u8"?z(r):typeof e=="number"?e:null,Zl=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 Jl extends ut{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 nr,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,Be);if(A(t)&&(t=await t),!t){this.lastSampleLoaded=!0;return}const i=ct(t);if(!i)break;let n=this.reader.requestSlice(t.filePos,i.size);A(n)&&(n=await n),g(n),ki(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=z(t),n=Qe(t),s=(i&128)!==0;switch(i&127){case Jt.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=N(o,34),l=new K(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 k=l.readBits(36);l.skipBits(128);const y=new Uint8Array(42);y.set(new Uint8Array([102,76,97,67]),0),y.set(new Uint8Array([128,0,0,34]),4),y.set(c,8),this.audioInfo={numberOfChannels:m,sampleRate:p,totalSamples:k,minimumBlockSize:u,maximumBlockSize:d,minimumFrameSize:f,maximumFrameSize:h,description:y},this.trackBacking=new eu(this);break}case Jt.VORBIS_COMMENT:{let o=this.reader.requestSlice(e,n);A(o)&&(o=await o),g(o),tn(N(o,n),this.metadataTags);break}case Jt.PICTURE:{let o=this.reader.requestSlice(e,n);A(o)&&(o=await o),g(o);const c=R(o),l=R(o),u=Se.decode(N(o,l)),d=R(o),f=Se.decode(N(o,d));o.skip(16);const h=R(o),p=N(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(z(u)===255){const h=u.filePos,p=z(u),m=this.blockingBit===1?249:248;if(p!==m){u.filePos=h;continue}u.skip(-2);const k=u.filePos-e,y=this.readFlacFrameHeader({slice:u,isFirstPacket:!1});if(!y){u.filePos=h;continue}if(this.blockingBit===0){if(y.num-d.num!==1){u.filePos=h;continue}}else if(y.num-d.num!==d.blockSize){u.filePos=h;continue}return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:k,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const i=e.filePos,n=N(e,4),s=new K(n);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){g(t);const k=s.readBits(1);this.blockingBit=k}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=Kl(s.readBits(4));if(!o)return null;g(this.audioInfo);const c=Gl(s.readBits(4),this.audioInfo.sampleRate);if(!c||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;const u=Xl(e),d=Ql(e,o),f=Yl(e,c);if(f===null||f!==this.audioInfo.sampleRate)return null;const h=e.filePos-i,p=z(e);e.skip(-h),e.skip(-1);const m=Zl(N(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 eu{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 he}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{...lt}}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=G(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=N(o,i.byteSize)}g(this.demuxer.audioInfo);const s=i.blockOffset/this.demuxer.audioInfo.sampleRate,a=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Y(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 qe=9e4,Pe=188,tu=r=>{let e="video/MP2T";const t=[...new Set(r.filter(Boolean))];return t.length>0&&(e+=`; codecs="${t.join(", ")}"`),e};const go="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.",Ps=5,ru=1212435798,iu=1212436562,nu=1146376960,su=new Set([133,134,162]),Is=new Set;class au extends ut{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=Pe+16+1;let t=this.reader.requestSlice(0,e);A(t)&&(t=await t),g(t);const i=N(t,e);if(i[0]===71&&i[Pe]===71)this.packetOffset=0,this.packetStride=Pe;else if(i[0]===71&&i[Pe+16]===71)this.packetOffset=0,this.packetStride=Pe+16;else if(i[4]===71&&i[4+Pe+4]===71)this.packetOffset=4,this.packetStride=Pe+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 k=new K(u.payload),y=k.readAlignedByte();k.skipBits(8*y),h=k.readBits(8)===2}if(u.pid===0&&!o){const m=new K(u.payload),k=m.readAlignedByte();m.skipBits(8*k),m.skipBits(14);const y=m.readBits(10);for(m.skipBits(40);8*(y+d)-m.pos>f;){const w=m.readBits(16);m.skipBits(3);const b=m.readBits(13);if(w!==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 K(u.payload),k=m.readAlignedByte();m.skipBits(8*k),m.skipBits(12);const y=m.readBits(12);m.skipBits(43),m.readBits(13),m.skipBits(6);const w=m.readBits(10),b=m.pos+8*w;let S=!1;for(;m.pos<b;){const T=m.readBits(8),P=m.readBits(8),E=m.pos+8*P;if(T===Ps&&P>=4){const I=m.readBits(32);S||=I===ru||I===iu}m.pos=E}for(m.pos=b;8*(y+d)-m.pos>f;){const T=m.readBits(8);m.skipBits(3);const P=m.readBits(13);m.skipBits(6);const E=m.readBits(10),I=m.pos+8*E;let C=!1,_=!1,B=!1;for(;m.pos<I;){const D=m.readBits(8),V=m.readBits(8),L=m.pos+8*V;if(D===106)C=!0;else if(D===122||D===204)_=!0;else if(D===123)B=!0;else if(D===Ps&&V>=4){const te=m.readBits(32);B||=(te&4294967040)===nu}m.pos=L}let v=null;const O=S&&su.has(T)?130:T;switch(O){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 D;O===3||O===4?D="mp3":O===15?D="aac":O===129?D="ac3":O===135?D="eac3":D="dts",v={type:"audio",codec:D,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:_?v={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:C?v={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:B&&(v={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:Is.has(T)||(H._warn(`Note: MPEG-TS streams with stream_type 0x${T.toString(16)} are not currently supported.`),Is.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(k=>k.pid===u.pid);e:if(m&&!m.initialized){const k=Gt(u,!0);if(!k)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 y=new yr(m,k);if(m.info.type==="video"){for(;;){const w=y;if(w.suppliedPacket=null,await y.markNextPacket(),m.info.codec==="avc"){if(!y.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(m.info.avcCodecInfo=ci(y.suppliedPacket.data),!m.info.avcCodecInfo)continue;const b=m.info.avcCodecInfo.sequenceParameterSets[0];g(b);const S=li(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:Je[S.colourPrimaries],transfer:et[S.transferCharacteristics],matrix:tt[S.matrixCoefficients],fullRange:!!S.fullRangeFlag},m.info.reorderSize=S.maxDecFrameBuffering;break}else if(m.info.codec==="hevc"){if(!y.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(m.info.hevcCodecInfo=ui(y.suppliedPacket.data),!m.info.hevcCodecInfo)continue;const S=m.info.hevcCodecInfo.arrays.find(P=>P.nalUnitType===se.SPS_NUT).nalUnits[0];g(S);const T=An(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:Je[T.colourPrimaries],transfer:et[T.transferCharacteristics],matrix:tt[T.matrixCoefficients],fullRange:!!T.fullRangeFlag},m.info.reorderSize=T.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}m.info.decoderConfig={codec:Dn({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 y.markNextPacket(),!y.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${m.pid}`);if(m.info.codec==="aac"){const w=Te.tempFromBytes(y.suppliedPacket.data),b=ot(w);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=ar[b.channelConfiguration],m.info.sampleRate=St[b.samplingFrequencyIndex]}else if(m.info.codec==="mp3"){const w=R(Te.tempFromBytes(y.suppliedPacket.data)),b=Vn(w,y.suppliedPacket.data.byteLength);if(!b.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");m.info.numberOfChannels=Pr(b.header.channel),m.info.sampleRate=b.header.sampleRate}else if(m.info.codec==="ac3"){const w=Da(y.suppliedPacket.data);if(!w)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(w.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=Rn[w.acmod]+w.lfeon,m.info.sampleRate=si[w.fscod]}else if(m.info.codec==="eac3"){const w=Na(y.suppliedPacket.data);if(!w)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const b=Ua(w);if(b===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=Va(w),m.info.sampleRate=b}else if(m.info.codec==="dts"){const w=On(y.suppliedPacket.data);if(!w)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");m.info.numberOfChannels=w.numberOfChannels,m.info.sampleRate=w.sampleRate,w.core&&(m.info.dtsFormat=w.hasExtensions?"dtsh":"dtsc")}else throw new Error("Unhandled.");m.info.decoderConfig={codec:zn({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 ou(l)):this.trackBackingEntries.push(new cu(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 tu(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(Ar(this.sectionEndPositions,n,y=>y)!==-1){l=!1;break}}if(l){const f=G(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(z(t)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const n=ne(t),s=n>>14&1,a=n&8191,c=z(t)>>4&3;return{payloadUnitStartIndicator:s,pid:a,adaptationFieldControl:c}}async readPacket(e){let t=this.reader.requestSlice(e,Pe);if(A(t)&&(t=await t),!t)return null;const i=N(t,Pe);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 It=(r,e)=>{if(r.payload.byteLength<3)return null;const t=new K(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(go);return{sectionStartPos:r.startPos,sectionEndPos:r.endPos,pts:a,randomAccessIndicator:r.randomAccessIndicator}},Gt=(r,e)=>{g(r.endPos!==null);const t=It(r,e);if(!t)return null;const i=new K(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 hi{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 hi),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 he}getDisposition(){return{...lt,primary:!1}}getTimeResolution(){return qe}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 Y(i.metadataOnly?ve:e.data,n,e.pts/qe,Math.max(t/qe,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;g(t);const i=Gt(t,!0);g(i);const n=new yr(this.elementaryStream,i),s=new Mi(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=Gt(a,!0);g(o);const c=new yr(this.elementaryStream,o);i=new Mi(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=Cr(e*qe),s=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=s,c=this.elementaryStream.pid,l=async(S,T,P)=>{let E=S;for(;E<T;){const I=await s.readPacketHeader(E);if(!I)return null;if(I.pid===c&&I.payloadUnitStartIndicator===1){const C=await s.readSection(E,P);if(!C)return null;const _=It(C,!1);if(_&&_.pts!==null)return{pesPacketHeader:_,section:C}}E+=s.packetStride}return null},u=this.elementaryStream.firstSection;g(u);const d=It(u,!0);if(g(d),n<d.pts)return null;let f;const h=this.elementaryStream.referencePesPackets,p=G(h,n,S=>S.pts),m=p!==-1?h[p]:null;if(m&&n-m.pts<qe/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,E=T-1;for(S=P;P<=E;){const I=Math.floor((P+E)/2),C=Ti(I*o,s.packetStride)+d.sectionStartPos,_=C+o,B=await l(C,_,!1);if(!B){E=I-1;continue}B.pesPacketHeader.pts<=n?(S=I,P=I+1):E=I-1}}}f=Ti(S*o,s.packetStride)+d.sectionStartPos}let y=(await l(f,a.fileSize??1/0,!1))?.pesPacketHeader??null;y||(y=d);const w=this.getReorderSize(),b=async(S,T)=>{const P=await s.readSection(S,!0);g(P);const E=Gt(P,!0);g(E);const I=new yr(this.elementaryStream,E),C=new Mi(this,I);for(;!((ee(C.presentationOrderPackets)?.pts??-1/0)>=n||!await C.readNextPacket()););const _=bn(C.presentationOrderPackets,T);if(_===-1)return null;const B=C.presentationOrderPackets[_],v=_===0?0:B.pts-C.presentationOrderPackets[_-1].pts;for(;C.decodeOrderPackets[0]!==B;)C.decodeOrderPackets.shift();C.lastDuration=v;const O=await C.readNext();g(O);const D=this.createEncodedPacket(O.packet,O.duration,i);return this.packetBuffers.set(D,C),this.packetSectionStarts.set(D,O.packet.sectionStartPos),D};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let S=y.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 E=It(P,!1);if(E&&E.pts!==null){if(E.pts>n)break e;y=E,dn(this.elementaryStream,y);break}}}S+=s.packetStride}}e:for(let S=0;S<w+1;S++){let T=y.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 E=await s.readSection(T,!1);if(E){const I=It(E,!1);if(I&&I.pts!==null){y=I;break}}}T-=s.packetStride}}return b(y.sectionStartPos,S=>S.pts<=n)}else{let S=f,T=null;const P=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let E=null;const I=S<=d.sectionStartPos;let C,_=null;if(I)C=d,_=u;else{const O=await l(S,a.fileSize??1/0,P);C=O?.pesPacketHeader??null,_=O?.section??null}let B=!1,v=0;e:for(;C&&!(T!==null&&C.sectionStartPos>=T);){if(C.pts<=n){let D;if(this.elementaryStream.canBeTrustedWithKeyPackets)D=C.randomAccessIndicator===1;else{g(_);const V=Gt(_,!0);g(V);const L=new yr(this.elementaryStream,V);await L.markNextPacket(),D=L.suppliedPacket?.randomAccessIndicator===1}D&&(E=C)}if(C.pts>n&&(B=!0),B&&(v++,v>w))break;let O=C.sectionStartPos+s.packetStride;for(;;){const D=await s.readPacketHeader(O);if(!D)break e;if(D.pid===c&&D.payloadUnitStartIndicator===1){const V=await s.readSection(O,P);
1if(V){const L=It(V,!1);if(L&&L.pts!==null){C=L,_=V,dn(this.elementaryStream,C);break}}}O+=s.packetStride}}if(E){let O=E;if(v===0)e:for(let V=0;V<w;V++){let L=O.sectionStartPos-s.packetStride;for(;L>=s.packetOffset;){const te=await s.readPacketHeader(L);if(!te)break e;if(te.pid===c&&te.payloadUnitStartIndicator===1){const pe=await s.readSection(L,P);if(pe){const ze=It(pe,!1);if(ze&&ze.pts!==null){O=ze;break}}}L-=s.packetStride}}const D=await b(O.sectionStartPos,V=>V.pts<=n&&V.randomAccessIndicator===1);return g(D),D}if(I)return null;T=S,S=Math.max(Ti(S-d.sectionStartPos-o,s.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}}class ou extends hi{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}
1async 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 cu extends hi{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 dn=(r,e)=>{const t=r.referencePesPackets,i=G(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 yr{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=ee(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=Gt(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);if(h===-1||h>=d)break;f=h;const p=l+f;if(f+3>=d){this.seekTo(p);break}const m=u[f+1],k=u[f+2],y=u[f+3];let w=0;if(m===0&&k===0&&y===1?w=4:m===0&&k===1&&(w=3),w===0){f++;continue}const b=p;s??=b;const S=f+w,T=S+n,P=6;if(T+(t==="avc"?P:1)>d){this.seekTo(p);break}const I=u[S];let C,_,B;if(t==="avc")C=ai(I),_=C===le.NON_IDR_SLICE||C===le.SLICE_DPA||C===le.IDR,B=C===le.SEI||C===le.SPS||C===le.PPS||C===le.AUD;else{if(C=ir(I),((I&1)<<5|u[S+1]>>3)>0){f+=w;continue}_=C<=se.RASL_R||C>=se.BLA_W_LP&&C<=21,B=C>=se.VPS_NUT&&C<=37||C===se.PREFIX_SEI_NUT||C>=41&&C<=44||C>=48&&C<=55}let v=!1;if(_){let O;if(t==="avc"){const D=u.subarray(T,T+P),V=M(new K(D));O=!a||V<=o,o=V}else O=u[T]>>7===1;O&&(a?v=!0:a=!0)}else B&&a&&(v=!0);if(v){const O=b-s;return this.seekTo(s),this.supplyPacket(O,0)}f+=w}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(bt);if(A(c)&&(c=await c),c<bt)return;const l=this.readBytes(bt),u=ot(Te.tempFromBytes(l));if(u){this.seekTo(o);let d=this.ensureBuffered(u.frameLength);return A(d)&&(d=await d),this.supplyPacket(d,Math.round(Zr*qe/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(Mt);if(A(c)&&(c=await c),c<Mt)return;const l=this.readBytes(Mt),u=$(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*qe/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=Nc[3*d+u];g(f!==void 0),this.seekTo(o),c=this.ensureBuffered(f),A(c)&&(c=await c);const h=Math.round(Uc*qe/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=za[h];this.seekTo(o),c=this.ensureBuffered(d),A(c)&&(c=await c);const m=p*256,k=Math.round(m*qe/e.info.sampleRate);return this.supplyPacket(c,k)}else if(t==="dts"){if(a!==127&&a!==100)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(Wr);if(A(c)&&(c=await c),c<Wr)return;const l=this.readBytes(Wr),u=Ha(l);let d=u?null:Lr(l);
1if(!u&&!d){this.seekTo(o+1);continue}if(d&&!d.asset){this.seekTo(o);const m=Math.min(d.frameSize,Lc);let k=this.ensureBuffered(m);A(k)&&(k=await k),d=Lr(this.readBytes(k))??d}let f=u?u.frameSize:d.frameSize;if(u){let m=Math.ceil(u.frameSize/4)*4;for(;;){this.seekTo(o);const k=m+rn;let y=this.ensureBuffered(k);if(A(y)&&(y=await y),y<k)break;this.seekTo(o+m);const w=Lr(this.readBytes(rn));if(!w)break;m+=w.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*qe/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(go);n=i.pts,dn(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=di(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 Mi{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)}async 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 ko="application/vnd.apple.mpegurl",Es="#EXT-X-STREAM-INF:",_s="#EXT-X-I-FRAME-STREAM-INF:",vs="#EXT-X-MEDIA:",fn="#EXTINF:",As="#EXT-X-MAP:",Bs="#EXT-X-KEY:",Fs="#EXT-X-MEDIA-SEQUENCE:",Rs="#EXT-X-BYTERANGE:",Ms="#EXT-X-PROGRAM-DATE-TIME:",lu="#EXT-X-DISCONTINUITY",Os="#EXT-X-TARGETDURATION:",uu="#EXT-X-ENDLIST",Ds="#EXT-X-PLAYLIST-TYPE:",du="#EXT-X-I-FRAMES-ONLY",yo=r=>r.length===0||r.startsWith("#")&&!r.startsWith("#EXT");class Sr{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 fu{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=gr(e,n=>n.getType()==="video")+1;e.push(new zs(this,t,i))}else if(t.type==="audio"){const i=gr(e,n=>n.getType()==="audio")+1;e.push(new Ns(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=gr(e,a=>a.getType()==="video")+1;e.push(new zs(this,{id:e.length+1,type:"video"},s))}else if(n.type==="audio"){const s=gr(e,a=>a.getType()==="audio")+1;e.push(new Ns(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 wo{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:tr(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 zs extends wo{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 Ns extends wo{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())}}Cn();const bo=0,To=1/0;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(r=>{r()});class je extends Br{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 ke;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,bo,To),e=this._getFileSize(),g(e!==void 0)),e})()}async getSize(){if(this._disposed)throw new ke;
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 ku(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new Hn(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}}class Hn{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 Mr extends je{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 je||n instanceof Hn))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const s=n instanceof je?n.ref():n;return s.source._usedForHls||=this._usedForHls,s};return A(t)?t.then(i):i(t)}}const Us=(r,e)=>r.path===e.path;class hu extends Mr{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 je?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 Vs=typeof FinalizationRegistry<"u"?new FinalizationRegistry(r=>{r.cancel().catch(()=>{})}):null;class ih extends je{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&&(!sr(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 gu({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),Vs?.unregister(i),n.cancel().catch(()=>{}))},prefetchProfile:pu.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&&!wr()&&this._options.useStreamReader!==!1?(t=this._blob.slice(e.currentPos).stream().getReader(),Vs?.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 mu extends je{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&&(!sr(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=G(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:$(a),offset:e};this._currentIndex>s&&this._throwDueToCacheMiss();const{promise:o,resolve:c,reject:l}=oe();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:$(a.bytes),offset:a.start}),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:i,end:n,bytes:t,view:$(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 ke);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const pu={fileSystem:(r,e)=>(r=Math.floor((r-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:r,end:e})};class gu{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=G(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=G(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 E=Math.max(a,P.start),I=Math.min(o,P.end);if(g(E<=I),p<E&&m.push({start:p,end:E}),p=I,f){const C=Math.max(e,P.start),_=Math.min(t,P.end);if(C<_){const B=C-e;f.set(P.bytes.subarray(C-P.start,_-P.start),B),B===h&&(h=_-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:$(f),offset:e}),m.length===0)return g(c),c;const{promise:k,resolve:y,reject:w}=oe(),b=[];for(const T of m){const P=Math.max(e,T.start),E=Math.min(t,T.end);P===T.start&&E===T.end?b.push(T):P<E&&b.push({start:P,end:E}
1)}const S=f&&{start:e,bytes:f,holes:b,resolve:y,reject:w};e:for(const T of m){for(const I of this.workers)if(this.checkHoleAgainstWorker(I,T,S?[S]:[])){this.checkQueuedReadsAgainstWorker(I);continue e}const P=T.end<o||this.fileSize!==null,E=this.createWorker(T.start,T.end,P);if(E)S&&(E.pendingSlices=[S]),this.runWorker(E);else{let I=G(this.queuedReads,T.start,_=>_.hole.start),C=I!==-1?this.queuedReads[I]:null;for(C&&T.start<=C.hole.end?(C.hole.end=Math.max(C.hole.end,T.end),C.strictTarget&&=P,S&&C.pendingSlices.push(S)):(I++,C={hole:{start:T.start,end:T.end},strictTarget:P,pendingSlices:S?[S]:[],age:this.nextAge++},this.queuedReads.splice(I,0,C));I+1<this.queuedReads.length;){const _=this.queuedReads[I+1];if(_.hole.start>C.hole.end)break;C.hole.end=Math.max(C.hole.end,_.hole.end),C.pendingSlices.push(..._.pendingSlices),C.strictTarget&&=_.strictTarget,C.age=Math.min(C.age,_.age),this.queuedReads.splice(I+1,1)}}}return c?k.catch(T=>{if(!this.disposed)throw T}):(g(f),c=k.then(T=>T&&{bytes:T,view:$(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:$(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=G(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=$(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=$(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 ke);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 ke);this.workers.length=0,this.cache.length=0,this.queuedReads.length=0,this.disposed=!0}}class ku extends je{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:ae(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 Ws=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},Ls=(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 yu=/^0[xX][0-9a-fA-F]+$/,wu=/^data:.*;base64,/i;class Hs extends fu{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 Ia(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=Ws(b,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),P=await new qr(S.source).requestEntireFile();g(P),e=Ho(P,P.length,{ignore:yo}),S.source instanceof Mr&&(this.rootPath=S.source.rootPath)}catch(S){b.error=S,b.hasError=!0}finally{Ls(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,k=ee(this.segments)??null;const y=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}},w=b=>{c=b,k&&(g(k.sequenceNumber!==null),k.sequenceNumber<b&&(n=k.timestamp+k.duration,l=k.firstSegment,u=k.initSegment,h=k.lastProgramDateTimeSeconds,s=k.unixEpochTimestamp!==null?k.unixEpochTimestamp+k.duration:null,k=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(!k){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 C=new Uint8Array(Le),_=$(C);_.setUint32(8,Math.floor(c/2**32)),_.setUint32(12,c),T={...T,iv:C}}const E={path:gt(this.rootPath,S),offset:f?.offset??0,length:f?.length??null},I={timestamp:n,unixEpochTimestamp:s,firstSegment:l,sequenceNumber:c,location:E,duration:a,encryption:T,initSegment:u,lastProgramDateTimeSeconds:h};l??=I,n+=a,s!==null&&(s+=a),this.segments.push(I)}a=null,f===null?d=null:f=null,w(c+1)}if(S.startsWith(fn)){if(k){m=!0;continue}m||(h===null&&c>0&&p!==null&&(n=c*p),m=!0);const T=S.slice(fn.length),P=T.indexOf(","),E=P===-1?T:T.slice(0,P),I=Number(E);if(!Number.isFinite(I)||I<0)throw new Error(`Invalid #EXTINF tag duration '${E}'.`);a=I}else if(S.startsWith(As)){const T=new Sr(S.slice(As.length)),P=T.get("uri");if(!P)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const E=T.get("byterange");let I=null;if(E!==null&&(I=y(E)),I&&I.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!k){const _={path:gt(this.rootPath,P),offset:I?.offset??0,length:I?.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:_,duration:0,encryption:o,initSegment:null,lastProgramDateTimeSeconds:h}}a=null,f===null?d=null:f=null}else if(S.startsWith(Bs)){const T=new Sr(S.slice(Bs.length)),P=T.get("method");if(P==="NONE")o=null;else if(P==="AES-128"){const E=T.get("uri");if(!E)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let I=null;const C=T.get("iv");if(C){if(!yu.test(C))throw new Error(`Unsupported IV format '${C}'.`);let B=C.slice(2);B=B.padStart(Le*2,"0"),I=new Uint8Array(Le);for(let v=0;v<Le;v++){const O=-Le*2+v;I[v]=parseInt(B.slice(O,O+2),16)}}const _=T.get("keyformat")??"identity";if(_!=="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:gt(this.rootPath,E),iv:I,keyFormat:_}}else if(P==="SAMPLE-AES"||P==="SAMPLE-AES-CTR"){const E=T.get("uri");if(!E)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 C=null;if(wu.test(E)){const _=E.indexOf(","),B=Ca(E.slice(_+1));if(B.length>=8&&B[4]===112&&B[5]===115&&B[6]===115&&B[7]===104){const v=$(B).getUint32(0);C=Za(B.subarray(8,Math.min(v,B.length)))}}o={method:P,psshBox:C}}else throw new Error(`Unsupported encryption method '${P}'. If you think this method should be supported, please raise an issue.`)}else if(S.startsWith(Fs)){const T=S.slice(Fs.length),P=Number(T);
1if(!Number.isInteger(P)||P<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${T}'.`);w(P)}else if(S.startsWith(Rs)){const T=y(S.slice(Rs.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(Ms)){if(k)continue;const T=S.slice(Ms.length),P=Date.parse(T);if(!Number.isFinite(P))continue;const E=P/1e3;if(h===E)continue;if(h===null&&this.segments.length>0){const I=ee(this.segments),C=I.timestamp+I.duration,_=E-C;for(const B of this.segments)B.unixEpochTimestamp=B.timestamp+_,t&&(B.timestamp=B.unixEpochTimestamp)}h=E,s=E,t&&(n=E)}else if(S===lu)l=null;else if(S.startsWith(Os)){const T=S.slice(Os.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===uu){this.streamHasEnded=!0;break}else S.startsWith(Ds)&&S.slice(Ds.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=G(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 Kn({source:new hu(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 y=h.source.slice(t.location.offset,t.location.length??void 0).ref();h.free(),h=y}const p=new qr(h.source),m=wl(p,async()=>{const k={stack:[],error:void 0,hasError:!1};try{const y=Ws(k,await this.input._getSourceCached({path:f.keyUri,isRoot:!1},gd),!1),b=await new qr(y.source).requestSlice(0,Le);if(!b)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:N(b,Le),iv:f.iv}}catch(y){k.error=y,k.hasError=!0}finally{Ls(k)}},()=>{h.free()});u=new mu(m).ref()}else g(!1);return u}),formats:this.input._formats.filter(c=>!(c instanceof Eo)),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=Pn(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 bu extends ut{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 Mr);const e=await this.input._reader.requestEntireFile();g(e);const t=Ho(e,e.length,{ignore:yo}),{rootPath:i}=this.input._rootSource,n=[],s=[];for(let d=1;d<t.length;d++){const f=t[d];if(f.startsWith(Es)){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=gt(i,p),k=new Sr(f.slice(Es.length));if(k.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:k,lineNumber:h,hasOnlyKeyPackets:!1})}else if(f.startsWith(_s)){const h=new Sr(f.slice(_s.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 k=gt(i,p);n.push({fullPath:k,attributes:h,lineNumber:d,hasOnlyKeyPackets:!0})}else if(f.startsWith(vs)){const h=new Sr(f.slice(vs.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 k=null;const y=h.get("uri");y!==null&&(k=gt(i,y)),s.push({fullPath:k,attributes:h,lineNumber:d})}else if(f!==du){if(f.startsWith(fn)){const h=new Hs(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(C=>C.trim());
1else{const _=await this.getSegmentedInputForPath(d.fullPath).getTrackBackings(),B=await Promise.all(_.map(async v=>({track:v,codec:await v.getCodec()})));m=await Promise.all(B.filter(v=>v.codec!==null).map(v=>v.track.getDecoderConfig().then(O=>O.codec)))}const k=d.attributes.get("video"),y=d.attributes.get("audio"),w=m.some(C=>_e.includes(at(C))),b=m.some(C=>De.includes(at(C)));if(k!==null&&!w){if(!a.includes(k))throw new Error(`Invalid M3U8 file; variant stream references video group "${k}" which is not defined in any #EXT-X-MEDIA tags.`);const C=s.find(_=>{const B=_.attributes.get("group-id"),v=_.attributes.get("type");return B===k&&v.toLowerCase()==="video"});e:if(C){const _=C.attributes.get("uri");if(_===null)break e;const B=gt(i,_),D=(await this.getSegmentedInputForPath(B).getTrackBackings()).find(L=>L.getType()==="video");if(!D||await D.getCodec()===null)break e;const V=await D.getDecoderConfig().then(L=>L?.codec??null);g(V!==null),m.push(V)}}if(y!==null&&!b){if(!o.includes(y))throw new Error(`Invalid M3U8 file; variant stream references audio group "${y}" which is not defined in any #EXT-X-MEDIA tags.`);const C=s.find(_=>{const B=_.attributes.get("group-id"),v=_.attributes.get("type");return B===y&&v.toLowerCase()==="audio"});e:if(C){const _=C.attributes.get("uri");if(_===null)break e;
1const B=gt(i,_),D=(await this.getSegmentedInputForPath(B).getTrackBackings()).find(L=>L.getType()==="audio");if(!D||await D.getCodec()===null)break e;const V=await D.getDecoderConfig().then(L=>L?.codec??null);g(V!==null),m.push(V)}}m=[...new Set(m)];let S=null,T=null;const P=d.attributes.getAsNumber("bandwidth");g(P!==null);const E=d.attributes.getAsNumber("average-bandwidth"),I=d.attributes.get("name");for(const C of m){const _=at(C);if(_!==null){if(_e.includes(_)){if(S!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");S=C;const B=d.attributes.get("video");if(B===null){const v=d.attributes.get("resolution");let O=null,D=null;if(v){const V=v.match(/^(\d+)x(\d+)$/);V&&(O=Number(V[1]),D=Number(V[2]))}h.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:he,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:S,pairingMask:1n<<BigInt(f),peakBitrate:P,averageBitrate:E,name:I,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:O,height:D}})}else{if(!a.includes(B))throw new Error(`Invalid M3U8 file; variant stream references video group "${B}" which is not defined in any #EXT-X-MEDIA tags.`);for(const v of s){const O=v.attributes.get("group-id"),D=v.attributes.get("type");if(O!==B||D.toLowerCase()!=="video")continue;const V=v.attributes.get("resolution")??d.attributes.get("resolution");let L=null,te=null;if(V){const pe=V.match(/^(\d+)x(\d+)$/);pe&&(L=Number(pe[1]),te=Number(pe[2]))}h.push({id:-1,demuxer:this,backingTrack:null,default:zr(v.attributes),autoselect:zr(v.attributes)||qs(v.attributes),languageCode:js(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:L,height:te}})}}}else if(De.includes(_)){if(T!==null)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");T=C;const B=d.attributes.get("audio");if(B===null){const v=d.attributes.get("channels"),O=v!==null?Number(v.split("/")[0]):null;h.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:he,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:T,pairingMask:1n<<BigInt(f),peakBitrate:P,averageBitrate:E,name:I,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:O!==null&&Number.isInteger(O)&&O>0?O:null}})}else{if(!o.includes(B))throw new Error(`Invalid M3U8 file; variant stream references audio group "${B}" which is not defined in any #EXT-X-MEDIA tags.`);for(const v of s){const O=v.attributes.get("group-id"),D=v.attributes.get("type");if(O!==B||D.toLowerCase()!=="audio")continue;const V=v.attributes.get("channels")??d.attributes.get("channels"),L=V!==null?Number(V.split("/")[0]):null;h.push({id:-1,demuxer:this,backingTrack:null,default:zr(v.attributes),autoselect:zr(v.attributes)||qs(v.attributes),languageCode:js(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:L!==null&&Number.isInteger(L)&&L>0?L: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===he&&(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 xo(d)):this.trackBackings.push(new Co(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 Hs(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return ko}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class So{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 xo){for(const s of n)if(await s.getCodec()===this.getCodec()){t=s;break}}else{g(this instanceof Co);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{...lt,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)}
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 xo extends So{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return at(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 Co extends So{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return at(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 zr=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}".`)},qs=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}".`)},js=r=>{if(r===null)return he;const e=r.split("-")[0];return e||he};class Ge{constructor(){this._isIsobmff=!1}}class Po extends Ge{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=ie(t,4);return i!=="ftyp"&&i!=="styp"?null:ie(t,4)}_createDemuxer(e){return new Wn(e)}}class Tu extends Po{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=R(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=ie(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 Su extends Po{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class Io extends Ge{async isSupportedEBMLOfDocType(e,t){let i=e._reader.requestSlice(0,it);if(A(i)&&(i=await i),!i)return!1;const n=oo(i);if(n===null||n<1||n>8||j(i,n)!==x.EBML)return!1;const a=co(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-Ae;){const l=Ze(o);if(!l)break;const{id:u,size:d}=l,f=o.filePos;if(d===void 0)return!1;switch(u){case x.EBMLVersion:if(j(o,d)!==1)return!1;break;case x.EBMLReadVersion:if(j(o,d)!==1)return!1;break;case x.DocType:if(Kt(o,d)!==t)return!1;break;case x.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 Al(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class xu extends Io{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Cu extends Ge{async _canReadInput(e){let t=0;for(;;){let d=e._reader.requestSlice(t,Be);if(A(d)&&(d=await d),!d)break;const f=ct(d);if(!f)break;t=d.filePos+f.size}const i=await un(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=R(a);if(o===Ga||o===Xa)return!0;t=i.startPos+i.header.totalSize;const l=await un(e._reader,t,t+Mt);if(!l)return!1;const u=l.header;return!(n.channel!==u.channel||n.sampleRate!==u.sampleRate)}_createDemuxer(e){return new Rl(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}
1class Pu extends Ge{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(A(t)&&(t=await t),!t)return!1;const i=ie(t,4);return i!=="RIFF"&&i!=="RIFX"&&i!=="RF64"?!1:(t.skip(4),ie(t,4)==="WAVE")}_createDemuxer(e){return new Hl(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Iu extends Ge{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return A(t)&&(t=await t),t?ie(t,4)==="OggS":!1}_createDemuxer(e){return new Wl(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Eu extends Ge{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,Be);if(A(n)&&(n=await n),!n)break;const s=ct(n);if(!s)break;t=n.filePos+s.size}let i=e._reader.requestSlice(t,4);return A(i)&&(i=await i),i?ie(i,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Jl(e)}}class _u extends Ge{async _canReadInput(e){let t=0;for(;;){let a=e._reader.requestSlice(t,Be);if(A(a)&&(a=await a),!a)break;const o=ct(a);if(!o)break;t=a.filePos+o.size}let i=e._reader.requestSliceRange(t,Er,bt);if(A(i)&&(i=await i),!i)return!1;const n=ot(i);if(!n||(t+=n.frameLength,i=e._reader.requestSliceRange(t,Er,bt),A(i)&&(i=await i),!i))return!1;const s=ot(i);return s?n.objectType===s.objectType&&n.samplingFrequencyIndex===s.samplingFrequencyIndex&&n.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new jl(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class vu extends Ge{async _canReadInput(e){const t=Pe+16+1;let i=e._reader.requestSlice(0,t);if(A(i)&&(i=await i),!i)return!1;const n=N(i,t);return n[0]===71&&n[Pe]===71||n[0]===71&&n[Pe+16]===71?!0:n[4]===71&&n[4+Pe+4]===71}_createDemuxer(e){return new au(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Eo extends Ge{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(A(t)&&(t=await t),!t||!(ie(t,7)==="#EXTM3U"))return!1;if(!(e._rootSource instanceof Mr))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 bu(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return ko}}const Au=new Tu,Bu=new Su,Fu=new Io,Ru=new xu,Mu=new Cu,Ou=new Pu,Du=new Iu,zu=new _u,Nu=new Eu,Uu=new vu,Vu=new Eo,nh=[Vu,Au,Bu,Fu,Ru,Ou,Du,Nu,Mu,zu,Uu],Wu=(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 Lu=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},Hu=(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});Cn();let $s=-1/0,Ks=-1/0,_r=null;typeof FinalizationRegistry<"u"&&(_r=new FinalizationRegistry(r=>{const e=performance.now();r.type==="video"?(e-$s>=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."),$s=e),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(e-Ks>=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."),Ks=e),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));class Ct{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const hn=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],qu=new Set(hn);class ue{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(kt*this.timestamp)}get microsecondDuration(){return Math.trunc(kt*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||!qu.has(t.format))throw new TypeError("init.format must be one of: "+hn.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&&Pi(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??Ku(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
1opy?fe(e):fe(e).slice(),this._layout=i,this.colorSpace=new Oi(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&&Pi(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 Oi(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&&Pi(t.visibleRect,"init.visibleRect"),typeof VideoFrame<"u")return new ue(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*kt),duration:Math.trunc((t.duration??0)*kt)||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:xa(),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 Oi({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof Ct){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&&!hn.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=rr({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),_r?.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 Ct?new ue(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):lr(this._data)?new ue(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(g(this._layout),new ue(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 ue(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||(_r?.unregister(this),this._data instanceof Ct?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):lr(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Ys(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 lr(this._data)?this._data.allocationSize(e):Zs(this,e).allocationSize}async copyTo(e,t={}){if(!ti(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ys(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),lr(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 Ct){const l={stack:[],error:void 0,hasError:!1};try{const u=Lu(l,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(u instanceof ue))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{Hu(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=Zs(this,t);g(this.format);const n=fe(e);if(n.byteLength<i.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${i.allocationSize}, Available: ${n.byteLength}`);const s=mi(this.format);let a;if(this._data instanceof Ct){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:fe(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,k={offset:p,stride:u.destinationStride};for(let y=0;y<u.sourceHeight;y++){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 w=f.subarray(h,h+m);n.set(w,p),h+=d,p+=u.destinationStride}o.push(k)}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 Ct){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 lr(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,k=this.displayWidth,y=this.displayHeight;if(a!==void 0?(u=t,d=i,f=n,h=s,p=a,m=o,c!==void 0?(k=c,y=l):(k=f,y=h)):(p=t,m=i,n!==void 0&&(k=n,y=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(k)||k<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<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 w=this.toCanvasImageSource();e.save();const b=p+k/2,S=m+y/2;e.translate(b,S),e.rotate(this.rotation*Math.PI/180);const T=this.rotation%180===0?1:k/y;e.scale(1/T,T),e.drawImage(w,u,d,f,h,-k/2,-y/2,k,y),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&&mn(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=Qs(c,a,o));let l,u,d,f;const{sx:h,sy:p,sWidth:m,sHeight:k}=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[w,b]=t.crop?[t.crop.width,t.crop.height]:[a,o],S=t.fit==="contain"?Math.min(i/w,n/b):Math.max(i/w,n/b);d=w*S,f=b*S,l=(i-d)/2,u=(n-f)/2}e.save();const y=s%180===0?1:d/f;e.translate(i/2,n/2),e.rotate(s*Math.PI/180),e.scale(1/y,y),e.translate(-i/2,-n/2),e.drawImage(this.toCanvasImageSource(),h,p,m,k,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?Xs(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 k=u;k>1;k--){const y=n*2**k,w=s*2**k;p.drawImage(h,0,0,y,w,0,0,y/2,w/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 Ct||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&&mn(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=ei(this.rotation+(e.rotate??0)),[i,n]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let s=e.crop;s&&(s=Qs(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=Yi(l,e.roundDimensionsTo??1),u=Yi(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 ju){let k=m(this,d);if(A(k)&&(k=await k),k!==null)return k}const{canvas:f,context:h,isNew:p}=Xs(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 ue(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 ju=[],$u=3,cr=[];let Gs=0;const Xs=(r,e)=>{for(const n of cr)if(n.canvas.width===r&&n.canvas.height===e)return n.age=Gs++,{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 cr.length>=$u&&cr.splice(Pn(cr,n=>n.age),1),cr.push({canvas:t,context:i,age:Gs++}),{canvas:t,context:i,isNew:!0}};class Oi{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(zt);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(Nt);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(Ut);if(e.matrix!=null&&!n.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${n.join(", ")}.`);
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 lr=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,Qs=(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}},mn=(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.")},Ys=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.")}},Ku=(r,e,t)=>{const i=mi(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},mi=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:Ee(r),g(!1)}},Zs=(r,e)=>{const t={left:0,top:0,width:r.codedWidth,height:r.codedHeight},i=e.rect,n=Gu(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 Qu(n,a,s)},Gu=(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(!Xu(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},Xu=(r,e)=>{if(r===null)return!0;const t=mi(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},Qu=(r,e,t)=>{const i=mi(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 k=t[c];if(k.stride<h.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);h.destinationOffset=k.offset,h.destinationStride=k.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 k=0;k<c;k++){const y=a[k];if(!(o[c]<=y.destinationOffset||o[k]<=h.destinationOffset))throw new TypeError("Planes overlap.")}a.push(h)}return{allocationSize:s,computedLayouts:a}},Nr=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class ur{constructor(){this._referenceCount=0}}class de{get microsecondTimestamp(){return Math.trunc(kt*this.timestamp)}get microsecondDuration(){return Math.trunc(kt*this.duration)}constructor(e){if(this._closed=!1,dr(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 ur){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!Nr.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(!Nr.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/(pt(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*pt(this.format);if(i.byteLength<n)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}_r?.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&&!Nr.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=pt(t),a=Et(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(!ti(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&&!Nr.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=pt(c),p=Et(c);if(p&&a>=u)throw new RangeError("planeIndex out of range");if(!p&&a!==0)throw new RangeError("planeIndex out of range");const k=(p?f:f*u)*h;if(e.byteLength<k)throw new RangeError("Destination buffer is too small");const y=$(e),w=vo(c);if(dr(this._data))if(wr()&&u>2&&c!==o){Zu(this._data,y,o,c,u,a,d,f);return}else try{this._data.copyTo(e,{planeIndex:a,frameOffset:d,frameCount:f,format:c});return}
1catch(I){if(c==="f32-planar")throw I;o="f32-planar"}const b=_o(o),S=pt(o),T=Et(o);let P;if(this._data instanceof ur){const I=C=>{const _=this._data.getDataPlane(C);if(!(_ instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const B=l*S*(T?1:u);if(_.byteLength!==B)throw new TypeError(`Data plane ${C} has invalid size. Expected exactly ${B} bytes, got ${_.byteLength} bytes.`);return _};if(T)if(p)P=I(a),a=0;else{P=new Uint8Array(l*S*u);for(let C=0;C<u;C++){const _=I(C);P.set(_,C*l*S)}}else P=I(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 I=0;I<u;I++)this._data.copyTo(P.subarray(I*l*S,(I+1)*l*S),{format:"f32-planar",planeIndex:I})}const E=$(P);for(let I=0;I<f;I++)if(p){const C=I*h;let _;T?_=(a*l+(I+d))*S:_=((I+d)*u+a)*S;const B=b(E,_);w(y,C,B)}else for(let C=0;C<u;C++){const B=(I*u+C)*h;let v;T?v=(C*l+(I+d))*S:v=((I+d)*u+C)*S;const O=b(E,v);w(y,B,O)}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof ur){const e=new de(this._data);return e.setTimestamp(this.timestamp),e}else if(dr(this._data)){const e=new de(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new de({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=pt(this.format);let s;if(Et(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 de({data:s,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(_r?.unregister(this),this._data instanceof ur?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):dr(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 ur?this._createAudioDataFromData():dr(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(Et(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 de({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 de({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 pt=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")}},Et=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},_o=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)}},vo=r=>{switch(r){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,ae((i+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,ae(Math.round(i*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,ae(Math.round(i*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},dr=r=>typeof AudioData<"u"&&r instanceof AudioData,Yu=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}},Zu=(r,e,t,i,n,s,a,o)=>{const c=_o(t),l=vo(i),u=pt(t),d=pt(i),f=Et(t);if(Et(i))if(f){const p=new ArrayBuffer(o*u),m=$(p);r.copyTo(p,{planeIndex:s,frameOffset:a,frameCount:o,format:t});for(let k=0;k<o;k++){const y=k*u,w=k*d,b=c(m,y);l(e,w,b)}}else{const p=new ArrayBuffer(o*n*u),m=$(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let k=0;k<o;k++){const y=(k*n+s)*u,w=k*d,b=c(m,y);l(e,w,b)}}else if(f){const p=o*u,m=new ArrayBuffer(p),k=$(m);for(let y=0;y<n;y++){r.copyTo(m,{planeIndex:y,frameOffset:a,frameCount:o,format:t});for(let w=0;w<o;w++){const b=w*u,S=(w*n+y)*d,T=c(k,b);l(e,S,T)}}}else{const p=new ArrayBuffer(o*n*u),m=$(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let k=0;k<o;k++)for(let y=0;y<n;y++){const w=k*n+y,b=w*u,S=w*d,T=c(m,b);l(e,S,T)}}},Ju=(r,e)=>{const t=r.allocationSize({format:e,planeIndex:0}),i=new ArrayBuffer(t);return r.copyTo(i,{format:e,planeIndex:0}),new de({data:i,format:e,numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,timestamp:r.timestamp,duration:r.duration})};const Js=new Map,ea=new Map,Ao=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 Ie))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof Ie)&&(!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.");
1if(r.transform.crop!==void 0&&mn(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.");Bo(r.codec,r)},Bo=(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&&at(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.")},Fo=r=>{const e=r.bitrateMode,t=r.quality._toVideoRateControl(r.codec,r.width,r.height,e),i=(s,a,o)=>({codec:r.fullCodecString??rl(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,...sl(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},Ro=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!De.includes(r.codec))throw new TypeError(`Invalid audio codec '${r.codec}'. Must be one of: ${De.join(", ")}.`);const e=r.bitrate;if(r.quality===void 0&&e===void 0&&!(me.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 Ie))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof Ie)&&(!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.");
1if(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.");Mo(r.codec,r)},Mo=(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&&at(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`)},Oo=r=>{const e=r.bitrateMode;return{codec:r.fullCodecString??nl(r.codec,r.numberOfChannels,r.sampleRate),numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,bitrate:r.quality?._toAudioBitrate(r.codec),bitrateMode:r.quality?._bitrateMode??e,...al(r.codec)}};class Ie{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 ta):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"?ta[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=ed[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=ae(Math.round(dc(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=ae((a-s.worst)/(s.best-s.worst),0,1)),c=ra(e,t,i,Di(l))}return{quantizer:a,bitrate:c,bitrateMode:o}}_toVideoBitrate(e,t,i){return this._bitrate!==void 0?this._bitrate:(g(this._quality!==void 0),ra(e,t,i,Di(this._quality)))}_toAudioBitrate(e){if(me.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=Di(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 ta={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},ed={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}},Di=r=>.3*Math.exp(2.5538*r),ra=(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},Do=(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)},sh=new Ie("high"),td=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 Ie))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 Ie)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer or a quality.");Bo(r,a);const o=pi(n,s)??new Ie("medium");let c;try{c=Fo({codec:r,width:t,height:i,quality:o,framerate:void 0,...a,alpha:"discard"})}catch{return!1}const l=JSON.stringify(c),u=Js.get(l);if(u)return u;const d=(async()=>{for(const{config:h}of c)if(Uo.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(!xa()||await new Promise(async k=>{try{const y=new VideoEncoder({output:()=>{},error:()=>k(!1)});y.configure(h);const w=new Uint8Array(t*i*4),b=new VideoFrame(w,{format:"RGBA",codedWidth:t,codedHeight:i,timestamp:0});y.encode(b,p!==null?Do(r,p):void 0),b.close(),await y.flush(),k(!0)}catch{k(!1)}}))return!0}return!1})();return Js.set(l,d),d},rd=async(r,e={})=>{const{numberOfChannels:t=2,sampleRate:i=48e3,quality:n,bitrate:s,...a}=e;if(!De.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 Ie))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 Ie)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer.");Mo(r,a);const o=pi(n,s)??new Ie("medium"),c=Oo({codec:r,numberOfChannels:t,sampleRate:i,quality:o,...a}),l=JSON.stringify(c),u=ea.get(l);if(u)return u;const d=(async()=>{if(Vo.some(f=>f.supports(r,c))||me.includes(r))return!0;if(typeof AudioEncoder>"u")return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return ea.set(l,d),d},pi=(r,e)=>{if(r!==void 0)return r;if(e!==void 0)return e instanceof Ie?e:new Ie({bitrate:e})},ah=async(r=De,e)=>{const t=await Promise.all(r.map(i=>rd(i,e)));return r.filter((i,n)=>t[n])},oh=async(r,e)=>{for(const t of r)if(await td(t,e))return t;return null};const zo=[],No=[],Uo=[],Vo=[];const id=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},nd=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},sd=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},ad=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.")},Ot=r=>{if(!sr(r))throw new TypeError("timestamp must be a number.")},zi=(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 gi{constructor(e){if(!(e instanceof Or))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(Pt(e),this._track.input._disposed)throw new ke;return zi(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(Ot(e),Pt(t),this._track.input._disposed)throw new ke;return zi(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof Y))throw new TypeError("packet must be an EncodedPacket.");if(Pt(t),this._track.input._disposed)throw new ke;return zi(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Ot(e),Pt(t),this._track.input._disposed)throw new ke;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 Y))throw new TypeError("packet must be an EncodedPacket.");if(Pt(t),this._track.input._disposed)throw new ke;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 Y))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 Y))throw new TypeError("endPacket must be an EncodedPacket.");if(Pt(i),this._track.input._disposed)throw new ke;const n=[];let{promise:s,resolve:a}=oe(),{promise:o,resolve:c}=oe(),l=!1,u=!1,d=null,f=!1;const h=[],p=()=>Math.max(2,h.length);(async()=>{let k=e??await this.getFirstPacket(i);for(;k&&!u&&!this._track.input._disposed&&!(t&&k.sequenceNumber>=t?.sequenceNumber);){if(n.length>p()){({promise:o,resolve:c}=oe()),await o;continue}n.push(k),a(),{promise:s,resolve:a}=oe(),k=await this.getNextPacket(k,i)}l=!0,a()})().catch(k=>{f||(d=k,f=!0,a())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new ke;if(u)return{value:void 0,done:!0};if(f)throw d;if(n.length>0){const k=n.shift(),y=performance.now();for(h.push(y);h.length>0&&y-h[0]>=1e3;)h.shift();return c(),{value:k,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(k){throw k},[Symbol.asyncIterator](){return this}}}}class qn{constructor(e,t){this.onSample=e,this.onError=t}}class Wo{mediaSamplesInRange(e=-1/0,t=1/0,i){Ot(e),Ot(t);const n=[];let s=!1,a=null,{promise:o,resolve:c}=oe(),{promise:l,resolve:u}=oe(),d=!1,f=!1,h=!1,p=null,m=null,k=!1;const y={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=await this._createDecoder(C=>{if(u(),C.timestamp>=t&&(f=!0),f){C.close();return}a&&(C.timestamp>e?(n.push(a),s=!0):a.close()),C.timestamp>=e&&(n.push(C),s=!0),a=s?null:C,n.length>0&&(c(),{promise:o,resolve:c}=oe())},C=>{k||(m=C,k=!0,c())});const S=this._createPacketSink(),T=await S.getKeyPacket(e,y)??await S.getFirstKeyPacket(y);let P=T;const I=S.packets(T??void 0,void 0,y);for(await I.next();P&&!f&&!this._track.input._disposed;){const C=ia(n.length);if(n.length+p.getDecodeQueueSize()>C){({promise:l,resolve:u}=oe()),await l;continue}p.decode(P);const _=await I.next();if(_.done)break;P=_.value}await I.return(),!h&&!this._track.input._disposed&&await p.flush(),!s&&a&&n.push(a),d=!0,c()})().catch(S=>{k||(m=S,k=!0,c())}).finally(()=>{p?.close()});const w=this._track,b=()=>{a?.close();for(const S of n)S.close()};return{async next(){for(;;){if(w.input._disposed)throw h=!0,f=!0,b(),new ke;if(h)return{value:void 0,done:!0};if(k)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){cc(e);const i=oc(e),n=[],s=[];let{promise:a,resolve:o}=oe(),{promise:c,resolve:l}=oe(),u=!1,d=!1,f=null,h=null,p=!1;const m=b=>{s.push(b),o(),{promise:a,resolve:o}=oe()},k={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=await this._createDecoder(C=>{if(l(),d){C.close();return}let _=0;for(;n.length>0&&C.timestamp-n[0]>-1e-10;)_++,n.shift();if(_>0)for(let B=0;B<_;B++)m(B<_-1?C.clone():C);else C.close()},C=>{p||(h=C,p=!0,o())});const b=this._createPacketSink();let S=null,T=null,P=-1;const E=async()=>{g(T),g(f);let C=T;for(f.decode(C);C.sequenceNumber<P;){const _=ia(s.length);for(;s.length+f.getDecodeQueueSize()>_&&!d;)({promise:c,resolve:l}=oe()),await c;if(d)break;const B=await b.getNextPacket(C,k);g(B),f.decode(B),C=B}P=-1},I=async()=>{g(f),await f.flush();for(let C=0;C<n.length;C++)m(null);n.length=0};for await(const C of i){if(Ot(C),d||this._track.input._disposed)break;const _=await b.getPacket(C,k),B=_&&await b.getKeyPacket(C,k);if(!B){P!==-1&&(await E(),await I()),m(null),S=null;continue}S&&(B.sequenceNumber!==T.sequenceNumber||_.timestamp<S.timestamp)&&(await E(),await I()),n.push(_.timestamp),P=Math.max(_.sequenceNumber,P),S=_,T=B}!d&&!this._track.input._disposed&&(P!==-1&&await E(),await I()),u=!0,o()})().catch(b=>{p||(h=b,p=!0,o())}).finally(()=>{f?.close()});const y=this._track,w=()=>{for(const b of s)b?.close()};return{async next(){for(;;){if(y.input._disposed)throw d=!0,w(),new ke;if(d)return{value:void 0,done:!0};if(p)throw d=!0,w(),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(),w(),{value:void 0,done:!0}},async throw(b){throw b},[Symbol.asyncIterator](){return this}}}}const ia=r=>r===0?40:8;class od extends qn{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 ii,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=zo.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 ue))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(Ji()){if(i==="avc"&&this.decoderConfig.description){const u=Ba(fe(this.decoderConfig.description));if(u&&u.sequenceParameterSets.length>0){const d=li(u.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}wn(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),wr()||ts(this.inputTimestamps,e.timestamp,t=>t),Ji()&&this.currentPacketIndex===0){if(this.codec==="avc"){const t=[];let i=!1;for(const s of va(e.data,this.decoderConfig)){const a=ai(e.data[s.offset]);if(i||=a>=1&&a<=5,a===le.AUD){if(i)break;t.length=0}a>=20&&a<=31||t.push(e.data.subarray(s.offset,s.offset+s.length))}const n=bc(t,this.decoderConfig);e=new Y(n,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){const t=Bc(e.data,this.decoderConfig);t&&(e=new Y(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 cd),!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=di(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 $r(e,this.decoderConfig)){const i=ir(e[t.offset]);if(i===se.RASL_N||i===se.RASL_R)return!0}return!1}sampleHandler(e){if(wr()){if(this.sampleQueue.length>0&&e.timestamp>=ee(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=oe();this.mergeAlphaPromises.push(i.promise);const n={sample:null};this.finalSamples.push(n);try{if(!t)n.sample=new ue(e);else{g(this.merger);const s=await this.merger.merge(e,t);n.sample=new ue(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){const s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){Qi(this.finalSamples,n),this.onError(s)}finally{Qi(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),wr()){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 Ni=null;class cd{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(this.workers.length===0){if(!Ni){const o=new Blob([`(${ld.toString()})()`],{type:"application/javascript"});Ni=URL.createObjectURL(o)}const a=ae(navigator.hardwareConcurrency,1,4);for(let o=0;o<a;o++){const c=new Worker(Ni);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=oe();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 ld=()=>{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 w=0,b=3;w<h;w++,b+=4)p[b]=m[w];const y={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,y)},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 k,y;u.startsWith("I420")?(k=Math.ceil(d/2),y=Math.ceil(f/2)):u.startsWith("I422")?(k=Math.ceil(d/2),y=f):(k=d,y=f);const w=d*f,b=k*y,S=w*m,T=b*m,P=w*m,E=S+2*T+P,I=new Uint8Array(E);await c.copyTo(I);const C=await o(l,d,f,m),_=S+2*T;I.set(C,_);const v={format:u.slice(0,4)+"A"+u.slice(4),codedWidth:d,codedHeight:f,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[I.buffer]};return new VideoFrame(I,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,k=c.allocationSize();(!e||e.byteLength!==k)&&(e=new Uint8Array(k)),await c.copyTo(e);const y=new Uint8Array(f+2*m+f);y.set(e.subarray(0,f),0);const w=f,b=f+m,S=f;for(let E=0;E<m;E++)y[w+E]=e[S+E*2],y[b+E]=e[S+E*2+1];const T=await o(l,u,d,1);y.set(T,f+2*m);const P={format:"I420A",codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[y.buffer]};return new VideoFrame(y,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 k=0;k<m;k++)r[k]=r[k*4+p];return r.subarray(0,m)}else return r.subarray(0,l*u*d)}},ud=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 ch extends Wo{constructor(e,t={}){if(!(e instanceof jn))throw new TypeError("videoTrack must be an InputVideoTrack.");ud(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(ni("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 od(e,t,i,s,n,a)}_createPacketSink(){return new gi(this._track)}async getSample(e,t={}){Ot(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 dd extends qn{constructor(e,t,i,n){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new ii,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=No.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 de))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 de(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 fd extends qn{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,g(me.includes(i.codec)),this.codec=i.codec;const{dataType:n,sampleSize:s,littleEndian:a}=$e(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)=>nd(o.getUint8(c)):n==="alaw"?this.readInputValue=(o,c)=>ad(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)=>ri(o,c,a)-2**23:n==="signed"?this.readInputValue=(o,c)=>lc(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:Ee(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:Ee(s),g(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=$(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 de({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:c});this.onSample(l)}async flush(){}close(){}}class lh extends Wo{constructor(e){if(!(e instanceof $n))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(ni("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),me.includes(n.codec)?new fd(e,t,n):new dd(e,t,i,n)}_createPacketSink(){return new gi(this._track)}async getSample(e,t={}){Ot(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 Or{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof jn}isAudioTrack(){return this instanceof $n}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Z(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Z(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Z(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Z(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 Z(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 tr(i,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){const i=new gi(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 Or))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(_t({filter:t=>t.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(_t({filter:t=>t.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(_t({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(_t({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(_t({filter:t=>t.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=Ui(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&&=Ui(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=Ui(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const Z=(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},Ui=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 jn extends Or{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 Z(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 Z(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Z(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return Z(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Z(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Z(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=rr({num:await this.get
1SquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=rr({num:Z(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Z(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:Z(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Z(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=Z(e,"displayWidth","getDisplayWidth");if(n!==null)return n}const i=Z(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Z(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=Z(e,"displayHeight","getDisplayHeight");if(n!==null)return n}const i=Z(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Z(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),zo.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 Y))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),di(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&&(!sr(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 gi(this),s=[];let a=-1/0,o=0;for await(const _ of n.packets(void 0,void 0,{metadataOnly:!0})){if(s.length>=i&&_.timestamp>=a)break;s.push(_.timestamp),a=Math.max(a,_.timestamp),o++}const c=new Float64Array(s.length);for(let _=0;_<s.length;_++)c[_]=Math.round(s[_]*t);c.sort();let l=1;for(let _=1;_<c.length;_++)c[_]!==c[l-1]&&(c[l++]=c[_]);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=hd(u,t),f=d??t,h=d!==null?t/d:null,p=new Map;let m=1/0,k=-1/0,y=0;for(let _=1;_<l;_++){const B=u[_]-u[_-1],v=h!==null?Math.max(1,Math.round(B/h)):B;p.set(v,(p.get(v)??0)+1),m=Math.min(m,v),k=Math.max(k,v),y+=v}const w=l-1,b=[...p.keys()].sort((_,B)=>_-B),S=w-1>>1,T=w>>1;let P=0,E=0,I=0;for(const _ of b)if(I+=p.get(_),P===0&&I>S&&(P=_),I>T){E=_;break}const C=(f/P+f/E)/2;return{underlyingFrameRate:d,bestGuessFrameRate:d!==null?d:md(C),minFrameRate:f/k,maxFrameRate:f/m,averageFrameRate:f*w/y,medianFrameRate:C,frameRateIsConstant:d!==null&&m===1&&k===1,probedPacketCount:o}}}class $n extends Or{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Z(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Z(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Z(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),No.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 Y))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}}const na=r=>-(r??-1/0),fr=r=>-r,hr=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}},_t=(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}),Vi=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)},hd=(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 E=1;E<r.length;E++){const I=r[E]-r[E-1];if(!(I>0))return null;o[E-1]=I}const c=o.slice();c.sort();let l=c[Math.floor(c.length*.05)];for(let E=0;E<6;E++){let I=0,C=0;for(const B of o){const v=Math.max(1,Math.round(B/l));Math.abs(B-v*l)>=n||(I+=B,C+=v)}if(C===0)return null;const _=I/C;if(Math.abs(_-l)<=1e-12*Math.max(1,l)){l=_;break}l=_}let u=0,d=0,f=0;for(const E of o){const I=Math.max(1,Math.round(E/l));Math.abs(E-I*l)>=n||(u++,d+=E,f+=I)}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,k=e/m,y=e/p,w=e/l;let b=null,S=1/0;for(const E of a){if(E<k||E>y)continue;const I=Math.abs(E/w-1);I<S&&(b=E,S=I)}if(b===null){const E=sa(p,m,1e6),I=sa(k,y,1e6);if(I&&(!E||I.den<E.den||I.den===E.den&&I.num<=E.num))b=I.num/I.den;else if(E)b=e*E.den/E.num;else return null}const T=e/b;let P=0;for(const E of o){const I=Math.max(1,Math.round(E/T));Math.abs(E-I*T)<n&&P++}return P/o.length<.98?null:b},sa=(r,e,t)=>{for(let i=1;i<=t;i++){const n=Math.floor(r*i)+1;if(n/i<e)return rr({num:n,den:i})}return null},md=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};Cn();const pd=1,gd=2;class Kn extends Br{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 Ge)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof je||e.source instanceof Hn))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof je&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof Kn))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&Wu(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof je?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 Mr);const t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}
1_getSourceCached(e,t=pd){const i=this._sourceCache.find(a=>a.cacheGroup===t&&Us(a.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const n=this._sourceCachePromises.find(a=>a.cacheGroup===t&&Us(a.request,e));if(n)return n.promise.then(a=>a.sourceRef.source.ref());const s=(async()=>{const a=await this._getSourceUncached(e);if(gr(this._sourceCache,d=>d.cacheGroup===t&&d.sourceRef.source._refCount===1)>=4){const d=Pn(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(),Qi(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 qr(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new aa})()}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 aa)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&&=hr(e);const i=(await this._getTrackBackings()).map(n=>this._wrapBackingAsTrack(n));return Vi(i,e)}async getVideoTracks(e){e&&=hr(e);const i=(await this.getTracks()).filter(n=>n.isVideoTrack());return Vi(i,e)}async getAudioTracks(e){e&&=hr(e);const i=(await this.getTracks()).filter(n=>n.isAudioTrack());return Vi(i,e)}async getPrimaryVideoTrack(e){e&&=hr(e);const t=_t(e,{sortBy:async n=>[fr((await n.getDisposition()).default),fr(await n.hasPairableAudioTrack()),fr(!await n.hasOnlyKeyPackets()),na(await n.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=hr(e);const t=await this.getPrimaryVideoTrack(),i=_t(e,{sortBy:async s=>[fr(!t||s.canBePairedWith(t)),fr((await s.getDisposition()).default),na(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 jn(this,e):new $n(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 aa extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class ke extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class qr{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 ke;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){const s=new Uint8Array(0);return new Te(s,$(s),0,e,e)}const i=e+t,n=this.source._read(e,i,bo,To);return A(n)?n.then(s=>s?new Te(s.bytes,s.view,s.offset,e,i):null):n?new Te(n.bytes,n.view,n.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new ke;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,ae(this.fileSizeNonStrict-e,t,i));{const n=this.requestSlice(e,i),s=a=>
1a||(g(this.fileSizeNonStrict!==null),this.requestSlice(e,ae(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=N(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 Te(n,$(n),0,0,i)})()}}class Te{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 Te(e,$(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 Te(this.bytes,this.view,this.offset,e,e+t)}}const xe=(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.`)},N=(r,e)=>{xe(r,e);const t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},z=r=>(xe(r,1),r.view.getUint8(r.bufferPos++)),mr=(r,e)=>{xe(r,2);const t=r.view.getUint16(r.bufferPos,e);return r.bufferPos+=2,t},ne=r=>{xe(r,2);const e=r.view.getUint16(r.bufferPos,!1);return r.bufferPos+=2,e},Qe=r=>{xe(r,3);const e=ri(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},pn=r=>{xe(r,2);const e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},wt=(r,e)=>{xe(r,4);const t=r.view.getUint32(r.bufferPos,e);return r.bufferPos+=4,t},R=r=>{xe(r,4);const e=r.view.getUint32(r.bufferPos,!1);return r.bufferPos+=4,e},Xt=r=>{xe(r,4);const e=r.view.getUint32(r.bufferPos,!0);return r.bufferPos+=4,e},Bt=r=>{xe(r,4);const e=r.view.getInt32(r.bufferPos,!1);return r.bufferPos+=4,e},kd=r=>{xe(r,4);const e=r.view.getInt32(r.bufferPos,!0);return r.bufferPos+=4,e},oa=(r,e)=>{let t,i;return e?(t=wt(r,!0),i=wt(r,!0)):(i=wt(r,!1),t=wt(r,!1)),i*4294967296+t},Ce=r=>{const e=R(r),t=R(r);return e*4294967296+t},yd=r=>{const e=Bt(r),t=R(r);return e*4294967296+t},wd=r=>{const e=Xt(r);return kd(r)*4294967296+e},bd=r=>{xe(r,4);const e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},Lo=r=>{xe(r,8);const e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e},ie=(r,e)=>{xe(r,e);let t="";for(let i=0;i<e;i++)t+=String.fromCharCode(r.bytes[r.bufferPos++]);return t},Ho=(r,e,t)=>Se.decode(N(r,e)).split(` 2`).map(s=>s.trim()).filter(s=>s.length>0&&!t?.ignore?.(s));var Ft;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})(Ft||(Ft={}));var Qt;(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"})(Qt||(Qt={}));const jr=128,Be=10,Yt=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Po
2p-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"],Td=(r,e)=>{const t=r.filePos;e.raw??={},e.raw.TAG??=N(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=N(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=z(r);u<Yt.length&&(e.genre??=Yt[u])},Wt=(r,e)=>{const t=N(r,e),i=Lt(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()},ct=r=>{const e=r.filePos,t=ie(r,3),i=z(r),n=z(r),s=z(r),a=R(r);if(t!=="ID3"||i===255||n===255||(a&2155905152)!==0)return r.filePos=e,null;let o=nn(a);return s&Ft.Footer&&(o+=Be),{majorVersion:i,revision:n,flags:s,size:o}},ki=(r,e,t)=>{if(![2,3,4].includes(e.majorVersion)){H._warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}const i=e.flags&Ft.Footer?e.size-Be:e.size,n=N(r,i),s=new Sd(e,n);if(e.flags&Ft.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&Ft.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&Ft.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(Yt[p]!==void 0){t.genre??=Yt[p];break}}if(h=/^\d+$/.exec(f),h){const p=Number.parseInt(h[0]);if(Yt[p]!==void 0){t.genre??=Yt[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 y=s.readAscii(3);h=y==="PNG"?"image/png":y==="JPG"?"image/jpeg":"image/*"}else h=s.readId3V2Text(f,c);const p=s.readU8(),m=s.readId3V2Text(f,c).trimEnd(),k=c-s.pos;if(k>=0){const y=s.readBytes(k);t.images||(t.images=[]),t.images.push({data:y,mimeType:h,kind:p===3?"coverFront":p===4?"coverBack":"unknown",description:m})}}break;default:s.pos+=a.size;break}s.pos=c}};class Sd{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?nn(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:nn(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 Qt.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 Qt.UTF_16_WITH_BOM:if(n[0]===255&&n[1]===254){const s=new TextDecoder("utf-16le"),a=Lt(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=Lt(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=Lt(n.findIndex(a=>a===0),n.length);return this.pos=i+Math.min(s+1,n.length),Se.decode(n.subarray(0,s))}case Qt.UTF_16_BE_NO_BOM:{const s=new TextDecoder("utf-16be"),a=Lt(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 Qt.UTF_8:{const s=Lt(n.findIndex(a=>a===0),n.length);return this.pos=i+Math.min(s+1,n.length),Se.decode(n.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class qo{constructor(e){this.mutex=new nr,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 Jr=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,xd=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Cd=r=>{const e=xd.exec(r);if(!e)throw new Error("Expected match.");return 3600*1e3*Number(e[1]||"0")+60*1e3*Number(e[2])+1e3*Number(e[3])+Number(e[4])},jo=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 Ur{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),Fe=new DataView(q.buffer),re=r=>[(r%256+256)%256],W=r=>(Fe.setUint16(0,r,!1),[q[0],q[1]]),Gn=r=>(Fe.setInt16(0,r,!1),[q[0],q[1]]),$o=r=>(Fe.setUint32(0,r,!1),[q[1],q[2],q[3]]),F=r=>(Fe.setUint32(0,r,!1),[q[0],q[1],q[2],q[3]]),nt=r=>(Fe.setInt32(0,r,!1),[q[0],q[1],q[2],q[3]]),Ke=r=>(Fe.setUint32(0,Math.floor(r/2**32),!1),Fe.setUint32(4,r,!1),[q[0],q[1],q[2],q[3],q[4],q[5],q[6],q[7]]),Pd=r=>(Fe.setInt32(0,Math.floor(r/2**32),!1),Fe.setUint32(4,r,!1),[q[0],q[1],q[2],q[3],q[4],q[5],q[6],q[7]]),Ko=r=>(Fe.setInt16(0,2**8*r,!1),[q[0],q[1]]),Me=r=>(Fe.setInt32(0,2**16*r,!1),[q[0],q[1],q[2],q[3]]),Wi=r=>(Fe.setInt32(0,2**30*r,!1),[q[0],q[1],q[2],q[3]]),Li=(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()},Q=(r,e=!1)=>{const t=Array(r.length).fill(null).map((i,n)=>r.charCodeAt(n));return e&&t.push(0),t},Go=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]},Xo=Go(0),Qo=r=>[Me(r[0]),Me(r[1]),Wi(r[2]),Me(r[3]),Me(r[4]),Wi(r[5]),Me(r[6]),Me(r[7]),Wi(r[8])],U=(r,e,t)=>({type:r,contents:e&&new Uint8Array(e.flat(10)),children:t}),X=(r,e,t,i,n)=>U(r,[re(e),$o(t),i??[]],n),Id=r=>r.isQuickTime?U("ftyp",[Q("qt "),F(512),Q("qt ")]):r.fragmented?r.cmaf?U("ftyp",[Q("iso5"),F(512),Q("iso5"),Q("iso6"),Q("mp41"),Q("cmfc"),Q("dash")]):U("ftyp",[Q("iso5"),F(512),Q("iso5"),Q("iso6"),Q("mp41")]):U("ftyp",[Q("isom"),F(512),Q("isom"),r.holdsAvc?Q("avc1"):[],Q("mp41")]),ca=()=>U("styp",[Q("iso5"),F(0),Q("iso5"),Q("iso6"),Q("mp41"),Q("cmfc"),Q("dash")]),la=(r,e)=>{let t=r.maxWrittenEndTimestamp-r.minWrittenTimestamp;return Number.isFinite(t)||(t=0),X("sidx",1,0,[F(1),F(Oe),Ke(J(r.minWrittenTimestamp,Oe)),Ke(0),W(0),W(1),F(e&2147483647),F(J(t,Oe)),F(0)])},Vr=r=>({type:"mdat",largeSize:r}),Ed=r=>({type:"free",size:r}),pr=r=>U("moov",void 0,[_d(r.creationTime,r.trackDatas),...r.trackDatas.map(e=>vd(e,r.creationTime)),r.isFragmented?gf(r.trackDatas):null,vf(r)]
2),_d=(r,e)=>{const t=Math.max(0,...e.map(a=>J(yi(a),Oe)+J(a.startTimestampOffset??0,Oe))),i=Math.max(0,...e.map(a=>a.track.id))+1,n=!Tt(r)||!Tt(t),s=n?Ke:F;return X("mvhd",+n,0,[s(r),s(r),F(Oe),s(t),Me(1),Ko(1),Array(10).fill(0),Qo(Xo),Array(24).fill(0),F(i)])},yi=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},vd=(r,e)=>{const t=Vf(r),i=r.startTimestampOffset!==null&&r.startTimestampOffset>0;return U("trak",void 0,[Ad(r,e),i?Bd(r,r.startTimestampOffset):null,Fd(r,e),t.name!==void 0?U("udta",void 0,[U("name",[...be.encode(t.name)])]):null])},Ad=(r,e)=>{const t=J(yi(r),Oe)+J(r.startTimestampOffset??0,Oe),i=!Tt(e)||!Tt(t),n=i?Ke:F;let s;if(r.type==="video"){const c=r.track.metadata.rotation;s=Go(c??0)}else s=Xo;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:Ee(r);return X("tkhd",+i,a,[n(e),n(e),F(r.track.id),F(0),n(t),Array(8).fill(0),W(0),W(o),Ko(r.type==="audio"?1:0),W(0),Qo(s),Me(r.type==="video"?r.info.width:0),Me(r.type==="video"?r.info.height:0)])},Bd=(r,e)=>{const t=J(e,Oe),i=J(yi(r),Oe),n=!Tt(t)||!Tt(i),s=n?Ke:F,a=n?Pd:nt;return U("edts",void 0,[X("elst",n?1:0,0,[F(2),s(t),a(-1),Me(1),s(i),a(0),Me(1)])])},Fd=(r,e)=>U("mdia",void 0,[Rd(r,e),Xn(!0,Md[r.type],Od[r.type]),Dd(r)]),Rd=(r,e)=>{const t=J(yi(r),r.timescale),i=!Tt(e)||!Tt(t),n=i?Ke:F;return X("mdhd",+i,0,[n(e),n(e),F(r.timescale),n(t),W(ec(r.track.metadata.languageCode??he)),W(0)])},Md={video:"vide",audio:"soun",subtitle:"text"},Od={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Xn=(r,e,t,i="\0\0\0\0")=>X("hdlr",0,0,[r?Q("mhlr"):F(0),Q(e),Q(i),F(0),F(0),Q(t,!0)]),Dd=r=>U("minf",void 0,[Vd[r.type](),Wd(),qd(r)]),zd=()=>X("vmhd",0,1,[W(0),W(0),W(0),W(0)]),Nd=()=>X("smhd",0,0,[W(0),W(0)]),Ud=()=>X("nmhd",0,0),Vd={video:zd,audio:Nd,subtitle:Ud},Wd=()=>U("dinf",void 0,[Ld()]),Ld=()=>X("dref",0,0,[F(1)],[Hd()]),Hd=()=>X("url ",0,1),qd=r=>{const e=r.compositionTimeOffsetTable.length>1||r.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return U("stbl",void 0,[jd(r),lf(r),e?mf(r):null,e?pf(r):null,df(r),ff(r),hf(r),uf(r)])},jd=r=>{let e;if(r.type==="video")e=$d(Rf(r.track.source._codec,r.info.decoderConfig.codec),r);else if(r.type==="audio"){const t=Jo(r.track.source._codec,r.info.decoderConfig.codec,r.muxer.isQuickTime);g(t),e=Zd(t,r)}else r.type==="subtitle"&&(e=of(Df[r.track.source._codec],r));return g(e),X("stsd",0,0,[F(1)],[e])},$d=(r,e)=>U(r,[Array(6).fill(0),W(1),W(0),W(0),Array(12).fill(0),W(e.info.width),W(e.info.height),F(4718592),F(4718592),F(0),W(1),re(10),Q("Mediabunny"),Array(21).fill(0),W(e.info.hasAlphaChannel?32:24),Gn(65535)],[Mf[e.track.source._codec]?.(e)??null,Kd(e),ba(e.info.decoderConfig.colorSpace)?null:Gd(e)]),Kd=r=>r.info.pixelAspectRatio.num===r.info.pixelAspectRatio.den?null:U("pasp",[F(r.info.pixelAspectRatio.num),F(r.info.pixelAspectRatio.den)]),Gd=r=>{const e=r.info.decoderConfig.colorSpace;return U("colr",[Q(r.muxer.isQuickTime?"nclc":"nclx"),W(e?.primaries!=null?zt[e.primaries]:2),W(e?.transfer!=null?Nt[e.transfer]:2),W(e?.matrix!=null?Ut[e.matrix]:2),r.muxer.isQuickTime?[]:re((e?.fullRange?1:0)<<7)])},Xd=r=>r.info.decoderConfig&&U("avcC",[...fe(r.info.decoderConfig.description)]),Qd=r=>r.info.decoderConfig&&U("hvcC",[...fe(r.info.decoderConfig.description)]),ua=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?zt[e.colorSpace.primaries]:1,u=t[6]?Number(t[6]):e.colorSpace?.transfer?Nt[e.colorSpace.transfer]:1,d=t[7]?Number(t[7]):e.colorSpace?.matrix?Ut[e.colorSpace.matrix]:1;return X("vpcC",1,0,[re(i),re(n),re(c),re(l),re(u),re(d),W(0)])},Yd=r=>U("av1C",qa(r.info.decoderConfig.codec)),Zd=(r,e)=>{let t=0,i,n=16;const s=me.includes(e.track.source._codec);if(s){const a=e.track.source._codec,{sampleSize:o}=$e(a);n=8*o,n>16&&(t=1)}if(e.muxer.isQuickTime&&(t=1),t===0)i=[Array(6).fill(0),W(1),W(t),W(0),F(0),W(e.info.numberOfChannels),W(n),W(0),W(0),W(e.info.sampleRate<2**16?e.info.sampleRate:0),W(0)];else{const a=s?0:-2;i=[Array(6).fill(0),W(1),W(t),W(0),F(0),W(e.info.numberOfChannels),W(Math.min(n,16)),Gn(a),W(0),W(e.info.sampleRate<2**16?e.info.sampleRate:0),W(0),s?[F(1),F(n/8),F(e.info.numberOfChannels*n/8)]:[F(0),F(0),F(0)],F(2)]}return U(r,i,[Of(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},Hi=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=[...re(e),...re(21),...$o(0),...F(0),...F(0)];if(r.info.decoderConfig.description){const i=fe(r.info.decoderConfig.description);t=[...t,...re(5),...Li(i.byteLength),...i]}return t=[...W(1),...re(0),...re(4),...Li(t.length),...t,...re(6),...re(1),...re(2)],t=[...re(3),...Li(t.length),...t],X("esds",0,0,t)},dt=r=>U("wave",void 0,[Jd(r),ef(r),U("\0\0\0\0")]),Jd=r=>U("frma",[Q(Jo(r.track.source._codec,r.info.decoderConfig.codec,r.muxer.isQuickTime))]),ef=r=>{const{littleEndian:e}=$e(r.track.source._codec);return U("enda",[W(+e)])},tf=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=fe(o),l=Fn(c);e=l.outputChannelCount,t=l.preSkip,i=l.inputSampleRate,n=l.outputGain,s=l.channelMappingFamily,l.channelMappingTable&&(a=l.channelMappingTable)}return U("dOps",[re(0),re(e),W(t),F(i),Gn(n),re(s),...a])},rf=r=>{const e=r.info.decoderConfig?.description;g(e);const t=fe(e);return X("dfLa",0,0,[...t.subarray(4)])},Ue=r=>{const{littleEndian:e,sampleSize:t}=$e(r.track.source._codec),i=+e;return X("pcmC",0,0,[re(i),re(8*t)])},nf=r=>{g(r.info.primingPacket);const e=Da(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 K(t);return i.writeBits(2,e.fscod),i.writeBits(5,e.bsid),i.writeBits(3,e.b
2smod),i.writeBits(3,e.acmod),i.writeBits(1,e.lfeon),i.writeBits(5,e.bitRateCode),i.writeBits(5,0),U("dac3",[...t])},sf=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 K(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 U("dec3",[...n])},af=r=>{g(r.info.primingPacket);const e=On(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 U("ddts",[...Jc(e)])},of=(r,e)=>U(r,[Array(6).fill(0),W(1)],[zf[e.track.source._codec](e)]),cf=r=>U("vttC",[...be.encode(r.info.config.description)]),lf=r=>X("stts",0,0,[F(r.timeToSampleTable.length),r.timeToSampleTable.map(e=>[F(e.sampleCount),F(e.sampleDelta)])]),uf=r=>{if(r.samples.every(t=>t.type==="key"))return null;const e=[...r.samples.entries()].filter(([,t])=>t.type==="key");return X("stss",0,0,[F(e.length),e.map(([t])=>F(t+1))])},df=r=>X("stsc",0,0,[F(r.compactlyCodedChunkTable.length),r.compactlyCodedChunkTable.map(e=>[F(e.firstChunk),F(e.samplesPerChunk),F(1)])]),ff=r=>{if(r.type==="audio"&&r.info.requiresPcmTransformation){const{sampleSize:e}=$e(r.track.source._codec);return X("stsz",0,0,[F(e*r.info.numberOfChannels),F(r.samples.reduce((t,i)=>t+J(i.duration,r.timescale),0))])}return X("stsz",0,0,[F(0),F(r.samples.length),r.samples.map(e=>F(e.size))])},hf=r=>r.finalizedChunks.length>0&&ee(r.finalizedChunks).offset>=2**32?X("co64",0,0,[F(r.finalizedChunks.length),r.finalizedChunks.map(e=>Ke(e.offset))]):X("stco",0,0,[F(r.finalizedChunks.length),r.finalizedChunks.map(e=>F(e.offset))]),mf=r=>X("ctts",1,0,[F(r.compositionTimeOffsetTable.length),r.compositionTimeOffsetTable.map(e=>[F(e.sampleCount),nt(e.sampleCompositionTimeOffset)])]),pf=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,J(o.timestamp,r.timescale)),n=Math.max(n,J(o.timestamp+o.duration,r.timescale))}const s=Math.max(-e,0);return n>=2**31?null:X("cslg",0,0,[nt(s),nt(e),nt(t),nt(i),nt(n)])},gf=r=>U("mvex",void 0,r.map(kf)),kf=r=>X("trex",0,0,[F(r.track.id),F(1),F(0),F(0),F(0)]),da=(r,e)=>U("moof",void 0,[yf(r),...e.map(wf)]),yf=r=>X("mfhd",0,0,[F(r)]),Yo=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=>U("traf",void 0,[bf(r),Tf(r),Sf(r)]),bf=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:Yo(t)};return X("tfhd",0,e,[F(r.track.id),F(i.duration),F(i.size),F(i.flags)])},Tf=r=>(g(r.currentChunk),X("tfdt",1,0,[Ke(J(r.currentChunk.startTimestamp,r.timescale))])),Sf=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(Yo),n=r.currentChunk.samples.map(m=>J(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,X("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,k)=>[u?F(e[k]):[],d?F(t[k]):[],f?F(i[k]):[],h?nt(n[k]):[]])])},xf=r=>U("mfra",void 0,[...r.map(Cf),Pf()]),Cf=r=>X("tfra",1,0,[F(r.track.id),F(63),F(r.finalizedChunks.length),r.finalizedChunks.map(t=>[Ke(J(t.samples[0].timestamp,r.timescale)),Ke(t.moofOffset),F(t.trafIndex+1),F(1),F(1)])]),Pf=()=>X("mfro",0,0,[F(0)]),If=()=>U("vtte"),Ef=(r,e,t,i,n)=>U("vttc",void 0,[n!==null?U("vsid",[nt(n)]):null,t!==null?U("iden",[...be.encode(t)]):null,e!==null?U("ctim",[...be.encode(jo(e))]):null,i!==null?U("sttg",[...be.encode(i)]):null,U("payl",[...be.encode(r)])]),_f=r=>U("vtta",[...be.encode(r)]),vf=r=>{const e=[],t=r.format._options.metadataFormat??"auto",i=r.output._metadataTags;if(t==="mdir"||t==="auto"&&!r.isQuickTime){const n=Bf(i);n&&e.push(n)}else if(t==="mdta"){const n=Ff(i);n&&e.push(n)}else(t==="udta"||t==="auto"&&r.isQuickTime)&&Af(e,r.output._metadataTags);return e.length===0?null:U("udta",void 0,e)},Af=(r,e)=>{for(const{key:t,value:i}
2of xn(e))switch(t){case"title":r.push(Ve("©nam",i));break;case"description":r.push(Ve("©des",i));break;case"artist":r.push(Ve("©ART",i));break;case"album":r.push(Ve("©alb",i));break;case"albumArtist":r.push(Ve("albr",i));break;case"genre":r.push(Ve("©gen",i));break;case"date":r.push(Ve("©day",i.toISOString().slice(0,10)));break;case"comment":r.push(Ve("©cmt",i));break;case"lyrics":r.push(Ve("©lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:Ee(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(Ve(t,i)):i instanceof Uint8Array&&r.push(U(t,Array.from(i))))}},Ve=(r,e)=>{const t=be.encode(e);return U(r,[W(t.length),W(ec("und")),Array.from(t)])},fa={"image/jpeg":13,"image/png":14,"image/bmp":27},Zo=(r,e)=>{const t=[];for(const{key:i,value:n}of xn(r))switch(i){case"title":t.push({key:e?"title":"©nam",value:Re(n)});break;case"description":t.push({key:e?"description":"©des",value:Re(n)});break;case"artist":t.push({key:e?"artist":"©ART",value:Re(n)});break;case"album":t.push({key:e?"album":"©alb",value:Re(n)});break;case"albumArtist":t.push({key:e?"album_artist":"aART",value:Re(n)});break;case"comment":t.push({key:e?"comment":"©cmt",value:Re(n)});break;case"genre":t.push({key:e?"genre":"©gen",value:Re(n)});break;case"lyrics":t.push({key:e?"lyrics":"©lyr",value:Re(n)});break;case"date":t.push({key:e?"date":"©day",value:Re(n.toISOString().slice(0,10))});break;case"images":for(const s of n)s.kind==="coverFront"&&t.push({key:"covr",value:U("data",[F(fa[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:Re(s)})}else t.push({key:"trkn",value:U("data",[F(0),F(0),W(0),W(n),W(r.tracksTotal??0),W(0)])});break;case"discNumber":e||t.push({key:"disc",value:U("data",[F(0),F(0),W(0),W(n),W(r.discsTotal??0),W(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:Ee(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:Re(n)}):n instanceof Uint8Array?t.push({key:i,value:U("data",[F(0),F(0),Array.from(n)])}):n instanceof Zt&&t.push({key:i,value:U("data",[F(fa[n.mimeType]??0),F(0),Array.from(n.data)])}))}return t},Bf=r=>{const e=Zo(r,!1);return e.length===0?null:X("meta",0,0,void 0,[Xn(!1,"mdir","","appl"),U("ilst",void 0,e.map(t=>U(t.key,void 0,[t.value])))])},Ff=r=>{const e=Zo(r,!0);return e.length===0?null:U("meta",void 0,[Xn(!1,"mdta",""),X("keys",0,0,[F(e.length)],e.map(t=>U("mdta",[...be.encode(t.key)]))),U("ilst",void 0,e.map((t,i)=>{const n=String.fromCharCode(...F(i+1));return U(n,void 0,[t.value])}))])},Re=r=>U("data",[F(1),F(0),...be.encode(r)]),Rf=(r,e)=>{switch(r){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";
2case"prores":return e}},Mf={avc:Xd,hevc:Qd,vp8:ua,vp9:ua,av1:Yd,prores:null},Jo=(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"}},Of=(r,e)=>{switch(r){case"aac":return Hi;case"mp3":return Hi;case"opus":return tf;case"vorbis":return Hi;case"flac":return rf;case"ac3":return nf;case"eac3":return sf;case"dts":return af}if(e)switch(r){case"pcm-s24":return dt;case"pcm-s24be":return dt;case"pcm-s32":return dt;case"pcm-s32be":return dt;case"pcm-f32":return dt;case"pcm-f32be":return dt;case"pcm-f64":return dt;case"pcm-f64be":return dt}else switch(r){case"pcm-s16":return Ue;case"pcm-s16be":return Ue;case"pcm-s24":return Ue;case"pcm-s24be":return Ue;case"pcm-s32":return Ue;case"pcm-s32be":return Ue;case"pcm-f32":return Ue;case"pcm-f32be":return Ue;case"pcm-f64":return Ue;case"pcm-f64be":return Ue}return null},Df={webvtt:"wvtt"},zf={webvtt:cf},ec=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 gn{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 He extends Br{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 qi=2**16,ji=2**32;class $i extends He{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(qi,{maxByteLength:ji})}catch{this._buffer=new ArrayBuffer(qi),this._supportsResize=!1}else this._buffer=new ArrayBuffer(qi);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>ji)throw new Error(`ArrayBuffer exceeded maximum size of ${ji} 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 uh extends He{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _close(){}}class Nf extends He{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 Ki{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 Oe=57600,Uf=2082844800,Vf=r=>{const e={},t=r.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},J=(r,e,t=!0)=>{const i=r*e;return t?Math.round(i):i};class Wf extends qo{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new $i,this.auxWriter=new gn(this.auxTarget,!1),this.auxBoxWriter=new Ur(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=oe(),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 ic,this.isCmaf=t instanceof ga,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof ga?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 $i),this.boxWriter=new Ur(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof $i?"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 gn(i,!0);n.start(),this.initWriter=n,this.initBoxWriter=new Ur(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(Id({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=Vr(!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;Nn(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=ci(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=Tc(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=ui(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=vc(h),a=!0}const o=mc(1/(e.metadata.frameRate??Oe),1e6).den,c=s.displayAspectWidth,l=s.displayAspectHeight,u=c===void 0||l===void 0?{num:1,den:1}
2:rr({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;Un(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=ot(Te.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=St[c.samplingFrequencyIndex],u=ar[c.channelConfiguration];if(l===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");s.description=_n({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&&me.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;Ka(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=[...Fr(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=vn(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=ot(Te.tempFromBytes(a));if(!u)throw new Error("Expected ADTS frame, didn't get one.");const d=u.crcCheck===null?Er:bt;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=$e(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=J(i,e.timescale);if(i=n/e.timescale,n>0){const{sampleSize:s,silentValue:a}=$e(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=If();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;Jr.lastIndex=0;const d=Jr.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=_f(u.notes);this.auxBoxWriter.writeBox(m)}const p=Ef(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:J(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=J(a.duration,e.timescale);n+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleC
2ount:n,sampleDelta:1});else{const s=ee(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=J(s.timestamp-s.decodeTimestamp,e.timescale),o=J(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){g(e.lastSample);const c=J(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=ee(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=ee(e.compositionTimeOffsetTable);g(d),d.sampleCompositionTimeOffset===a?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=J(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=J(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+J(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||ee(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=pr(this);if(h.writeBox(p),this.formatOptions.onMoov){const{data:m,start:k}=h.writer.stopTrackingWrites();this.formatOptions.onMoov(m,k)}if(this.isCmaf){g(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Ur(this.writer);const m=this.boxWriter.measureBox(ca()),k=this.boxWriter.measureBox(la(this,0));this.segmentHeaderSize=m+k,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=da(i,t),s=this.writer.getPos(),a=s+this.boxWriter.measureBox(n);let o=a+rt,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+=vt-rt;this.formatOptions.onMoof&&this.writer.startTrackingWrites();const d=da(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=Vr(u);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(a+(u?vt:rt));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=pr(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=Vr(!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=Vr(!1);let t;for(let n=0;n<2;n++){const s=pr(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=pr(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(ca()),this.boxWriter.writeBox(la(this,t))}else{const t=this.writer.getPos(),i=xf(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=pr(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(Ed(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()}}const Lf=-32768,Hf=2**15-1,ha="Mediabunny",ma=6,pa=5,qf={video:1,audio:2,subtitle:17};class jf extends qo{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=oe(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=new Map,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new _l(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush();for(const t of this.output.tracks)t.isVideoTrack()&&t.metadata.decoderConfig?this.getVideoTrackData(t,t.metadata.primingPacket??null,{decoderConfig:t.metadata.decoderConfig}):t.isAudioTrack()&&t.metadata.decoderConfig&&this.getAudioTrackData(t,t.metadata.primingPacket??null,{decoderConfig:t.metadata.decoderConfig});e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();const e={id:x.EBML,data:[{id:x.EBMLVersion,data:1},{id:x.EBMLReadVersion,data:1},{id:x.EBMLMaxIDLength,data:4},{id:x.EBMLMaxSizeLength,data:8},{id:x.DocType,data:this.format instanceof ya?"webm":"matroska"},{id:x.DocTypeVersion,data:2},{id:x.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){const{data:t,start:i}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(t,i)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;const t=new Uint8Array([28,83,187,107]),i=new Uint8Array([21,73,169,102]),n=new Uint8Array([22,84,174,107]),s=new Uint8Array([25,65,164,105]),a=new Uint8Array([18,84,195,103]),o={id:x.SeekHead,data:[{id:x.Seek,data:[{id:x.SeekID,data:t},{id:x.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:x.Seek,data:[{id:x.SeekID,data:i},{id:x.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:x.Seek,data:[{id:x.SeekID,data:n},{id:x.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:x.Seek,data:[{id:x.SeekID,data:s},{id:x.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:x.Seek,data:[{id:x.SeekID,data:a},{id:x.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=o}createSegmentInfo(){const e={id:x.Duration,data:new on(0)};this.segmentDuration=e;const t={id:x.Info,data:[{id:x.TimestampScale,data:1e6},{id:x.MuxingApp,data:ha},{id:x.WritingApp,data:ha},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){const e={id:x.Tracks,data:[]};this.tracksElement=e;for(const t of this.trackDatas){let i=ye[t.track.source._codec];g(i),t.type==="audio"&&t.track.source._codec==="dts"&&(t.info.decoderConfig.codec==="dtse"?i="A_DTS/EXPRESS":t.info.decoderConfig.codec==="dtsl"&&(i="A_DTS/LOSSLESS"));let n=0;if(t.type==="audio"&&t.track.source._codec==="opus"){n=1e6*80;const s=t.info.decoderConfig.description;if(s){const a=fe(s),o=Fn(a);n=Math.round(1e9*(o.preSkip/Rr))}}e.data.push({id:x.TrackEntry,data:[{id:x.TrackNumber,data:t.track.id},{id:x.TrackUID,data:t.track.id},{id:x.TrackType,data:qf[t.type]},t.track.metadata.disposition?.default===!1?{id:x.FlagDefault,data:0}:null,t.track.metadata.disposition?.forced?{id:x.FlagForced,data:1}:null,t.track.metadata.disposition?.hearingImpaired?{id:x.FlagHearingImpaired,data:1}:null,t.track.metadata.disposition?.visuallyImpaired?{id:x.FlagVisualImpaired,data:1}:null,t.track.metadata.disposition?.original?{id:x.FlagOriginal,data:1}:null,t.track.metadata.disposition?.commentary?{id:x.FlagCommentary,data:1}:null,{id:x.FlagLacing,data:0},{id:x.Language,data:t.track.metadata.languageCode??he},{id:x.CodecID,data:i}
2,t.codecPrivate?{id:x.CodecPrivate,data:fe(t.codecPrivate)}:null,{id:x.CodecDelay,data:0},{id:x.SeekPreRoll,data:n},t.track.metadata.name!==void 0?{id:x.Name,data:new ft(t.track.metadata.name)}:null,t.type==="video"?this.videoSpecificTrackInfo(t):null,t.type==="audio"?this.audioSpecificTrackInfo(t):null,t.type==="subtitle"?this.subtitleSpecificTrackInfo(t):null]})}}videoSpecificTrackInfo(e){const{frameRate:t,rotation:i}=e.track.metadata,n=[t?{id:x.DefaultDuration,data:1e9/t}:null],s=i?ei(-i):0,a=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,o=e.info.decoderConfig.colorSpace,c={id:x.Video,data:[{id:x.PixelWidth,data:e.info.width},{id:x.PixelHeight,data:e.info.height},a?{id:x.DisplayWidth,data:e.info.aspectRatio.num}:null,a?{id:x.DisplayHeight,data:e.info.aspectRatio.den}:null,a?{id:x.DisplayUnit,data:3}:null,e.info.alphaMode?{id:x.AlphaMode,data:1}:null,ba(o)?null:{id:x.Colour,data:[{id:x.MatrixCoefficients,data:o?.matrix!=null?Ut[o.matrix]:2},{id:x.TransferCharacteristics,data:o?.transfer!=null?Nt[o.transfer]:2},{id:x.Primaries,data:o?.primaries!=null?zt[o.primaries]:2},{id:x.Range,data:o?.fullRange!=null?o.fullRange?2:1:0}]},s?{id:x.Projection,data:[{id:x.ProjectionType,data:0},{id:x.ProjectionPoseRoll,data:new an((s+180)%360-180)}]}:null]};return n.push(c),n}audioSpecificTrackInfo(e){const t=me.includes(e.track.source._codec)?$e(e.track.source._codec):null;return[{id:x.Audio,data:[{id:x.SamplingFrequency,data:new an(e.info.sampleRate)},{id:x.Channels,data:e.info.numberOfChannels},t?{id:x.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[]}maybeCreateTags(){const e=[],t=(s,a)=>{e.push({id:x.SimpleTag,data:[{id:x.TagName,data:new ft(s)},typeof a=="string"?{id:x.TagString,data:new ft(a)}:{id:x.TagBinary,data:a}]})},i=this.output._metadataTags,n=new Set;for(const{key:s,value:a}of xn(i))switch(s){case"title":t("TITLE",a),n.add("TITLE");break;case"description":t("DESCRIPTION",a),n.add("DESCRIPTION");break;case"artist":t("ARTIST",a),n.add("ARTIST");break;case"album":t("ALBUM",a),n.add("ALBUM");break;case"albumArtist":t("ALBUM_ARTIST",a),n.add("ALBUM_ARTIST");break;case"genre":t("GENRE",a),n.add("GENRE");break;case"comment":t("COMMENT",a),n.add("COMMENT");break;case"lyrics":t("LYRICS",a),n.add("LYRICS");break;case"date":t("DATE",a.toISOString().slice(0,10)),n.add("DATE");break;case"trackNumber":{const o=i.tracksTotal!==void 0?`${a}/${i.tracksTotal}`:a.toString();t("PART_NUMBER",o),n.add("PART_NUMBER")}break;case"discNumber":{const o=i.discsTotal!==void 0?`${a}/${i.discsTotal}`:a.toString();t("DISC",o),n.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:Ee(s)}if(i.raw)for(const s in i.raw){const a=i.raw[s];a==null||n.has(s)||(typeof a=="string"||a instanceof Uint8Array)&&t(s,a)}e.length!==0&&(this.tagsElement={id:x.Tags,data:[{id:x.Tag,data:[{id:x.Targets,data:[{id:x.TargetTypeValue,data:50},{id:x.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){const e=this.output._metadataTags,t=[],i=new Set,n=e.images??[];for(const s of n){let a=s.name;a===void 0&&(a=(s.kind==="coverFront"?"cover":s.kind==="coverBack"?"back":"image")+(gc(s.mimeType)??""));let o;for(;;){o=0n;for(let c=0;c<8;c++)o<<=8n,o|=BigInt(Math.floor(Math.random()*256));if(o!==0n&&!i.has(o))break}i.add(o),t.push({id:x.AttachedFile,data:[s.description!==void 0?{id:x.FileDescription,data:new ft(s.description)}:null,{id:x.FileName,data:new ft(a)},{id:x.FileMediaType,data:s.mimeType},{id:x.FileData,data:s.data},{id:x.FileUID,data:o}]})}for(const[s,a]of Object.entries(e.raw??{}))!(a instanceof In)||!/^\d+$/.test(s)||n.find(c=>
2c.mimeType===a.mimeType&&Pa(c.data,a.data))||t.push({id:x.AttachedFile,data:[a.description!==void 0?{id:x.FileDescription,data:new ft(a.description)}:null,{id:x.FileName,data:new ft(a.name??"")},{id:x.FileMediaType,data:a.mimeType??""},{id:x.FileData,data:a.data},{id:x.FileUID,data:BigInt(s)}]});t.length!==0&&(this.attachmentsElement={id:x.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const e={id:x.Segment,size:this.format._options.appendOnly?-1:ma,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){const{data:t,start:i}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(t,i)}}createCues(){this.cues={id:x.Cues,data:[]}}get segmentDataOffset(){return g(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}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 uo({isWebM:this.format instanceof ya,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(l=>l.track===e);if(n)return n;Nn(i,e.source._codec),g(i),g(i.decoderConfig),g(i.decoderConfig.codedWidth!==void 0),g(i.decoderConfig.codedHeight!==void 0);const s=i.decoderConfig.displayAspectWidth,a=i.decoderConfig.displayAspectHeight,o=s===void 0||a===void 0?null:rr({num:s,den:a}),c={track:e,type:"video",info:{width:i.decoderConfig.codedWidth,height:i.decoderConfig.codedHeight,aspectRatio:o,decoderConfig:i.decoderConfig,alphaMode:t?!!t.sideData.alpha:null},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:i.decoderConfig.description??null,closed:!1};return e.source._codec==="vp9"?c.codecPrivate=new Uint8Array(il(c.info.decoderConfig.codec)):e.source._codec==="av1"?c.codecPr
2ivate=new Uint8Array(qa(c.info.decoderConfig.codec)):e.source._codec==="prores"&&(c.codecPrivate=be.encode(i.decoderConfig.codec)),this.trackDatas.push(c),this.trackDatas.sort((l,u)=>l.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t,i){const n=this.trackDatas.find(c=>c.track===e);if(n)return n;Un(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=ot(Te.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=St[c.samplingFrequencyIndex],u=ar[c.channelConfiguration];if(l===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");s.description=_n({objectType:c.objectType,outputSampleRate:l,outputNumberOfChannels:u}),a=!0}const o={track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:s,requiresAdtsStripping:a},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:s.description??null,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;Ka(t),g(t),g(t.config);const n={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:be.encode(t.config.description),closed:!1};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);s.info.alphaMode??=!!t.sideData.alpha;let a=t.data;if(e.source._codec==="prores"){if(a.byteLength<8)throw new Error("ProRes packet too small, expected at least 8 bytes.");a=a.subarray(8)}const o=t.type==="key";this.validateTimestamp(s.track,t.timestamp,o);let c=t.timestamp,l=t.duration;e.metadata.frameRate!==void 0&&(c=tr(c,e.metadata.frameRate),l=tr(l,e.metadata.frameRate));const u=s.info.alphaMode?t.sideData.alpha??null:null,d=this.createInternalChunk(a,c,l,t.type,u);e.source._codec==="vp9"&&this.fixVP9ColorSpace(s,d),s.chunkQueue.push(d),await this.interleaveChunks()}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 l=ot(Te.tempFromBytes(a));if(!l)throw new Error("Expected ADTS frame, didn't get one.");const u=l.crcCheck===null?Er:bt;a=a.subarray(u)}const o=t.type==="key";this.validateTimestamp(s.track,t.timestamp,o);const c=this.createInternalChunk(a,t.timestamp,t.duration,t.type);s.chunkQueue.push(c),await this.interleaveChunks()}finally{n()}}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);let a=t.text;const o=Math.round(t.timestamp*1e3);Jr.lastIndex=0,a=a.replace(Jr,d=>{const h=Cd(d.slice(1,-1))-o;return`<${jo(h)}>`});const c=be.encode(a),l=`${t.settings??""} 3${t.identifier??""} 4${t.notes??""}`,u=this.createInternalChunk(c,t.timestamp,t.duration,"key",l.trim()?be.encode(l):null);s.chunkQueue.push(u),await this.interleaveChunks()}finally{n()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let t=null,i=1/0;for(const s of this.trackDatas){if(!e&&s.chunkQueue.length===0&&!s.closed)break e;s.chunkQueue.length>0&&s.chunkQueue[0].timestamp<i&&(t=s,i=s.chunkQueue[0].timestamp)}if(!t)break;const n=t.chunkQueue.shift();this.writeBlock(t,n)}e||await this.writer.flush()}}fixVP9ColorSpace(e,t){if(t.type!=="key"||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;const i=new K(t.data);i.skipBits(2);const n=i.readBits(1),a=(i.readBits(1)<<1)+n;if(a===3&&i.skipBits(1),i.readBits(1)||i.readBits(1)!==0||(i.skipBits(2),i.readBits(24)!==4817730))return;a>=2&&i.skipBits(1);const u={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];nc(t.data,i.pos,i.pos+3,u)}createInternalChunk(e,t,i,n,s=null){return{data:e,type:n,timestamp:t,duration:i,additions:s}}writeBlock(e,t){this.segment||this.createSegment();const i=Math.round(1e3*t.timestamp),n=this.trackDatas.every(d=>
4{if(e===d)return t.type==="key";const f=d.chunkQueue[0];return f?f.type==="key":d.closed});let s=!1;if(!this.currentCluster)s=!0;else{g(this.currentClusterStartMsTimestamp!==null),g(this.currentClusterMaxMsTimestamp!==null);const d=i-this.currentClusterStartMsTimestamp;s=n&&i>this.currentClusterMaxMsTimestamp&&d>=1e3*(this.format._options.minimumClusterDuration??1)||d>Hf}s&&this.createNewCluster(i);const a=i-this.currentClusterStartMsTimestamp;if(a<Lf)return;const o=new Uint8Array(4),c=new DataView(o.buffer);c.setUint8(0,128|e.track.id),c.setInt16(1,a,!1);const l=Math.round(1e3*t.duration);if(!!t.additions||e.type==="subtitle"){const d={id:x.BlockGroup,data:[{id:x.Block,data:[o,t.data]},t.type==="delta"?{id:x.ReferenceBlock,data:new ao(e.lastWrittenMsTimestamp-i)}:null,t.additions?{id:x.BlockAdditions,data:[{id:x.BlockMore,data:[{id:x.BlockAddID,data:1},{id:x.BlockAdditional,data:t.additions}]}]}:null,l>0?{id:x.BlockDuration,data:l}:null]};this.ebmlWriter.writeEBML(d)}else{c.setUint8(3,+(t.type==="key")<<7);const d={id:x.SimpleBlock,data:[o,t.data]};this.ebmlWriter.writeEBML(d)}this.startTimestamp=Math.min(this.startTimestamp,i),this.endTimestamp=Math.max(this.endTimestamp,i+l),e.lastWrittenMsTimestamp=i,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:i}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:x.Cluster,size:this.format._options.appendOnly?-1:pa,data:[{id:x.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(g(this.currentCluster),!this.format._options.appendOnly){const n=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),s=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(n,pa),this.writer.seek(s)}if(this.format._options.onCluster){g(this.currentClusterStartMsTimestamp!==null);const{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onCluster(n,s,this.currentClusterStartMsTimestamp/1e3)}const e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,t=new Map;for(const[n,{firstMsTimestamp:s}]of this.trackDatasInCurrentCluster)t.has(s)||t.set(s,[]),t.get(s).push(n);const i=[...t.entries()].sort((n,s)=>n[0]-s[0]);for(const[n,s]of i)g(this.cues),this.cues.data.push({id:x.CuePoint,data:[{id:x.CueTime,data:n},...s.map(a=>({id:x.CueTrackPositions,data:[{id:x.CueTrack,data:a.track.id},{id:x.CueClusterPosition,data:e}]}))]})}async onTrackClose(e){const t=await this.mutex.acquire(),i=this.trackDatas.find(n=>n.track===e);i&&(i.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)t.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),g(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){const t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,ma);const i=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new on(i),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),g(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}}class $f{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),k=h-p;for(let y=0;y<this.targetNumberOfChannels;y++){let w=0,b=0;p>=0&&p<e.numberOfFrames&&(w=this.channelMixer(n,p,y)),m>=0&&m<e.numberOfFrames&&(b=this.channelMixer(n,m,y));const S=w+k*(b-w),T=u*this.targetNumberOfChannels+y;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 de({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 Kf=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},Gf=(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)}
4if(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 wi 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 kn=(r,e)=>{if(r.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class dh extends wi{constructor(e){super(e)}add(e,t){if(!(e instanceof Y))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(),kn(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}}class tc{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
4dedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new ii,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 ue?a.push(o):typeof VideoFrame<"u"&&o instanceof VideoFrame?a.push(new ue(o)):a.push(new ue(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 ue&&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=G(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 Xf);
4const{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=Kf(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{Gf(a)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const t=pi(this.encodingConfig.quality,this.encodingConfig.bitrate);g(t!==void 0);const i=Fo({...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=Uo.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(ni("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=Do(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 Y))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.");kn(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 k={};if(p){const T=new Uint8Array(p.byteLength);p.copyTo(T),k.alpha=T}let y=Y.fromEncodedChunk(h,k);const w=G(this.preciseTimings,h.timestamp,T=>T.microsecondTimestamp),b=w!==-1?this.preciseTimings[w]:null;let S=null;this.emittedEncoderPackets===0&&y.type==="delta"&&m?.decoderConfig&&(S=di(this.encodingConfig.codec,m.decoderConfig,y.data)),(b&&b.microsecondTimestamp===h.timestamp||S!==null)&&(y=y.clone({timestamp:b?.timestampIsValid?b.timestamp:void 0,duration:b?.durationIsValid?b.duration:void 0,type:S??void 0})),kn(this.source._connectedTrack,y),this.encodingConfig.onEncodedPacket?.(y,m),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,y,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==="
4key"}),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 k=o.shift();for(g(k!==void 0),d(k.chunk,p,k.meta),l++;c.length>0&&c[0]===l;){c.shift();const y=o.shift();g(y!==void 0),d(y.chunk,null,y.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 Ia(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 Gi=null;class Xf{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!Gi){const n=new Blob([`(${Qf.toString()})()`],{type:"application/javascript"});Gi=URL.createObjectURL(n)}this.worker=new Worker(Gi),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=oe();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 Qf=()=>{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 w=0,b=3;w<u;w++,b+=4)p[w]=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}),k={format:"I420",codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0,transfer:[p.buffer]},y=new VideoFrame(p,k);return{colorFrame:m,alphaFrame:y}},n=(s,a,o)=>{const c=o.visibleRect?.width??o.codedWidth,l=o.visibleRect?.height??o.coded
4Height,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,k=h*p,y=m*f,w=k*f,b=m*f,S=y+w*2,T=a.replace("A",""),P=Math.ceil(c/2),E=Math.ceil(l/2),I=P*E,C=I*f,_=b+2*C,B=new Uint8Array(_),v=S;B.set(s.subarray(v,v+b),0);const O=b,D=u?512:d?2048:128;f===1?B.fill(D,O):new Uint16Array(B.buffer,O,2*I).fill(D);const V=u?"I420P10":d?"I420P12":"I420",L=new VideoFrame(s.subarray(0,S),{format:T,codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0}),te={format:V,codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0,transfer:[B.buffer]},pe=new VideoFrame(B,te);return{colorFrame:L,alphaFrame:pe}}};class fh extends wi{constructor(e){Ao(e),super(e.codec),this._encoder=new tc(this,e)}add(e,t){if(!(e instanceof ue))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class hh extends wi{constructor(e,t){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");Ao(t),super(t.codec),this._encoder=new tc(this,t),this._canvas=e}add(e,t=0,i){if(!Number.isFinite(e)||e<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(t)||t<0)throw new TypeError("duration must be a non-negative number.");const n=new ue(this._canvas,{timestamp:e,duration:t});return this._encoder.add(n,!0,i)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class bi extends Qn{constructor(e){if(super(),this._connectedTrack=null,!De.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${De.join(", ")}.`);this._codec=e}}class mh extends bi{constructor(e){super(e)}add(e,t){if(!(e instanceof Y))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 rc{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 ii,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 $f({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&&Yu(e.format)!==i.transform.sampleFormat){const n=Ju(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 de))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 de&&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;
4{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 de({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),k=new DataView(m);c.push({frameCount:h,view:k})}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 k=0;k<p;k++)this.writeOutputValue(m,(k*i+f)*this.outputSampleSize,u[h*o+k])}}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,k=f*o,y=new Y(new Uint8Array(m),"key",a+k/s,h/s);this.encodingConfig.onEncodedPacket?.(y,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,y,d)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const{numberOfChannels:t,sampleRate:i}=e,n=pi(this.encodingConfig.quality,this.encodingConfig.bitrate),s=Oo({numberOfChannels:t,sampleRate:i,...this.encodingConfig,quality:n});this.encodingConfig.onEncoderConfig?.(s);const a=Vo.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 Y))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(me.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error(ni("AudioEncoder"));let o;try{o=(await AudioEncoder.isConfigSupported(s)).supported??!1}catch{o=!1}if(!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=En(fe(u.decoderConfig.description)).objectType===0,f){const h=Number(ee(s.codec.split(".")));u.decoderConfig.description=_n({objectType:h,outputNumberOfChannels:u.decoderConfig.numberOfChannels,outputSampleRate:u.decoderConfig.sampleRate})}}let d=Y.fromEncodedChunk(l);d=d.clone({timestamp:tr(d.timestamp,s.sampleRate),duration:l.duration!=null?tr(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=>
4{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}=$e(e);switch(this.outputSampleSize=i,i){case 1:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint8(a,ae((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(s,a,o)=>{s.setInt8(a,ae(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(s,a,o)=>{const c=ae(Math.floor(o*32767),-32768,32767);s.setUint8(a,id(c))}:t==="alaw"?this.writeOutputValue=(s,a,o)=>{const c=ae(Math.floor(o*32767),-32768,32767);s.setUint8(a,sd(c))}:g(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint16(a,ae((o+1)*32767.5,0,65535),n):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt16(a,ae(Math.round(o*32767),-32768,32767),n):g(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(s,a,o)=>Tn(s,a,ae((o+1)*83886075e-1,0,16777215),n):t==="signed"?this.writeOutputValue=(s,a,o)=>uc(s,a,ae(Math.round(o*8388607),-8388608,8388607),n):g(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint32(a,ae((o+1)*21474836475e-1,0,4294967295),n):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt32(a,ae(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:Ee(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 ph extends bi{constructor(e){Ro(e),super(e.codec),this._encoder=new rc(this,e)}add(e){if(!(e instanceof de))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class gh extends bi{constructor(e){Ro(e),super(e.codec),this._accumulatedTime=0,this._encoder=new rc(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const t=de._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(const i of t)await this._encoder.add(i,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Yf extends Qn{constructor(e){if(super(),this._connectedTrack=null,!Dt.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Dt.join(", ")}.`);this._codec=e}}class Yn{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>_e.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>De.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Dt.includes(e))}_codecUnsupportedHint(e){return""}_isFragmentedIsobmff(){return!1}}class Zn extends Yn{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&&(!sr(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");
4if(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 Wf(e,this)}_isFragmentedIsobmff(){return this._options.fastStart==="fragmented"}}class Zf extends Zn{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[..._e,...fi,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Dt]}_codecUnsupportedHint(e){return new ic().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class ga extends Zn{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[..._e,...fi,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Dt]}}class ic extends Zn{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[..._e,...De]}_codecUnsupportedHint(e){return new Zf().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}class ka extends Yn{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(e.minimumClusterDuration!==void 0&&(!sr(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(e.onCluster!==void 0&&typeof e.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new jf(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:0,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[..._e,...fi,...me.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...Dt]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}}class ya extends ka{constructor(e){super(e)}getSupportedCodecs(){return[..._e.filter(e=>["vp8","vp9","av1"].includes(e)),...De.filter(e=>["opus","vorbis"].includes(e)),...Dt]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new ka().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}}const wa=["video","audio","subtitle"];class Dr{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 Dr))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 Dr{constructor(e,t,i,n){super(e,t,"video",i,n)}}class eh extends Dr{constructor(e,t,i,n){super(e,t,"audio",i,n)}}class th extends Dr{constructor(e,t,i,n){super(e,t,"subtitle",i,n)}}class vr{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof vr))throw new TypeError("other must be an OutputTrackGroup.");
4if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}}const Xi=r=>{if(!r||typeof r!="object")throw new TypeError("metadata must be an object.");if(r.languageCode!==void 0&&!Sn(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&&wc(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 vr)&&(!Array.isArray(r.group)||r.group.some(e=>!(e instanceof vr))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class kh extends Br{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 vr,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new nr,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 Yn))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof He||e.target instanceof Ki))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof He&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof He)&&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 He&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){g(this._target instanceof Ki);const t=this._target.getTarget(e),i=n=>{if(!(n instanceof He))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 Ki);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})}async _getInitTarget(){if(g(this._initTarget!==null),this._initTarget instanceof He)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 He)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 gn(t,typeof e=="boolean"?e:e(t));return i.start(),i})()}addVideoTrack(e,t={}){if(!(e instanceof wi))throw new TypeError("source must be a VideoSource.");if(Xi(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&&Nn({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof Y))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 bi))throw new TypeError("source must be an AudioSource.");if(Xi(t),t.decoderConfig!==void 0&&Un({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof Y))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 Yf))throw new TypeError("source must be a SubtitleSource.");Xi(t);const i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new th(this.tracks.length+1,this,e,i))}setMetadataTags(e){if(yc(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.");
4if(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))}else 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 wa){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 wa){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()}})()}}export{ph as A,ih as B,hh as C,rd as D,dh as E,gh as F,td as G,Kn as I,H as L,Zf as M,uh as N,kh as O,Ie as Q,fh as V,ya as W,Ee as a,g as b,Qs as c,rh as d,gi as e,ch as f,oh as g,mh as h,Sn as i,ah as j,fi as k,lh as l,pt as m,ei as n,de as o,oe as p,ae as q,pi as r,vr as s,_e as t,mn as u,yc as v,De as w,nh as x,$i as y,sh as z};
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.